summaryrefslogtreecommitdiff
path: root/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
blob: 9dfca4deebbd61e40a544339db100867bd7baf53 (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
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
/*
 * 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.
 */

package com.android.server.devicepolicy;

import static android.Manifest.permission.BIND_DEVICE_ADMIN;
import static android.Manifest.permission.LOCK_DEVICE;
import static android.Manifest.permission.MANAGE_CA_CERTIFICATES;
import static android.Manifest.permission.MANAGE_DEFAULT_APPLICATIONS;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_ACROSS_USERS;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_AIRPLANE_MODE;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_APPS_CONTROL;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_APP_RESTRICTIONS;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_AUDIO_OUTPUT;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_AUTOFILL;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_BLUETOOTH;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_CALLS;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_CAMERA;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_CERTIFICATES;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_COMMON_CRITERIA_MODE;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_DEBUGGING_FEATURES;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_DEFAULT_SMS;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_DISPLAY;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_FACTORY_RESET;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_FUN;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_INPUT_METHODS;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_KEYGUARD;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCALE;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCATION;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCK;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCK_TASK;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_MICROPHONE;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_MOBILE_NETWORK;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_MODIFY_USERS;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_MTE;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_NEARBY_COMMUNICATION;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_PACKAGE_STATE;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_PHYSICAL_MEDIA;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_PRINTING;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_PROFILES;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_PROFILE_INTERACTION;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_RESET_PASSWORD;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_RESTRICT_PRIVATE_DNS;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_RUN_IN_BACKGROUND;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SAFE_BOOT;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SCREEN_CAPTURE;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SCREEN_CONTENT;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SECURITY_LOGGING;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SMS;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_STATUS_BAR;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SYSTEM_DIALOGS;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SYSTEM_UPDATES;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_THREAD_NETWORK;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_TIME;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_USB_FILE_TRANSFER;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_VPN;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_WALLPAPER;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_WIFI;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_WINDOWS;
import static android.Manifest.permission.MANAGE_DEVICE_POLICY_WIPE_DATA;
import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
import static android.Manifest.permission.MASTER_CLEAR;
import static android.Manifest.permission.QUERY_ADMIN_POLICY;
import static android.Manifest.permission.REQUEST_PASSWORD_COMPLEXITY;
import static android.Manifest.permission.SET_TIME;
import static android.Manifest.permission.SET_TIME_ZONE;
import static android.accessibilityservice.AccessibilityServiceInfo.FEEDBACK_ALL_MASK;
import static android.accounts.AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION;
import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
import static android.app.AppOpsManager.MODE_ALLOWED;
import static android.app.AppOpsManager.MODE_DEFAULT;
import static android.app.AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION;
import static android.app.AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_DISMISSIBLE_NOTIFICATIONS;
import static android.app.AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_HIBERNATION;
import static android.app.AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_POWER_RESTRICTIONS;
import static android.app.AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_SUSPENSION;
import static android.app.admin.DeviceAdminInfo.HEADLESS_DEVICE_OWNER_MODE_AFFILIATED;
import static android.app.admin.DeviceAdminInfo.USES_POLICY_FORCE_LOCK;
import static android.app.admin.DeviceAdminInfo.USES_POLICY_WIPE_DATA;
import static android.app.admin.DeviceAdminReceiver.ACTION_COMPLIANCE_ACKNOWLEDGEMENT_REQUIRED;
import static android.app.admin.DeviceAdminReceiver.EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE;
import static android.app.admin.DevicePolicyIdentifiers.AUTO_TIMEZONE_POLICY;
import static android.app.admin.DevicePolicyManager.ACTION_CHECK_POLICY_COMPLIANCE;
import static android.app.admin.DevicePolicyManager.ACTION_DEVICE_FINANCING_STATE_CHANGED;
import static android.app.admin.DevicePolicyManager.ACTION_DEVICE_POLICY_RESOURCE_UPDATED;
import static android.app.admin.DevicePolicyManager.ACTION_MANAGED_PROFILE_PROVISIONED;
import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE;
import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE;
import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_USER;
import static android.app.admin.DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED;
import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
import static android.app.admin.DevicePolicyManager.DELEGATION_BLOCK_UNINSTALL;
import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_SELECTION;
import static android.app.admin.DevicePolicyManager.DELEGATION_ENABLE_SYSTEM_APP;
import static android.app.admin.DevicePolicyManager.DELEGATION_INSTALL_EXISTING_PACKAGE;
import static android.app.admin.DevicePolicyManager.DELEGATION_KEEP_UNINSTALLED_PACKAGES;
import static android.app.admin.DevicePolicyManager.DELEGATION_NETWORK_LOGGING;
import static android.app.admin.DevicePolicyManager.DELEGATION_PACKAGE_ACCESS;
import static android.app.admin.DevicePolicyManager.DELEGATION_PERMISSION_GRANT;
import static android.app.admin.DevicePolicyManager.DELEGATION_SECURITY_LOGGING;
import static android.app.admin.DevicePolicyManager.DEVICE_OWNER_TYPE_DEFAULT;
import static android.app.admin.DevicePolicyManager.DEVICE_OWNER_TYPE_FINANCED;
import static android.app.admin.DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
import static android.app.admin.DevicePolicyManager.EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION;
import static android.app.admin.DevicePolicyManager.EXEMPT_FROM_DISMISSIBLE_NOTIFICATIONS;
import static android.app.admin.DevicePolicyManager.EXEMPT_FROM_HIBERNATION;
import static android.app.admin.DevicePolicyManager.EXEMPT_FROM_POWER_RESTRICTIONS;
import static android.app.admin.DevicePolicyManager.EXEMPT_FROM_SUSPENSION;
import static android.app.admin.DevicePolicyManager.EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE;
import static android.app.admin.DevicePolicyManager.EXTRA_RESOURCE_IDS;
import static android.app.admin.DevicePolicyManager.EXTRA_RESOURCE_TYPE;
import static android.app.admin.DevicePolicyManager.EXTRA_RESOURCE_TYPE_DRAWABLE;
import static android.app.admin.DevicePolicyManager.EXTRA_RESOURCE_TYPE_STRING;
import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO;
import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI;
import static android.app.admin.DevicePolicyManager.ID_TYPE_INDIVIDUAL_ATTESTATION;
import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID;
import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL;
import static android.app.admin.DevicePolicyManager.LEAVE_ALL_SYSTEM_APPS_ENABLED;
import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK;
import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS;
import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_HOME;
import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_KEYGUARD;
import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS;
import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_SYSTEM_INFO;
import static android.app.admin.DevicePolicyManager.NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
import static android.app.admin.DevicePolicyManager.NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
import static android.app.admin.DevicePolicyManager.OPERATION_SAFETY_REASON_NONE;
import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_HIGH;
import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_LOW;
import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_MEDIUM;
import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_NONE;
import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC;
import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC;
import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK;
import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_MANAGED;
import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_NUMERIC;
import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX;
import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_SOMETHING;
import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
import static android.app.admin.DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
import static android.app.admin.DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED;
import static android.app.admin.DevicePolicyManager.PERSONAL_APPS_NOT_SUSPENDED;
import static android.app.admin.DevicePolicyManager.PERSONAL_APPS_SUSPENDED_EXPLICITLY;
import static android.app.admin.DevicePolicyManager.PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT;
import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_OFF;
import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME;
import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_UNKNOWN;
import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_SET_NO_ERROR;
import static android.app.admin.DevicePolicyManager.PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
import static android.app.admin.DevicePolicyManager.STATE_USER_SETUP_FINALIZED;
import static android.app.admin.DevicePolicyManager.STATE_USER_UNMANAGED;
import static android.app.admin.DevicePolicyManager.STATUS_ACCOUNTS_NOT_EMPTY;
import static android.app.admin.DevicePolicyManager.STATUS_CANNOT_ADD_MANAGED_PROFILE;
import static android.app.admin.DevicePolicyManager.STATUS_DEVICE_ADMIN_NOT_SUPPORTED;
import static android.app.admin.DevicePolicyManager.STATUS_HAS_DEVICE_OWNER;
import static android.app.admin.DevicePolicyManager.STATUS_HAS_PAIRED;
import static android.app.admin.DevicePolicyManager.STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED;
import static android.app.admin.DevicePolicyManager.STATUS_MANAGED_USERS_NOT_SUPPORTED;
import static android.app.admin.DevicePolicyManager.STATUS_NONSYSTEM_USER_EXISTS;
import static android.app.admin.DevicePolicyManager.STATUS_NOT_SYSTEM_USER;
import static android.app.admin.DevicePolicyManager.STATUS_OK;
import static android.app.admin.DevicePolicyManager.STATUS_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS;
import static android.app.admin.DevicePolicyManager.STATUS_SYSTEM_USER;
import static android.app.admin.DevicePolicyManager.STATUS_USER_HAS_PROFILE_OWNER;
import static android.app.admin.DevicePolicyManager.STATUS_USER_NOT_RUNNING;
import static android.app.admin.DevicePolicyManager.STATUS_USER_SETUP_COMPLETED;
import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE;
import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
import static android.app.admin.DevicePolicyManager.WIPE_SILENTLY;
import static android.app.admin.DevicePolicyResources.Strings.Core.LOCATION_CHANGED_MESSAGE;
import static android.app.admin.DevicePolicyResources.Strings.Core.LOCATION_CHANGED_TITLE;
import static android.app.admin.DevicePolicyResources.Strings.Core.NETWORK_LOGGING_MESSAGE;
import static android.app.admin.DevicePolicyResources.Strings.Core.NETWORK_LOGGING_TITLE;
import static android.app.admin.DevicePolicyResources.Strings.Core.NOTIFICATION_WORK_PROFILE_CONTENT_DESCRIPTION;
import static android.app.admin.DevicePolicyResources.Strings.Core.PERSONAL_APP_SUSPENSION_MESSAGE;
import static android.app.admin.DevicePolicyResources.Strings.Core.PERSONAL_APP_SUSPENSION_SOON_MESSAGE;
import static android.app.admin.DevicePolicyResources.Strings.Core.PERSONAL_APP_SUSPENSION_TITLE;
import static android.app.admin.DevicePolicyResources.Strings.Core.PERSONAL_APP_SUSPENSION_TURN_ON_PROFILE;
import static android.app.admin.DevicePolicyResources.Strings.Core.PRINTING_DISABLED_NAMED_ADMIN;
import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_DELETED_FAILED_PASSWORD_ATTEMPTS_MESSAGE;
import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_DELETED_GENERIC_MESSAGE;
import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_DELETED_ORG_OWNED_MESSAGE;
import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_DELETED_TITLE;
import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_TELEPHONY_PAUSED_BODY;
import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_TELEPHONY_PAUSED_TITLE;
import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_TELEPHONY_PAUSED_TURN_ON_BUTTON;
import static android.app.admin.ProvisioningException.ERROR_ADMIN_PACKAGE_INSTALLATION_FAILED;
import static android.app.admin.ProvisioningException.ERROR_PRE_CONDITION_FAILED;
import static android.app.admin.ProvisioningException.ERROR_PROFILE_CREATION_FAILED;
import static android.app.admin.ProvisioningException.ERROR_REMOVE_NON_REQUIRED_APPS_FAILED;
import static android.app.admin.ProvisioningException.ERROR_SETTING_PROFILE_OWNER_FAILED;
import static android.app.admin.ProvisioningException.ERROR_SET_DEVICE_OWNER_FAILED;
import static android.app.admin.ProvisioningException.ERROR_STARTING_PROFILE_FAILED;
import static android.app.admin.flags.Flags.dumpsysPolicyEngineMigrationEnabled;
import static android.app.admin.flags.Flags.policyEngineMigrationV2Enabled;
import static android.content.Intent.ACTION_MANAGED_PROFILE_AVAILABLE;
import static android.content.Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE;
import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
import static android.content.pm.PackageManager.GET_META_DATA;
import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static android.net.ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT;
import static android.net.ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE;
import static android.net.ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING;
import static android.net.ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK;
import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
import static android.provider.DeviceConfig.NAMESPACE_DEVICE_POLICY_MANAGER;
import static android.provider.Settings.Global.PRIVATE_DNS_SPECIFIER;
import static android.provider.Settings.Secure.MANAGED_PROVISIONING_DPC_DOWNLOADED;
import static android.provider.Settings.Secure.USER_SETUP_COMPLETE;
import static android.provider.Telephony.Carriers.DPC_URI;
import static android.provider.Telephony.Carriers.ENFORCE_KEY;
import static android.provider.Telephony.Carriers.ENFORCE_MANAGED_URI;
import static android.provider.Telephony.Carriers.INVALID_APN_ID;
import static android.security.keystore.AttestationUtils.USE_INDIVIDUAL_ATTESTATION;

import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.PROVISIONING_ENTRY_POINT_ADB;
import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_NONE;
import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
import static com.android.server.SystemTimeZone.TIME_ZONE_CONFIDENCE_HIGH;
import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER;
import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER;
import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME;
import static com.android.server.pm.UserManagerInternal.OWNER_TYPE_DEVICE_OWNER;
import static com.android.server.pm.UserManagerInternal.OWNER_TYPE_PROFILE_OWNER;
import static com.android.server.pm.UserManagerInternal.OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE;

import android.Manifest;
import android.Manifest.permission;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.UserIdInt;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManagerInternal;
import android.app.ActivityTaskManager;
import android.app.AlarmManager;
import android.app.AppGlobals;
import android.app.AppOpsManager;
import android.app.AppOpsManager.Mode;
import android.app.BroadcastOptions;
import android.app.IActivityManager;
import android.app.IActivityTaskManager;
import android.app.IApplicationThread;
import android.app.IServiceConnection;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.StatusBarManager;
import android.app.admin.AccountTypePolicyKey;
import android.app.admin.BooleanPolicyValue;
import android.app.admin.BundlePolicyValue;
import android.app.admin.ComponentNamePolicyValue;
import android.app.admin.DeviceAdminInfo;
import android.app.admin.DeviceAdminReceiver;
import android.app.admin.DevicePolicyCache;
import android.app.admin.DevicePolicyDrawableResource;
import android.app.admin.DevicePolicyEventLogger;
import android.app.admin.DevicePolicyManager;
import android.app.admin.DevicePolicyManager.DeviceOwnerType;
import android.app.admin.DevicePolicyManager.DevicePolicyOperation;
import android.app.admin.DevicePolicyManager.OperationSafetyReason;
import android.app.admin.DevicePolicyManager.PasswordComplexity;
import android.app.admin.DevicePolicyManager.PersonalAppsSuspensionReason;
import android.app.admin.DevicePolicyManagerInternal;
import android.app.admin.DevicePolicyManagerLiteInternal;
import android.app.admin.DevicePolicySafetyChecker;
import android.app.admin.DevicePolicyState;
import android.app.admin.DevicePolicyStringResource;
import android.app.admin.DeviceStateCache;
import android.app.admin.FactoryResetProtectionPolicy;
import android.app.admin.FullyManagedDeviceProvisioningParams;
import android.app.admin.IDevicePolicyManager;
import android.app.admin.IntegerPolicyValue;
import android.app.admin.IntentFilterPolicyKey;
import android.app.admin.LockTaskPolicy;
import android.app.admin.LongPolicyValue;
import android.app.admin.ManagedProfileProvisioningParams;
import android.app.admin.ManagedSubscriptionsPolicy;
import android.app.admin.NetworkEvent;
import android.app.admin.PackagePolicy;
import android.app.admin.ParcelableGranteeMap;
import android.app.admin.ParcelableResource;
import android.app.admin.PasswordMetrics;
import android.app.admin.PasswordPolicy;
import android.app.admin.PolicyKey;
import android.app.admin.PolicyValue;
import android.app.admin.PreferentialNetworkServiceConfig;
import android.app.admin.SecurityLog;
import android.app.admin.SecurityLog.SecurityEvent;
import android.app.admin.StartInstallingUpdateCallback;
import android.app.admin.StringSetPolicyValue;
import android.app.admin.SystemUpdateInfo;
import android.app.admin.SystemUpdatePolicy;
import android.app.admin.UnsafeStateException;
import android.app.admin.UserRestrictionPolicyKey;
import android.app.admin.WifiSsidPolicy;
import android.app.backup.IBackupManager;
import android.app.compat.CompatChanges;
import android.app.role.OnRoleHoldersChangedListener;
import android.app.role.RoleManager;
import android.app.trust.TrustManager;
import android.app.usage.UsageStatsManagerInternal;
import android.compat.annotation.ChangeId;
import android.compat.annotation.EnabledAfter;
import android.compat.annotation.EnabledSince;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.IIntentReceiver;
import android.content.IIntentSender;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.PermissionChecker;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.CrossProfileApps;
import android.content.pm.CrossProfileAppsInternal;
import android.content.pm.IPackageDataObserver;
import android.content.pm.IPackageManager;
import android.content.pm.PackageInfo;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.PackageManagerInternal;
import android.content.pm.ParceledListSlice;
import android.content.pm.PermissionInfo;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.content.pm.Signature;
import android.content.pm.StringParceledListSlice;
import android.content.pm.UserInfo;
import android.content.pm.UserPackage;
import android.content.pm.parsing.FrameworkParsingPackageUtils;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.hardware.usb.UsbManager;
import android.location.Location;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.IAudioService;
import android.net.ConnectivityManager;
import android.net.ConnectivitySettingsManager;
import android.net.IIpConnectivityMetrics;
import android.net.ProfileNetworkPreference;
import android.net.ProxyInfo;
import android.net.Uri;
import android.net.VpnManager;
import android.net.metrics.IpConnectivityLog;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.ParcelFileDescriptor;
import android.os.PersistableBundle;
import android.os.PowerManager;
import android.os.PowerManagerInternal;
import android.os.Process;
import android.os.RemoteCallback;
import android.os.RemoteException;
import android.os.ResultReceiver;
import android.os.ServiceManager;
import android.os.ServiceSpecificException;
import android.os.ShellCallback;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.os.UserHandle;
import android.os.UserManager;
import android.os.UserManager.EnforcingUser;
import android.os.UserManager.UserRestrictionSource;
import android.os.storage.StorageManager;
import android.permission.AdminPermissionControlParams;
import android.permission.IPermissionManager;
import android.permission.PermissionControllerManager;
import android.provider.CalendarContract;
import android.provider.ContactsContract.QuickContact;
import android.provider.ContactsInternal;
import android.provider.DeviceConfig;
import android.provider.Settings;
import android.provider.Settings.Global;
import android.provider.Telephony;
import android.security.AppUriAuthenticationPolicy;
import android.security.IKeyChainAliasCallback;
import android.security.IKeyChainService;
import android.security.KeyChain;
import android.security.KeyChain.KeyChainConnection;
import android.security.keymaster.KeymasterCertificateChain;
import android.security.keystore.AttestationUtils;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.security.keystore.ParcelableKeyGenParameterSpec;
import android.stats.devicepolicy.DevicePolicyEnums;
import android.telecom.TelecomManager;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.telephony.data.ApnSetting;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.AtomicFile;
import android.util.DebugUtils;
import android.util.IndentingPrintWriter;
import android.util.IntArray;
import android.util.Pair;
import android.util.Slog;
import android.util.SparseArray;
import android.util.Xml;
import android.view.IWindowManager;
import android.view.accessibility.AccessibilityManager;
import android.view.accessibility.IAccessibilityManager;
import android.view.inputmethod.InputMethodInfo;

import com.android.internal.R;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.app.LocalePicker;
import com.android.internal.infra.AndroidFuture;
import com.android.internal.logging.MetricsLogger;
import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
import com.android.internal.net.NetworkUtilsInternal;
import com.android.internal.notification.SystemNotificationChannels;
import com.android.internal.os.BackgroundThread;
import com.android.internal.statusbar.IStatusBarService;
import com.android.internal.telephony.SmsApplication;
import com.android.internal.util.ArrayUtils;
import com.android.internal.util.DumpUtils;
import com.android.internal.util.FunctionalUtils.ThrowingRunnable;
import com.android.internal.util.FunctionalUtils.ThrowingSupplier;
import com.android.internal.util.JournaledFile;
import com.android.internal.util.Preconditions;
import com.android.internal.util.StatLogger;
import com.android.internal.widget.LockPatternUtils;
import com.android.internal.widget.LockSettingsInternal;
import com.android.internal.widget.LockscreenCredential;
import com.android.internal.widget.PasswordValidationError;
import com.android.modules.utils.TypedXmlPullParser;
import com.android.modules.utils.TypedXmlSerializer;
import com.android.net.module.util.ProxyUtils;
import com.android.server.AlarmManagerInternal;
import com.android.server.LocalManagerRegistry;
import com.android.server.LocalServices;
import com.android.server.LockGuard;
import com.android.server.SystemServerInitThreadPool;
import com.android.server.SystemService;
import com.android.server.SystemServiceManager;
import com.android.server.devicepolicy.ActiveAdmin.TrustAgentInfo;
import com.android.server.inputmethod.InputMethodManagerInternal;
import com.android.server.net.NetworkPolicyManagerInternal;
import com.android.server.pdb.PersistentDataBlockManagerInternal;
import com.android.server.pm.DefaultCrossProfileIntentFilter;
import com.android.server.pm.DefaultCrossProfileIntentFiltersUtils;
import com.android.server.pm.PackageManagerLocal;
import com.android.server.pm.RestrictionsSet;
import com.android.server.pm.UserManagerInternal;
import com.android.server.pm.UserManagerInternal.UserRestrictionsListener;
import com.android.server.pm.UserRestrictionsUtils;
import com.android.server.pm.pkg.AndroidPackage;
import com.android.server.storage.DeviceStorageMonitorInternal;
import com.android.server.uri.NeededUriGrants;
import com.android.server.uri.UriGrantsManagerInternal;
import com.android.server.utils.Slogf;
import com.android.server.wm.ActivityTaskManagerInternal;

import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.time.LocalDate;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * Implementation of the device policy APIs.
 */
public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {

    protected static final String LOG_TAG = "DevicePolicyManager";

    private static final String ATTRIBUTION_TAG = "DevicePolicyManagerService";

    static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE

    static final String DEVICE_POLICIES_XML = "device_policies.xml";

    static final String POLICIES_VERSION_XML = "device_policies_version";

    private static final String TRANSFER_OWNERSHIP_PARAMETERS_XML =
            "transfer-ownership-parameters.xml";

    private static final String TAG_TRANSFER_OWNERSHIP_BUNDLE = "transfer-ownership-bundle";

    private static final int REQUEST_EXPIRE_PASSWORD = 5571;

    private static final int REQUEST_PROFILE_OFF_DEADLINE = 5572;

    // Binary XML serializer doesn't support longer strings
    private static final int MAX_POLICY_STRING_LENGTH = 65535;
    // FrameworkParsingPackageUtils#MAX_FILE_NAME_SIZE, Android packages are used in dir names.
    private static final int MAX_PACKAGE_NAME_LENGTH = 223;

    private static final int MAX_PROFILE_NAME_LENGTH = 200;
    private static final int MAX_LONG_SUPPORT_MESSAGE_LENGTH = 20000;
    private static final int MAX_SHORT_SUPPORT_MESSAGE_LENGTH = 200;
    private static final int MAX_ORG_NAME_LENGTH = 200;

    private static final long MS_PER_DAY = TimeUnit.DAYS.toMillis(1);

    private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
    private static final long MANAGED_PROFILE_MAXIMUM_TIME_OFF_THRESHOLD = 3 * MS_PER_DAY;
    /** When to warn the user about the approaching work profile off deadline: 1 day before */
    private static final long MANAGED_PROFILE_OFF_WARNING_PERIOD = 1 * MS_PER_DAY;

    private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION =
            "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";

    /** Broadcast action invoked when the user taps a notification to turn the profile on. */
    @VisibleForTesting
    static final String ACTION_TURN_PROFILE_ON_NOTIFICATION =
            "com.android.server.ACTION_TURN_PROFILE_ON_NOTIFICATION";

    /** Broadcast action for tracking managed profile maximum time off. */
    @VisibleForTesting
    static final String ACTION_PROFILE_OFF_DEADLINE =
            "com.android.server.ACTION_PROFILE_OFF_DEADLINE";

    private static final String CALLED_FROM_PARENT = "calledFromParent";
    private static final String NOT_CALLED_FROM_PARENT = "notCalledFromParent";

    private static final String CREDENTIAL_MANAGEMENT_APP = "credentialManagementApp";
    private static final String NOT_CREDENTIAL_MANAGEMENT_APP = "notCredentialManagementApp";

    private static final String NULL_STRING_ARRAY = "nullStringArray";

    private static final String ALLOW_USER_PROVISIONING_KEY = "ro.config.allowuserprovisioning";

    // Comprehensive list of delegations.
    private static final String DELEGATIONS[] = {
        DELEGATION_CERT_INSTALL,
        DELEGATION_APP_RESTRICTIONS,
        DELEGATION_BLOCK_UNINSTALL,
        DELEGATION_ENABLE_SYSTEM_APP,
        DELEGATION_KEEP_UNINSTALLED_PACKAGES,
        DELEGATION_PACKAGE_ACCESS,
        DELEGATION_PERMISSION_GRANT,
        DELEGATION_INSTALL_EXISTING_PACKAGE,
        DELEGATION_KEEP_UNINSTALLED_PACKAGES,
        DELEGATION_NETWORK_LOGGING,
        DELEGATION_SECURITY_LOGGING,
        DELEGATION_CERT_SELECTION,
    };

    // Subset of delegations that can only be delegated by Device Owner or Profile Owner of a
    // managed profile.
    private static final List<String> DEVICE_OWNER_OR_MANAGED_PROFILE_OWNER_DELEGATIONS =
            Arrays.asList(new String[]{
                    DELEGATION_NETWORK_LOGGING,
            });

    // Subset of delegations that can only be delegated by Device Owner or Profile Owner of an
    // organization-owned and managed profile.
    private static final List<String>
            DEVICE_OWNER_OR_ORGANIZATION_OWNED_MANAGED_PROFILE_OWNER_DELEGATIONS =
            Arrays.asList(new String[]{
                    DELEGATION_SECURITY_LOGGING,
            });

    // Subset of delegations that only one single package within a given user can hold
    private static final List<String> EXCLUSIVE_DELEGATIONS = Arrays.asList(new String[] {
            DELEGATION_NETWORK_LOGGING,
            DELEGATION_SECURITY_LOGGING,
            DELEGATION_CERT_SELECTION,
    });

    /**
     * System property whose value indicates whether the device is fully owned by an organization:
     * it can be either a device owner device, or a device with an organization-owned managed
     * profile.
     *
     * <p>The state is stored as a Boolean string.
     */
    private static final String PROPERTY_ORGANIZATION_OWNED = "ro.organization_owned";

    private static final int STATUS_BAR_DISABLE_MASK =
            StatusBarManager.DISABLE_EXPAND |
            StatusBarManager.DISABLE_NOTIFICATION_ICONS |
            StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
            StatusBarManager.DISABLE_SEARCH;

    private static final int STATUS_BAR_DISABLE2_MASK =
            StatusBarManager.DISABLE2_QUICK_SETTINGS;

    private static final Set<String> SECURE_SETTINGS_ALLOWLIST;
    private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST;
    private static final Set<String> GLOBAL_SETTINGS_ALLOWLIST;
    private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
    private static final Set<String> SYSTEM_SETTINGS_ALLOWLIST;
    private static final Set<Integer> DA_DISALLOWED_POLICIES;
    private static final String AB_DEVICE_KEY = "ro.build.ab_update";
    // The version of the current DevicePolicyManagerService data. This version is used
    // to decide whether an existing policy in the {@link #DEVICE_POLICIES_XML} needs to
    // be upgraded. See {@link PolicyVersionUpgrader} on instructions how to add an upgrade
    // step.
    static final int DPMS_VERSION = 6;

    static {
        SECURE_SETTINGS_ALLOWLIST = new ArraySet<>();
        SECURE_SETTINGS_ALLOWLIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
        SECURE_SETTINGS_ALLOWLIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
        SECURE_SETTINGS_ALLOWLIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);

        SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST = new ArraySet<>();
        SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST.addAll(SECURE_SETTINGS_ALLOWLIST);
        SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST.add(Settings.Secure.LOCATION_MODE);

        GLOBAL_SETTINGS_ALLOWLIST = new ArraySet<>();
        GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.ADB_ENABLED);
        GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.ADB_WIFI_ENABLED);
        GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.AUTO_TIME);
        GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.AUTO_TIME_ZONE);
        GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.DATA_ROAMING);
        GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
        GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.WIFI_SLEEP_POLICY);
        GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
        GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
        GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.PRIVATE_DNS_MODE);
        GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.PRIVATE_DNS_SPECIFIER);

        GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);

        SYSTEM_SETTINGS_ALLOWLIST = new ArraySet<>();
        SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_BRIGHTNESS);
        SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_BRIGHTNESS_FLOAT);
        SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_BRIGHTNESS_MODE);
        SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_OFF_TIMEOUT);

        DA_DISALLOWED_POLICIES = new ArraySet<>();
        DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
        DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
        DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD);
        DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
    }

    /**
     * Keyguard features that when set on a profile affect the profile content or challenge only.
     * These cannot be set on the managed profile's parent DPM instance
     */
    private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
            DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;

    /** Keyguard features that are allowed to be set on a managed profile */
    private static final int PROFILE_KEYGUARD_FEATURES =
            NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER
                    | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;

    private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;

    /**
     * Minimum timeout in milliseconds after which unlocking with weak auth times out,
     * i.e. the user has to use a strong authentication method like password, PIN or pattern.
     */
    private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);

    /**
     * The amount of ms that a managed kiosk must go without user interaction to be considered
     * unattended.
     */
    private static final int UNATTENDED_MANAGED_KIOSK_MS = 30000;

    /**
     * Strings logged with {@link
     * com.android.internal.logging.nano.MetricsProto.MetricsEvent#PROVISIONING_ENTRY_POINT_ADB},
     * {@link DevicePolicyEnums#PROVISIONING_ENTRY_POINT_ADB},
     * {@link DevicePolicyEnums#SET_NETWORK_LOGGING_ENABLED} and
     * {@link DevicePolicyEnums#RETRIEVE_NETWORK_LOGS}.
     */
    private static final String LOG_TAG_PROFILE_OWNER = "profile-owner";
    private static final String LOG_TAG_DEVICE_OWNER = "device-owner";

    /**
     * For admin apps targeting R+, throw when the app sets password requirement
     * that is not taken into account at given quality. For example when quality is set
     * to {@link android.app.admin.DevicePolicyManager#PASSWORD_QUALITY_UNSPECIFIED}, it doesn't
     * make sense to require certain password length. If the intent is to require a password of
     * certain length having at least NUMERIC quality, the admin should first call
     * {@link android.app.admin.DevicePolicyManager#setPasswordQuality} and only then call
     * {@link android.app.admin.DevicePolicyManager#setPasswordMinimumLength}.
     *
     * <p>Conversely when an admin app targeting R+ lowers password quality, those
     * requirements that stop making sense are reset to default values.
     */
    @ChangeId
    @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
    private static final long ADMIN_APP_PASSWORD_COMPLEXITY = 123562444L;

    /**
     * Admin apps targeting Android R+ may not use
     * {@link android.app.admin.DevicePolicyManager#setSecureSetting} to change the deprecated
     * {@link android.provider.Settings.Secure#LOCATION_MODE} setting. Instead they should use
     * {@link android.app.admin.DevicePolicyManager#setLocationEnabled}.
     */
    @ChangeId
    @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
    private static final long USE_SET_LOCATION_ENABLED = 117835097L;

    /**
     * Forces wipeDataNoLock to attempt removing the user or throw an error as
     * opposed to trying to factory reset the device first and only then falling back to user
     * removal.
     */
    @ChangeId
    @EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
    public static final long EXPLICIT_WIPE_BEHAVIOUR = 242193913L;

    /**
     * Apps targetting U+ should now expect that attempts to grant sensor permissions without
     * authorisation will result in a security exception.
     */
    @ChangeId
    @EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
    public static final long THROW_SECURITY_EXCEPTION_FOR_SENSOR_PERMISSIONS = 277035314L;

    // Only add to the end of the list. Do not change or rearrange these values, that will break
    // historical data. Do not use negative numbers or zero, logger only handles positive
    // integers.
    private static final int COPY_ACCOUNT_SUCCEEDED = 1;
    private static final int COPY_ACCOUNT_FAILED = 2;
    private static final int COPY_ACCOUNT_TIMED_OUT = 3;
    private static final int COPY_ACCOUNT_EXCEPTION = 4;

    @IntDef({
            COPY_ACCOUNT_SUCCEEDED,
            COPY_ACCOUNT_FAILED,
            COPY_ACCOUNT_TIMED_OUT,
            COPY_ACCOUNT_EXCEPTION})
    private @interface CopyAccountStatus {}

    /**
     * Mapping of {@link android.app.admin.DevicePolicyManager.ApplicationExemptionConstants} to
     * corresponding app-ops.
     */
    private static final Map<Integer, String> APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS =
            new ArrayMap<>();
    static {
        APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.put(
                EXEMPT_FROM_SUSPENSION, OPSTR_SYSTEM_EXEMPT_FROM_SUSPENSION);
        APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.put(
                EXEMPT_FROM_DISMISSIBLE_NOTIFICATIONS,
                OPSTR_SYSTEM_EXEMPT_FROM_DISMISSIBLE_NOTIFICATIONS);
        APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.put(
                EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION,
                OPSTR_SYSTEM_EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION);
        APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.put(
                EXEMPT_FROM_HIBERNATION, OPSTR_SYSTEM_EXEMPT_FROM_HIBERNATION);
        APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.put(
                EXEMPT_FROM_POWER_RESTRICTIONS, OPSTR_SYSTEM_EXEMPT_FROM_POWER_RESTRICTIONS);
    }

    /**
     * Admin apps targeting Android S+ may not use
     * {@link android.app.admin.DevicePolicyManager#setPasswordQuality} to set password quality
     * on the {@code DevicePolicyManager} instance obtained by calling
     * {@link android.app.admin.DevicePolicyManager#getParentProfileInstance}.
     * Instead, they should use
     * {@link android.app.admin.DevicePolicyManager#setRequiredPasswordComplexity} to set
     * coarse-grained password requirements device-wide.
     */
    @ChangeId
    @EnabledSince(targetSdkVersion = Build.VERSION_CODES.S)
    private static final long PREVENT_SETTING_PASSWORD_QUALITY_ON_PARENT = 165573442L;

    /**
     * For Admin Apps targeting U+
     * If {@link android.security.IKeyChainService#setGrant} is called with an alias with no
     * existing key, throw IllegalArgumentException.
     */
    @ChangeId
    @EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
    private static final long THROW_EXCEPTION_WHEN_KEY_MISSING = 175101461L;

    private static final String CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG =
            "The alias provided must be contained in the aliases specified in the credential "
                    + "management app's authentication policy";
    private static final String NOT_SYSTEM_CALLER_MSG = "Only the system can %s";

    private static final String PERMISSION_BASED_ACCESS_EXPERIMENT_FLAG =
            "enable_permission_based_access";
    private static final boolean DEFAULT_VALUE_PERMISSION_BASED_ACCESS_FLAG = false;

    // TODO(b/266831522) remove the flag after rollout.
    private static final String APPLICATION_EXEMPTIONS_FLAG = "application_exemptions";
    private static final boolean DEFAULT_APPLICATION_EXEMPTIONS_FLAG = true;

    /**
     * For apps targeting U+
     * Enable multiple admins to coexist on the same device.
     */
    @ChangeId
    @EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
    static final long ENABLE_COEXISTENCE_CHANGE = 260560985L;

    final Context mContext;
    final Injector mInjector;
    final PolicyPathProvider mPathProvider;
    final IPackageManager mIPackageManager;
    final IPermissionManager mIPermissionManager;
    final UserManager mUserManager;
    final UserManagerInternal mUserManagerInternal;
    final UsageStatsManagerInternal mUsageStatsManagerInternal;
    final TelephonyManager mTelephonyManager;
    final RoleManager mRoleManager;
    private final LockPatternUtils mLockPatternUtils;
    private final LockSettingsInternal mLockSettingsInternal;
    private final DeviceAdminServiceController mDeviceAdminServiceController;
    private final OverlayPackagesProvider mOverlayPackagesProvider;

    private final DevicePolicyCacheImpl mPolicyCache = new DevicePolicyCacheImpl();
    private final DeviceStateCacheImpl mStateCache = new DeviceStateCacheImpl();
    private final Object mESIDInitilizationLock = new Object();
    private EnterpriseSpecificIdCalculator mEsidCalculator;
    private final Object mSubscriptionsChangedListenerLock = new Object();
    @GuardedBy("mSubscriptionsChangedListenerLock")
    private SubscriptionManager.OnSubscriptionsChangedListener mSubscriptionsChangedListener;

    /**
     * Contains the list of OEM Default Role Holders for Contact-related roles
     * (DIALER, SMS, SYSTEM_CONTACTS)
     */
    private final Set<String> mContactSystemRoleHolders;

    /**
     * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
     * is requested for user u.
     */
    private final Set<UserPackage> mPackagesToRemove = new ArraySet<>();

    final LocalService mLocalService;

    // Stores and loads state on device and profile owners.
    @VisibleForTesting
    final Owners mOwners;

    private final Binder mToken = new Binder();

    /**
     * Whether or not device admin feature is supported. If it isn't return defaults for all
     * public methods, unless the caller has the appropriate permission for a particular method.
     */
    final boolean mHasFeature;

    /**
     * Whether or not this device is a watch.
     */
    final boolean mIsWatch;

    /**
     * Whether or not this device is an automotive.
     */
    private final boolean mIsAutomotive;

    /**
     * Whether this device has the telephony feature.
     */
    final boolean mHasTelephonyFeature;

    private final CertificateMonitor mCertificateMonitor;
    private final SecurityLogMonitor mSecurityLogMonitor;
    private final RemoteBugreportManager mBugreportCollectionManager;

    @GuardedBy("getLockObject()")
    private NetworkLogger mNetworkLogger;

    private final SetupContentObserver mSetupContentObserver;
    private final DevicePolicyConstantsObserver mConstantsObserver;

    private DevicePolicyConstants mConstants;

    /**
     * User to be switched to on {@code logoutUser()}.
     *
     * <p>Only used on devices with headless system user mode
     */
    @GuardedBy("getLockObject()")
    private @UserIdInt int mLogoutUserId = UserHandle.USER_NULL;

    /**
     * User the network logging notification was sent to.
     */
    // Guarded by mHandler
    private @UserIdInt int mNetworkLoggingNotificationUserId = UserHandle.USER_NULL;

    private final DeviceManagementResourcesProvider mDeviceManagementResourcesProvider;
    private final DevicePolicyManagementRoleObserver mDevicePolicyManagementRoleObserver;

    private final DevicePolicyEngine mDevicePolicyEngine;

    private static final boolean ENABLE_LOCK_GUARD = true;

    /**
     * Profile off deadline is not set or more than MANAGED_PROFILE_OFF_WARNING_PERIOD away, or the
     * user is running unlocked, no need for notification.
     */
    private static final int PROFILE_OFF_NOTIFICATION_NONE = 0;
    /**
     * Profile off deadline is closer than MANAGED_PROFILE_OFF_WARNING_PERIOD.
     */
    private static final int PROFILE_OFF_NOTIFICATION_WARNING = 1;
    /**
     * Profile off deadline reached, notify the user that personal apps blocked.
     */
    private static final int PROFILE_OFF_NOTIFICATION_SUSPENDED = 2;

    interface Stats {
        int LOCK_GUARD_GUARD = 0;

        int COUNT = LOCK_GUARD_GUARD + 1;
    }

    private final StatLogger mStatLogger = new StatLogger(new String[] {
            "LockGuard.guard()",
    });

    private final Object mLockDoNoUseDirectly = LockGuard.installNewLock(
            LockGuard.INDEX_DPMS, /* doWtf=*/ true);

    final Object getLockObject() {
        if (ENABLE_LOCK_GUARD) {
            final long start = mStatLogger.getTime();
            LockGuard.guard(LockGuard.INDEX_DPMS);
            mStatLogger.logDurationStat(Stats.LOCK_GUARD_GUARD, start);
        }
        return mLockDoNoUseDirectly;
    }

    /**
     * Check if the current thread holds the DPMS lock, and if not, do a WTF.
     *
     * (Doing this check too much may be costly, so don't call it in a hot path.)
     */
    final void ensureLocked() {
        if (Thread.holdsLock(mLockDoNoUseDirectly)) {
            return;
        }
        Slogf.wtfStack(LOG_TAG, "Not holding DPMS lock.");
    }

    /**
     * Calls wtfStack() if called with the DPMS lock held.
     */
    private void wtfIfInLock() {
        if (Thread.holdsLock(mLockDoNoUseDirectly)) {
            Slogf.wtfStack(LOG_TAG, "Shouldn't be called with DPMS lock held");
        }
    }

    @VisibleForTesting
    final TransferOwnershipMetadataManager mTransferOwnershipMetadataManager;

    @Nullable
    private DevicePolicySafetyChecker mSafetyChecker;

    @GuardedBy("getLockObject()")
    private final ArrayList<Object> mPendingUserCreatedCallbackTokens = new ArrayList<>();

    public static final class Lifecycle extends SystemService {
        private DevicePolicyManagerService mService;

        public Lifecycle(Context context) {
            super(context);
            String dpmsClassName = context.getResources()
                    .getString(R.string.config_deviceSpecificDevicePolicyManagerService);
            if (TextUtils.isEmpty(dpmsClassName)) {
                mService = new DevicePolicyManagerService(context);
            } else {
                try {
                    Class<?> serviceClass = Class.forName(dpmsClassName);
                    Constructor<?> constructor = serviceClass.getConstructor(Context.class);
                    mService = (DevicePolicyManagerService) constructor.newInstance(context);
                } catch (Exception e) {
                    throw new IllegalStateException(
                        "Failed to instantiate DevicePolicyManagerService with class name: "
                        + dpmsClassName, e);
                }
            }
        }

        /** Sets the {@link DevicePolicySafetyChecker}. */
        public void setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker) {
            mService.setDevicePolicySafetyChecker(safetyChecker);
        }

        @Override
        public void onStart() {
            publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
        }

        @Override
        public void onBootPhase(int phase) {
            mService.systemReady(phase);
        }

        @Override
        public void onUserStarting(@NonNull TargetUser user) {
            if (user.isPreCreated()) return;
            mService.handleStartUser(user.getUserIdentifier());
        }

        @Override
        public void onUserUnlocking(@NonNull TargetUser user) {
            if (user.isPreCreated()) return;
            mService.handleUnlockUser(user.getUserIdentifier());
        }

        @Override
        public void onUserStopping(@NonNull TargetUser user) {
            if (user.isPreCreated()) return;
            mService.handleStopUser(user.getUserIdentifier());
        }

        @Override
        public void onUserUnlocked(@NonNull TargetUser user) {
            if (user.isPreCreated()) return;
            mService.handleOnUserUnlocked(user.getUserIdentifier());
        }
    }

    @GuardedBy("getLockObject()")
    final SparseArray<DevicePolicyData> mUserData;

    final Handler mHandler;
    final Handler mBackgroundHandler;

    /** Listens only if mHasFeature == true. */
    final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
                    getSendingUserId());

            /*
             * Network logging would ideally be started in setDeviceOwnerSystemPropertyLocked(),
             * however it's too early in the boot process to register with IIpConnectivityMetrics
             * to listen for events.
             */
            if (Intent.ACTION_USER_STARTED.equals(action) && userHandle == UserHandle.USER_SYSTEM) {
                synchronized (getLockObject()) {
                    if (isNetworkLoggingEnabledInternalLocked()) {
                        setNetworkLoggingActiveInternal(true);
                    }
                }
            }

            if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
                calculateHasIncompatibleAccounts();
            }

            if (Intent.ACTION_BOOT_COMPLETED.equals(action)
                    && userHandle == mOwners.getDeviceOwnerUserId()) {
                mBugreportCollectionManager.checkForPendingBugreportAfterBoot();

            }
            if (Intent.ACTION_BOOT_COMPLETED.equals(action)
                    || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
                if (VERBOSE_LOG) {
                    Slogf.v(LOG_TAG, "Sending password expiration notifications for action "
                            + action + " for user " + userHandle);
                }
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        handlePasswordExpirationNotification(userHandle);
                    }
                });
            }

            if (Intent.ACTION_USER_ADDED.equals(action)) {
                sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_ADDED, userHandle);
                synchronized (getLockObject()) {
                    // It might take a while for the user to become affiliated. Make security
                    // and network logging unavailable in the meantime.
                    maybePauseDeviceWideLoggingLocked();
                }
            } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
                sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_REMOVED, userHandle);
                synchronized (getLockObject()) {
                    // Check whether the user is affiliated, *before* removing its data.
                    boolean isRemovedUserAffiliated = isUserAffiliatedWithDeviceLocked(userHandle);
                    removeUserData(userHandle);
                    if (!isRemovedUserAffiliated) {
                        // We discard the logs when unaffiliated users are deleted (so that the
                        // device owner cannot retrieve data about that user after it's gone).
                        discardDeviceWideLogsLocked();
                        // Resume logging if all remaining users are affiliated.
                        maybeResumeDeviceWideLoggingLocked();
                    }
                }
                mDevicePolicyEngine.handleUserRemoved(userHandle);
            } else if (Intent.ACTION_USER_STARTED.equals(action)) {
                sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STARTED, userHandle);
                synchronized (getLockObject()) {
                    maybeSendAdminEnabledBroadcastLocked(userHandle);
                    // Reset the policy data
                    mUserData.remove(userHandle);
                }
                handlePackagesChanged(null /* check all admins */, userHandle);
                updatePersonalAppsSuspensionOnUserStart(userHandle);
            } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
                sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STOPPED, userHandle);
                if (isManagedProfile(userHandle)) {
                    Slogf.d(LOG_TAG, "Managed profile was stopped");
                    updatePersonalAppsSuspension(userHandle);
                }
            } else if (Intent.ACTION_USER_SWITCHED.equals(action)) {
                sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_SWITCHED, userHandle);
            } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
                synchronized (getLockObject()) {
                    maybeSendAdminEnabledBroadcastLocked(userHandle);
                }
                if (isManagedProfile(userHandle)) {
                    Slogf.d(LOG_TAG, "Managed profile became unlocked");
                    final boolean suspended = updatePersonalAppsSuspension(userHandle);
                    triggerPolicyComplianceCheckIfNeeded(userHandle, suspended);
                }
            } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
                handlePackagesChanged(null /* check all admins */, userHandle);
            } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
                handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
            } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
                if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
                    handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
                } else {
                    handleNewPackageInstalled(intent.getData().getSchemeSpecificPart(), userHandle);
                }
            } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
                    && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
                handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
                removeCredentialManagementApp(intent.getData().getSchemeSpecificPart());
            } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
                clearWipeProfileNotification();
            } else if (Intent.ACTION_DATE_CHANGED.equals(action)
                    || Intent.ACTION_TIME_CHANGED.equals(action)) {
                // Update freeze period record when clock naturally progresses to the next day
                // (ACTION_DATE_CHANGED), or when manual clock adjustment is made
                // (ACTION_TIME_CHANGED)
                updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ true);
                final int userId = getManagedUserId(getMainUserId());
                if (userId >= 0) {
                    updatePersonalAppsSuspension(userId);
                }
            } else if (ACTION_PROFILE_OFF_DEADLINE.equals(action)) {
                Slogf.i(LOG_TAG, "Profile off deadline alarm was triggered");
                final int userId = getManagedUserId(getMainUserId());
                if (userId >= 0) {
                    updatePersonalAppsSuspension(userId);
                } else {
                    Slogf.wtf(LOG_TAG, "Got deadline alarm for nonexistent profile");
                }
            } else if (ACTION_TURN_PROFILE_ON_NOTIFICATION.equals(action)) {
                Slogf.i(LOG_TAG, "requesting to turn on the profile: " + userHandle);
                mUserManager.requestQuietModeEnabled(false, UserHandle.of(userHandle));
            } else if (ACTION_MANAGED_PROFILE_UNAVAILABLE.equals(action)) {
                notifyIfManagedSubscriptionsAreUnavailable(
                        UserHandle.of(userHandle), /* managedProfileAvailable= */ false);
                updatePersonalAppsSuspension(userHandle);
            } else if (ACTION_MANAGED_PROFILE_AVAILABLE.equals(action)) {
                notifyIfManagedSubscriptionsAreUnavailable(
                        UserHandle.of(userHandle), /* managedProfileAvailable= */ true);
                final boolean suspended = updatePersonalAppsSuspension(userHandle);
                triggerPolicyComplianceCheckIfNeeded(userHandle, suspended);
            } else if (LOGIN_ACCOUNTS_CHANGED_ACTION.equals(action)) {
                calculateHasIncompatibleAccounts();
            }
        }

        private void sendDeviceOwnerUserCommand(String action, int userHandle) {
            synchronized (getLockObject()) {
                ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
                if (deviceOwner != null) {
                    Bundle extras = new Bundle();
                    extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
                    sendAdminCommandLocked(deviceOwner, action, extras, /* result */ null,
                            /* inForeground */ true);
                }
            }
        }
    };

    protected static class RestrictionsListener implements UserRestrictionsListener {
        private final Context mContext;
        private final UserManagerInternal mUserManagerInternal;
        private final DevicePolicyManagerService mDpms;

        public RestrictionsListener(
                Context context,
                UserManagerInternal userManagerInternal,
                DevicePolicyManagerService dpms) {
            mContext = context;
            mUserManagerInternal = userManagerInternal;
            mDpms = dpms;
        }

        @Override
        public void onUserRestrictionsChanged(int userId, Bundle newRestrictions,
                Bundle prevRestrictions) {
            resetCrossProfileIntentFiltersIfNeeded(userId, newRestrictions, prevRestrictions);
            resetUserVpnIfNeeded(userId, newRestrictions, prevRestrictions);
        }

        private void resetUserVpnIfNeeded(
                int userId, Bundle newRestrictions, Bundle prevRestrictions) {
            final boolean newlyEnforced =
                    !prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_VPN)
                    && newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_VPN);
            if (newlyEnforced) {
                mDpms.clearUserConfiguredVpns(userId);
            }
        }

        private void resetCrossProfileIntentFiltersIfNeeded(
                int userId, Bundle newRestrictions, Bundle prevRestrictions) {
            if (UserRestrictionsUtils.restrictionsChanged(prevRestrictions, newRestrictions,
                    UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE)) {
                final int parentId = mUserManagerInternal.getProfileParentId(userId);
                if (parentId == userId) {
                    return;
                }

                // Always reset filters on the parent user, which handles cross profile intent
                // filters between the parent and its profiles.
                Slogf.i(LOG_TAG, "Resetting cross-profile intent filters on restriction "
                        + "change");
                mDpms.resetDefaultCrossProfileIntentFilters(parentId);
                mContext.sendBroadcastAsUser(
                        new Intent(DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_APPLIED),
                        UserHandle.of(userId));
            }
        }
    }

    private void clearUserConfiguredVpns(int userId) {
        final String adminConfiguredVpnPkg;
        synchronized (getLockObject()) {
            final ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId);
            if (owner == null) {
                Slogf.wtf(LOG_TAG, "Admin not found");
                return;
            }
            adminConfiguredVpnPkg = owner.mAlwaysOnVpnPackage;
        }

        // Clear always-on configuration if it wasn't set by the admin.
        if (adminConfiguredVpnPkg == null) {
            mInjector.getVpnManager().setAlwaysOnVpnPackageForUser(userId, null, false, null);
        }

        // Clear app authorizations to establish VPNs. When DISALLOW_CONFIG_VPN is enforced apps
        // won't be able to get those authorizations unless it is configured by an admin.
        final List<AppOpsManager.PackageOps> allVpnOps = mInjector.getAppOpsManager()
                .getPackagesForOps(new int[] {AppOpsManager.OP_ACTIVATE_VPN});
        if (allVpnOps == null) {
            return;
        }
        for (AppOpsManager.PackageOps pkgOps : allVpnOps) {
            if (UserHandle.getUserId(pkgOps.getUid()) != userId
                    || pkgOps.getPackageName().equals(adminConfiguredVpnPkg)) {
                continue;
            }
            if (pkgOps.getOps().size() != 1) {
                Slogf.wtf(LOG_TAG, "Unexpected number of ops returned");
                continue;
            }
            final @Mode int mode = pkgOps.getOps().get(0).getMode();
            if (mode == MODE_ALLOWED) {
                Slogf.i(LOG_TAG, String.format("Revoking VPN authorization for package %s uid %d",
                        pkgOps.getPackageName(), pkgOps.getUid()));
                mInjector.getAppOpsManager().setMode(AppOpsManager.OP_ACTIVATE_VPN, pkgOps.getUid(),
                        pkgOps.getPackageName(), MODE_DEFAULT);
            }
        }
    }

    private final class UserLifecycleListener implements UserManagerInternal.UserLifecycleListener {

        @Override
        public void onUserCreated(UserInfo user, Object token) {
            mHandler.post(() -> handleNewUserCreated(user, token));
        }
    }

    private void handlePackagesChanged(@Nullable String packageName, int userHandle) {
        boolean removedAdmin = false;
        String removedAdminPackage = null;
        if (VERBOSE_LOG) {
            Slogf.d(LOG_TAG, "Handling package changes package " + packageName
                    + " for user " + userHandle);
        }
        DevicePolicyData policy = getUserData(userHandle);
        synchronized (getLockObject()) {
            for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
                ActiveAdmin aa = policy.mAdminList.get(i);
                try {
                    // If we're checking all packages or if the specific one we're checking matches,
                    // then check if the package and receiver still exist.
                    final String adminPackage = aa.info.getPackageName();
                    if (packageName == null || packageName.equals(adminPackage)) {
                        if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
                                || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
                                PackageManager.MATCH_DIRECT_BOOT_AWARE
                                        | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
                                userHandle) == null) {
                            Slogf.e(LOG_TAG, String.format(
                                    "Admin package %s not found for user %d, removing active admin",
                                    packageName, userHandle));
                            removedAdmin = true;
                            removedAdminPackage = adminPackage;
                            policy.mAdminList.remove(i);
                            policy.mAdminMap.remove(aa.info.getComponent());
                            pushActiveAdminPackagesLocked(userHandle);
                        }
                    }
                } catch (RemoteException re) {
                    // Shouldn't happen.
                    Slogf.wtf(LOG_TAG, "Error handling package changes", re);
                }
            }
            if (removedAdmin) {
                policy.validatePasswordOwner();
            }

            boolean removedDelegate = false;

            // Check if a delegate was removed.
            for (int i = policy.mDelegationMap.size() - 1; i >= 0; i--) {
                final String delegatePackage = policy.mDelegationMap.keyAt(i);
                if (isRemovedPackage(packageName, delegatePackage, userHandle)) {
                    policy.mDelegationMap.removeAt(i);
                    removedDelegate = true;
                }
            }

            // If it's an owner package, we may need to refresh the bound connection.
            final ComponentName owner = getOwnerComponent(userHandle);
            if ((packageName != null) && (owner != null)
                    && (owner.getPackageName().equals(packageName))) {
                startOwnerService(userHandle, "package-broadcast");
            }
            mDevicePolicyEngine.handlePackageChanged(packageName, userHandle, removedAdminPackage);
            // Persist updates if the removed package was an admin or delegate.
            if (removedAdmin || removedDelegate) {
                saveSettingsLocked(policy.mUserId);
            }
        }
        if (removedAdmin) {
            // The removed admin might have disabled camera, so update user restrictions.
            pushMeteredDisabledPackages(userHandle);
        }
    }

    private void removeCredentialManagementApp(String packageName) {
        mBackgroundHandler.post(() -> {
            try (KeyChainConnection connection = mInjector.keyChainBind()) {
                IKeyChainService service = connection.getService();
                if (service.hasCredentialManagementApp()
                        && packageName.equals(service.getCredentialManagementAppPackageName())) {
                    service.removeCredentialManagementApp();
                }
            } catch (RemoteException | InterruptedException | IllegalStateException
                    | AssertionError e) {
                Slogf.e(LOG_TAG, "Unable to remove the credential management app", e);
            }
        });
    }

    private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
        try {
            return targetPackage != null
                    && (changedPackage == null || changedPackage.equals(targetPackage))
                    && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
        } catch (RemoteException e) {
            // Shouldn't happen
            Slogf.wtf(LOG_TAG, "Error checking isRemovedPackage", e);
        }

        return false;
    }

    private void handleNewPackageInstalled(String packageName, int userHandle) {
        // If personal apps were suspended by the admin, suspend the newly installed one.
        if (!getUserData(userHandle).mAppsSuspended) {
            return;
        }
        final String[] packagesToSuspend = { packageName };
        // Check if package is considered not suspendable?
        if (mInjector.getPackageManager(userHandle)
                .getUnsuspendablePackages(packagesToSuspend).length != 0) {
            Slogf.i(LOG_TAG, "Newly installed package is unsuspendable: " + packageName);
            return;
        }
        mInjector.getPackageManagerInternal()
                .setPackagesSuspendedByAdmin(userHandle, packagesToSuspend, true /*suspend*/);
    }

    public void setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker) {
        CallerIdentity callerIdentity = getCallerIdentity();
        Preconditions.checkCallAuthorization(mIsAutomotive || isAdb(callerIdentity), "can only set "
                + "DevicePolicySafetyChecker on automotive builds or from ADB (but caller is %s)",
                callerIdentity);
        setDevicePolicySafetyCheckerUnchecked(safetyChecker);
    }

    /**
     * Used by {@code setDevicePolicySafetyChecker()} above and {@link OneTimeSafetyChecker}.
     */
    void setDevicePolicySafetyCheckerUnchecked(DevicePolicySafetyChecker safetyChecker) {
        Slogf.i(LOG_TAG, "Setting DevicePolicySafetyChecker as %s", safetyChecker);
        mSafetyChecker = safetyChecker;
        mInjector.setDevicePolicySafetyChecker(safetyChecker);
    }

    /**
     * Used by {@link OneTimeSafetyChecker} only.
     */
    DevicePolicySafetyChecker getDevicePolicySafetyChecker() {
        return mSafetyChecker;
    }

    /**
     * Checks if it's safe to execute the given {@code operation}.
     *
     * @throws UnsafeStateException if it's not safe to execute the operation.
     */
    private void checkCanExecuteOrThrowUnsafe(@DevicePolicyOperation int operation) {
        int reason = getUnsafeOperationReason(operation);
        if (reason == OPERATION_SAFETY_REASON_NONE) return;

        if (mSafetyChecker == null) {
            // Happens on CTS after it's set just once (by OneTimeSafetyChecker)
            throw new UnsafeStateException(operation, reason);
        }
        // Let mSafetyChecker customize it (for example, by explaining how to retry)
        throw mSafetyChecker.newUnsafeStateException(operation, reason);
    }

    /**
     * Returns whether it's safe to execute the given {@code operation}, and why.
     */
    @OperationSafetyReason
    int getUnsafeOperationReason(@DevicePolicyOperation int operation) {
        return mSafetyChecker == null ? OPERATION_SAFETY_REASON_NONE
                : mSafetyChecker.getUnsafeOperationReason(operation);
    }

    @Override
    public void setNextOperationSafety(@DevicePolicyOperation int operation,
            @OperationSafetyReason int reason) {
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS));
        Slogf.i(LOG_TAG, "setNextOperationSafety(%s, %s)",
                DevicePolicyManager.operationToString(operation),
                DevicePolicyManager.operationSafetyReasonToString(reason));
        mSafetyChecker = new OneTimeSafetyChecker(this, operation, reason);
    }

    @Override
    public boolean isSafeOperation(@OperationSafetyReason int reason) {
        if (VERBOSE_LOG) {
            Slogf.v(LOG_TAG, "checking isSafeOperation(%s) using mSafetyChecker %s",
                    DevicePolicyManager.operationSafetyReasonToString(reason), mSafetyChecker);
        }
        return mSafetyChecker == null ? true : mSafetyChecker.isSafeOperation(reason);
    }

    // Used by DevicePolicyManagerServiceShellCommand
    List<OwnerShellData> listAllOwners() {
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS));
        return mInjector.binderWithCleanCallingIdentity(() -> {
            SparseArray<DevicePolicyData> userData;

            // Gets the owners of "full users" first (device owner and profile owners)
            List<OwnerShellData> owners = mOwners.listAllOwners();
            synchronized (getLockObject()) {
                for (int i = 0; i < owners.size(); i++) {
                    OwnerShellData owner = owners.get(i);
                    owner.isAffiliated = isUserAffiliatedWithDeviceLocked(owner.userId);
                }
                userData = mUserData;
            }

            // Then the owners of profile users (managed profiles)
            for (int i = 0; i < userData.size(); i++) {
                DevicePolicyData policyData = mUserData.valueAt(i);
                int userId = userData.keyAt(i);
                int parentUserId = mUserManagerInternal.getProfileParentId(userId);
                boolean isProfile = parentUserId != userId;
                if (!isProfile) continue;
                for (int j = 0; j < policyData.mAdminList.size(); j++) {
                    ActiveAdmin admin = policyData.mAdminList.get(j);
                    OwnerShellData owner = OwnerShellData.forManagedProfileOwner(userId,
                            parentUserId, admin.info.getComponent());
                    owners.add(owner);
                }
            }

            return owners;
        });
    }

    /**
     * Unit test will subclass it to inject mocks.
     */
    @VisibleForTesting
    static class Injector {

        public final Context mContext;

        @Nullable private DevicePolicySafetyChecker mSafetyChecker;

        Injector(Context context) {
            mContext = context;
        }

        public boolean hasFeature() {
            return getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
        }

        Context createContextAsUser(UserHandle user) throws PackageManager.NameNotFoundException {
            final String packageName = mContext.getPackageName();
            return mContext.createPackageContextAsUser(packageName, 0, user);
        }

        Resources getResources() {
            return mContext.getResources();
        }

        UserManager getUserManager() {
            return UserManager.get(mContext);
        }

        UserManagerInternal getUserManagerInternal() {
            return LocalServices.getService(UserManagerInternal.class);
        }

        PackageManagerInternal getPackageManagerInternal() {
            return LocalServices.getService(PackageManagerInternal.class);
        }

        PackageManagerLocal getPackageManagerLocal() {
            return LocalManagerRegistry.getManager(PackageManagerLocal.class);
        }

        ActivityTaskManagerInternal getActivityTaskManagerInternal() {
            return LocalServices.getService(ActivityTaskManagerInternal.class);
        }

        @NonNull PermissionControllerManager getPermissionControllerManager(
                @NonNull UserHandle user) {
            if (user.equals(mContext.getUser())) {
                return mContext.getSystemService(PermissionControllerManager.class);
            } else {
                try {
                    return mContext.createPackageContextAsUser(mContext.getPackageName(), 0,
                            user).getSystemService(PermissionControllerManager.class);
                } catch (NameNotFoundException notPossible) {
                    // not possible
                    throw new IllegalStateException(notPossible);
                }
            }
        }

        UsageStatsManagerInternal getUsageStatsManagerInternal() {
            return LocalServices.getService(UsageStatsManagerInternal.class);
        }

        NetworkPolicyManagerInternal getNetworkPolicyManagerInternal() {
            return LocalServices.getService(NetworkPolicyManagerInternal.class);
        }

        NotificationManager getNotificationManager() {
            return mContext.getSystemService(NotificationManager.class);
        }

        IIpConnectivityMetrics getIIpConnectivityMetrics() {
            return (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface(
                ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
        }

        PackageManager getPackageManager() {
            return mContext.getPackageManager();
        }

        PackageManager getPackageManager(int userId) {
            try {
                return createContextAsUser(UserHandle.of(userId)).getPackageManager();
            } catch (NameNotFoundException e) {
                throw new IllegalStateException(e);
            }
        }

        PowerManagerInternal getPowerManagerInternal() {
            return LocalServices.getService(PowerManagerInternal.class);
        }

        TelephonyManager getTelephonyManager() {
            return mContext.getSystemService(TelephonyManager.class);
        }

        RoleManager getRoleManager() {
            return mContext.getSystemService(RoleManager.class);
        }

        TrustManager getTrustManager() {
            return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
        }

        AlarmManager getAlarmManager() {
            return mContext.getSystemService(AlarmManager.class);
        }

        AlarmManagerInternal getAlarmManagerInternal() {
            return LocalServices.getService(AlarmManagerInternal.class);
        }

        ConnectivityManager getConnectivityManager() {
            return mContext.getSystemService(ConnectivityManager.class);
        }

        VpnManager getVpnManager() {
            return mContext.getSystemService(VpnManager.class);
        }

        LocationManager getLocationManager() {
            return mContext.getSystemService(LocationManager.class);
        }

        IWindowManager getIWindowManager() {
            return IWindowManager.Stub
                    .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
        }

        IActivityManager getIActivityManager() {
            return ActivityManager.getService();
        }

        IActivityTaskManager getIActivityTaskManager() {
            return ActivityTaskManager.getService();
        }

        ActivityManagerInternal getActivityManagerInternal() {
            return LocalServices.getService(ActivityManagerInternal.class);
        }

        IPackageManager getIPackageManager() {
            return AppGlobals.getPackageManager();
        }

        IPermissionManager getIPermissionManager() {
            return AppGlobals.getPermissionManager();
        }

        IBackupManager getIBackupManager() {
            return IBackupManager.Stub.asInterface(
                    ServiceManager.getService(Context.BACKUP_SERVICE));
        }

        IAudioService getIAudioService() {
            return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
        }

        PersistentDataBlockManagerInternal getPersistentDataBlockManagerInternal() {
            return LocalServices.getService(PersistentDataBlockManagerInternal.class);
        }

        AppOpsManager getAppOpsManager() {
            return mContext.getSystemService(AppOpsManager.class);
        }

        LockSettingsInternal getLockSettingsInternal() {
            return LocalServices.getService(LockSettingsInternal.class);
        }

        CrossProfileApps getCrossProfileApps(@UserIdInt int userId) {
            return mContext.createContextAsUser(UserHandle.of(userId), /* flags= */ 0)
                    .getSystemService(CrossProfileApps.class);
        }

        boolean hasUserSetupCompleted(DevicePolicyData userData) {
            return userData.mUserSetupComplete;
        }

        boolean isBuildDebuggable() {
            return Build.IS_DEBUGGABLE;
        }

        LockPatternUtils newLockPatternUtils() {
            return new LockPatternUtils(mContext);
        }

        EnterpriseSpecificIdCalculator newEnterpriseSpecificIdCalculator() {
            return new EnterpriseSpecificIdCalculator(mContext);
        }

        boolean storageManagerIsFileBasedEncryptionEnabled() {
            return StorageManager.isFileEncrypted();
        }

        Looper getMyLooper() {
            return Looper.myLooper();
        }

        WifiManager getWifiManager() {
            return mContext.getSystemService(WifiManager.class);
        }

        UsbManager getUsbManager() {
            return mContext.getSystemService(UsbManager.class);
        }

        @SuppressWarnings("ResultOfClearIdentityCallNotStoredInVariable")
        long binderClearCallingIdentity() {
            return Binder.clearCallingIdentity();
        }

        void binderRestoreCallingIdentity(long token) {
            Binder.restoreCallingIdentity(token);
        }

        int binderGetCallingUid() {
            return Binder.getCallingUid();
        }

        int binderGetCallingPid() {
            return Binder.getCallingPid();
        }

        UserHandle binderGetCallingUserHandle() {
            return Binder.getCallingUserHandle();
        }

        boolean binderIsCallingUidMyUid() {
            return getCallingUid() == Process.myUid();
        }

        void binderWithCleanCallingIdentity(@NonNull ThrowingRunnable action) {
             Binder.withCleanCallingIdentity(action);
        }

        final <T> T binderWithCleanCallingIdentity(@NonNull ThrowingSupplier<T> action) {
            return Binder.withCleanCallingIdentity(action);
        }

        final int userHandleGetCallingUserId() {
            return UserHandle.getUserId(binderGetCallingUid());
        }

        void powerManagerGoToSleep(long time, int reason, int flags) {
            mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
        }

        void powerManagerReboot(String reason) {
            mContext.getSystemService(PowerManager.class).reboot(reason);
        }

        boolean recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force,
                boolean wipeEuicc, boolean wipeExtRequested, boolean wipeResetProtectionData)
                        throws IOException {
            return FactoryResetter.newBuilder(mContext).setSafetyChecker(mSafetyChecker)
                    .setReason(reason).setShutdown(shutdown).setForce(force).setWipeEuicc(wipeEuicc)
                    .setWipeAdoptableStorage(wipeExtRequested)
                    .setWipeFactoryResetProtection(wipeResetProtectionData)
                    .build().factoryReset();
        }

        boolean systemPropertiesGetBoolean(String key, boolean def) {
            return SystemProperties.getBoolean(key, def);
        }

        long systemPropertiesGetLong(String key, long def) {
            return SystemProperties.getLong(key, def);
        }

        String systemPropertiesGet(String key, String def) {
            return SystemProperties.get(key, def);
        }

        String systemPropertiesGet(String key) {
            return SystemProperties.get(key);
        }

        void systemPropertiesSet(String key, String value) {
            SystemProperties.set(key, value);
        }

        boolean userManagerIsHeadlessSystemUserMode() {
            return UserManager.isHeadlessSystemUserMode();
        }

        @SuppressWarnings("AndroidFrameworkPendingIntentMutability")
        PendingIntent pendingIntentGetActivityAsUser(Context context, int requestCode,
                @NonNull Intent intent, int flags, Bundle options, UserHandle user) {
            return PendingIntent.getActivityAsUser(
                    context, requestCode, intent, flags, options, user);
        }

        @SuppressWarnings("AndroidFrameworkPendingIntentMutability")
        PendingIntent pendingIntentGetBroadcast(
                Context context, int requestCode, Intent intent, int flags) {
            return PendingIntent.getBroadcast(context, requestCode, intent, flags);
        }

        void registerContentObserver(Uri uri, boolean notifyForDescendents,
                ContentObserver observer, int userHandle) {
            mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
                    observer, userHandle);
        }

        int settingsSecureGetIntForUser(String name, int def, int userHandle) {
            return Settings.Secure.getIntForUser(mContext.getContentResolver(),
                    name, def, userHandle);
        }

        String settingsSecureGetStringForUser(String name, int userHandle) {
            return Settings.Secure.getStringForUser(mContext.getContentResolver(), name,
                    userHandle);
        }

        void settingsSecurePutIntForUser(String name, int value, int userHandle) {
            Settings.Secure.putIntForUser(mContext.getContentResolver(),
                    name, value, userHandle);
        }

        void settingsSecurePutStringForUser(String name, String value, int userHandle) {
            Settings.Secure.putStringForUser(mContext.getContentResolver(),
                    name, value, userHandle);
        }

        void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
            Settings.Global.putStringForUser(mContext.getContentResolver(),
                    name, value, userHandle);
        }

        void settingsSecurePutInt(String name, int value) {
            Settings.Secure.putInt(mContext.getContentResolver(), name, value);
        }

        int settingsGlobalGetInt(String name, int def) {
            return Settings.Global.getInt(mContext.getContentResolver(), name, def);
        }

        @Nullable
        String settingsGlobalGetString(String name) {
            return Settings.Global.getString(mContext.getContentResolver(), name);
        }

        void settingsGlobalPutInt(String name, int value) {
            Settings.Global.putInt(mContext.getContentResolver(), name, value);
        }

        void settingsSecurePutString(String name, String value) {
            Settings.Secure.putString(mContext.getContentResolver(), name, value);
        }

        void settingsGlobalPutString(String name, String value) {
            Settings.Global.putString(mContext.getContentResolver(), name, value);
        }

        void settingsSystemPutStringForUser(String name, String value, int userId) {
          Settings.System.putStringForUser(
              mContext.getContentResolver(), name, value, userId);
        }

        void securityLogSetLoggingEnabledProperty(boolean enabled) {
            SecurityLog.setLoggingEnabledProperty(enabled);
        }

        boolean securityLogGetLoggingEnabledProperty() {
            return SecurityLog.getLoggingEnabledProperty();
        }

        boolean securityLogIsLoggingEnabled() {
            return SecurityLog.isLoggingEnabled();
        }

        KeyChainConnection keyChainBind() throws InterruptedException {
            return KeyChain.bind(mContext);
        }

        KeyChainConnection keyChainBindAsUser(UserHandle user) throws InterruptedException {
            return KeyChain.bindAsUser(mContext, user);
        }

        void postOnSystemServerInitThreadPool(Runnable runnable) {
            SystemServerInitThreadPool.submit(runnable, LOG_TAG);
        }

        public TransferOwnershipMetadataManager newTransferOwnershipMetadataManager() {
            return new TransferOwnershipMetadataManager();
        }

        public void runCryptoSelfTest() {
            CryptoTestHelper.runAndLogSelfTest();
        }

        public String[] getPersonalAppsForSuspension(@UserIdInt int userId) {
            return PersonalAppsSuspensionHelper.forUser(mContext, userId)
                    .getPersonalAppsForSuspension();
        }

        public long systemCurrentTimeMillis() {
            return System.currentTimeMillis();
        }

        public boolean isChangeEnabled(long changeId, String packageName, int userId) {
            return CompatChanges.isChangeEnabled(changeId, packageName, UserHandle.of(userId));
        }

        void setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker) {
            mSafetyChecker = safetyChecker;
        }

        DeviceManagementResourcesProvider getDeviceManagementResourcesProvider() {
            return new DeviceManagementResourcesProvider();
        }

        boolean isAdminInstalledCaCertAutoApproved() {
            return false;
        }
    }

    /**
     * Instantiates the service.
     */
    public DevicePolicyManagerService(Context context) {
        this(new Injector(
                context.createAttributionContext(ATTRIBUTION_TAG)), new PolicyPathProvider() {});
    }

    @VisibleForTesting
    DevicePolicyManagerService(Injector injector, PolicyPathProvider pathProvider) {
        DevicePolicyManager.disableLocalCaches();

        mInjector = injector;
        mPathProvider = pathProvider;
        mContext = Objects.requireNonNull(injector.mContext);
        mHandler = new Handler(Objects.requireNonNull(injector.getMyLooper()));

        mConstantsObserver = new DevicePolicyConstantsObserver(mHandler);
        mConstantsObserver.register();
        mConstants = loadConstants();

        mUserManager = Objects.requireNonNull(injector.getUserManager());
        mUserManagerInternal = Objects.requireNonNull(injector.getUserManagerInternal());
        mUsageStatsManagerInternal = Objects.requireNonNull(
                injector.getUsageStatsManagerInternal());
        mIPackageManager = Objects.requireNonNull(injector.getIPackageManager());
        mIPermissionManager = Objects.requireNonNull(injector.getIPermissionManager());
        mTelephonyManager = Objects.requireNonNull(injector.getTelephonyManager());
        mRoleManager = Objects.requireNonNull(injector.getRoleManager());

        mLocalService = new LocalService();
        mLockPatternUtils = injector.newLockPatternUtils();
        mLockSettingsInternal = injector.getLockSettingsInternal();
        // TODO: why does SecurityLogMonitor need to be created even when mHasFeature == false?
        mSecurityLogMonitor = new SecurityLogMonitor(this);

        mHasFeature = mInjector.hasFeature();
        mIsWatch = mInjector.getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_WATCH);
        mHasTelephonyFeature = mInjector.getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
        mIsAutomotive = mInjector.getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
        mBackgroundHandler = BackgroundThread.getHandler();

        // Needed when mHasFeature == false, because it controls the certificate warning text.
        mCertificateMonitor = new CertificateMonitor(this, mInjector, mBackgroundHandler);

        mDeviceAdminServiceController = new DeviceAdminServiceController(this, mConstants);
        mOverlayPackagesProvider = new OverlayPackagesProvider(mContext);
        mTransferOwnershipMetadataManager = mInjector.newTransferOwnershipMetadataManager();
        mBugreportCollectionManager = new RemoteBugreportManager(this, mInjector);

        mDeviceManagementResourcesProvider = mInjector.getDeviceManagementResourcesProvider();
        mDevicePolicyManagementRoleObserver = new DevicePolicyManagementRoleObserver(mContext);
        mDevicePolicyManagementRoleObserver.register();

        // "Lite" interface is available even when the device doesn't have the feature
        LocalServices.addService(DevicePolicyManagerLiteInternal.class, mLocalService);

        // Policy version upgrade must not depend on either mOwners or mUserData, so they are
        // initialized only after performing the upgrade.
        if (mHasFeature) {
            performPolicyVersionUpgrade();
        }

        mUserData = new SparseArray<>();
        mOwners = makeOwners(injector, pathProvider);

        mDevicePolicyEngine = new DevicePolicyEngine(
                mContext, mDeviceAdminServiceController, getLockObject());

        if (!mHasFeature) {
            // Skip the rest of the initialization
            mSetupContentObserver = null;
            mContactSystemRoleHolders = Collections.emptySet();
            return;
        }

        loadOwners();

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_BOOT_COMPLETED);
        filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
        filter.addAction(ACTION_TURN_PROFILE_ON_NOTIFICATION);
        filter.addAction(ACTION_PROFILE_OFF_DEADLINE);
        filter.addAction(Intent.ACTION_USER_ADDED);
        filter.addAction(Intent.ACTION_USER_REMOVED);
        filter.addAction(Intent.ACTION_USER_STARTED);
        filter.addAction(Intent.ACTION_USER_STOPPED);
        filter.addAction(Intent.ACTION_USER_SWITCHED);
        filter.addAction(Intent.ACTION_USER_UNLOCKED);
        filter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION);
        filter.addAction(ACTION_MANAGED_PROFILE_UNAVAILABLE);
        filter.addAction(ACTION_MANAGED_PROFILE_AVAILABLE);
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
        filter = new IntentFilter();
        filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
        filter.addDataScheme("package");
        mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
        filter = new IntentFilter();
        filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
        filter.addAction(Intent.ACTION_TIME_CHANGED);
        filter.addAction(Intent.ACTION_DATE_CHANGED);
        mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);

        LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);

        mSetupContentObserver = new SetupContentObserver(mHandler);

        mUserManagerInternal.addUserRestrictionsListener(
                new RestrictionsListener(mContext, mUserManagerInternal, this));
        mUserManagerInternal.addUserLifecycleListener(new UserLifecycleListener());

        mDeviceManagementResourcesProvider.load();
        mDevicePolicyEngine.load();

        mContactSystemRoleHolders = fetchOemSystemHolders(/* roleResIds...= */
                com.android.internal.R.string.config_defaultSms,
                com.android.internal.R.string.config_defaultDialer,
                com.android.internal.R.string.config_systemContacts
        );

        // The binder caches are not enabled until the first invalidation.
        invalidateBinderCaches();
    }

    /**
     * Fetch the OEM System Holders for the supplied roleNames
     *
     * @param roleResIds the list of resource ids whose role holders are needed
     * @return the set of packageNames that handle the requested roles
     */
    private @NonNull Set<String> fetchOemSystemHolders(int... roleResIds) {
        Set<String> packageNames = new ArraySet<>();

        for (int roleResId : roleResIds) {
            String packageName = getDefaultRoleHolderPackageName(roleResId);
            if (packageName != null) {
                packageNames.add(packageName);
            }
        }

        return Collections.unmodifiableSet(packageNames);
    }


    private @Nullable String getDefaultRoleHolderPackageName(int resId) {
        String packageNameAndSignature = mContext.getString(resId);

        if (TextUtils.isEmpty(packageNameAndSignature)) {
            return null;
        }

        if (packageNameAndSignature.contains(":")) {
            return packageNameAndSignature.split(":")[0];
        }

        return packageNameAndSignature;
    }

    private void unsuspendAppsForQuietProfiles() {
        PackageManagerInternal pmi = mInjector.getPackageManagerInternal();
        List<UserInfo> users = mUserManagerInternal.getUsers(true /* excludeDying */);

        for (UserInfo user : users) {
            if (!user.isManagedProfile() || !user.isQuietModeEnabled()) {
                continue;
            }
            int userId = user.id;
            var suspendedByAdmin = getPackagesSuspendedByAdmin(userId);
            var packagesToUnsuspend = mInjector.getPackageManager(userId)
                    .getInstalledPackages(PackageManager.PackageInfoFlags.of(
                            MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE))
                    .stream()
                    .map(packageInfo -> packageInfo.packageName)
                    .filter(pkg -> !suspendedByAdmin.contains(pkg))
                    .toArray(String[]::new);

            Slogf.i(LOG_TAG, "Unsuspending work apps for user %d", userId);
            // When app suspension was used for quiet mode, the apps were suspended by platform
            // package, just like when admin suspends them. So although it wasn't admin who
            // suspended, this method will remove the right suspension record.
            pmi.setPackagesSuspendedByAdmin(userId, packagesToUnsuspend, false /* suspended */);
        }
    }

    private Owners makeOwners(Injector injector, PolicyPathProvider pathProvider) {
        return new Owners(
                injector.getUserManager(), injector.getUserManagerInternal(),
                injector.getPackageManagerInternal(),
                injector.getActivityTaskManagerInternal(),
                injector.getActivityManagerInternal(), mStateCache, pathProvider);
    }

    /**
     * Invalidate the binder API caches. The invalidation itself does not require any
     * locking, but this specific call should be protected by getLockObject() to ensure
     * that the invalidation is synchronous with cached queries, for those queries that
     * are served under getLockObject().
     */
    static void invalidateBinderCaches() {
        DevicePolicyManager.invalidateBinderCaches();
    }

    /**
     * Creates and loads the policy data from xml.
     * @param userHandle the user for whom to load the policy data
     * @return
     */
    @NonNull
    DevicePolicyData getUserData(int userHandle) {
        synchronized (getLockObject()) {
            DevicePolicyData policy = mUserData.get(userHandle);
            if (policy == null) {
                policy = new DevicePolicyData(userHandle);
                mUserData.append(userHandle, policy);
                loadSettingsLocked(policy, userHandle);
                if (userHandle == UserHandle.USER_SYSTEM) {
                    mStateCache.setDeviceProvisioned(policy.mUserSetupComplete);
                }
            }
            return policy;
        }
    }

    /**
     * Creates and loads the policy data from xml for data that is shared between
     * various profiles of a user. In contrast to {@link #getUserData(int)}
     * it allows access to data of users other than the calling user.
     *
     * This function should only be used for shared data, e.g. everything regarding
     * passwords and should be removed once multiple screen locks are present.
     * @param userHandle the user for whom to load the policy data
     * @return
     */
    DevicePolicyData getUserDataUnchecked(int userHandle) {
        return mInjector.binderWithCleanCallingIdentity(() -> getUserData(userHandle));
    }

    void removeUserData(int userHandle) {
        final boolean isOrgOwned;
        synchronized (getLockObject()) {
            if (userHandle == UserHandle.USER_SYSTEM) {
                Slogf.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
                return;
            }
            updatePasswordQualityCacheForUserGroup(userHandle);
            mPolicyCache.onUserRemoved(userHandle);

            if (isManagedProfile(userHandle)) {
                clearManagedProfileApnUnchecked();
            }
            isOrgOwned = mOwners.isProfileOwnerOfOrganizationOwnedDevice(userHandle);

            // Clear any restrictions set by the a profile owner and the parent admin.
            final ActiveAdmin admin = getProfileOwnerLocked(userHandle);
            if (admin != null) {
                admin.userRestrictions = null;
                final ActiveAdmin parentAdmin = admin.getParentActiveAdmin();
                if (parentAdmin != null) {
                    parentAdmin.userRestrictions = null;
                }
            }
            mOwners.removeProfileOwner(userHandle);
            mOwners.writeProfileOwner(userHandle);

            DevicePolicyData policy = mUserData.get(userHandle);
            if (policy != null) {
                mUserData.remove(userHandle);
            }

            File policyFile =
                    new File(mPathProvider.getUserSystemDirectory(userHandle), DEVICE_POLICIES_XML);
            policyFile.delete();
            Slogf.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
        }
        if (isOrgOwned) {
            final UserInfo primaryUser = mUserManager.getPrimaryUser();
            if (primaryUser != null) {
                clearOrgOwnedProfileOwnerDeviceWidePolicies(primaryUser.id);
            } else {
                Slogf.wtf(LOG_TAG, "Was unable to get primary user.");
            }
        }
    }

    /**
     * Load information about device and profile owners of the device, populating mOwners and
     * pushing owner info to other system services. This is called at a fairly early stage of
     * system server initialiation (via DevicePolicyManagerService's ctor), so care should to
     * be taken to not interact with system services that are initialiated after DPMS.
     * onLockSettingsReady() is a safer place to do initialization work not critical during
     * the first boot stage.
     * Note this only loads the list of owners, and not their actual policy (DevicePolicyData).
     * The policy is normally loaded lazily when it's first accessed. In several occasions
     * the list of owners is necessary for providing callers with aggregated policies across
     * multiple owners, hence the owner list is loaded as part of DPMS's construction here.
     */
    void loadOwners() {
        synchronized (getLockObject()) {
            mOwners.load();
            setDeviceOwnershipSystemPropertyLocked();
            if (mOwners.hasDeviceOwner()) {
                setGlobalSettingDeviceOwnerType(
                        mOwners.getDeviceOwnerType(mOwners.getDeviceOwnerPackageName()));
            }
        }
    }

    /**
     * Creates a new {@link CallerIdentity} object to represent the caller's identity.
     */
    private CallerIdentity getCallerIdentity() {
        return getCallerIdentity(null, null);
    }

    /**
     * Creates a new {@link CallerIdentity} object to represent the caller's identity.
     */
    private CallerIdentity getCallerIdentity(@Nullable String callerPackage) {
        return getCallerIdentity(null, callerPackage);
    }

    /**
     * Creates a new {@link CallerIdentity} object to represent the caller's identity.
     * The component name should be an active admin for the calling user.
     */
    @VisibleForTesting
    CallerIdentity getCallerIdentity(@Nullable ComponentName adminComponent) {
        return getCallerIdentity(adminComponent, null);
    }

    /**
     * Creates a new {@link CallerIdentity} object to represent the caller's identity.
     * If {@code adminComponent} is provided, it's validated against the list of known
     * active admins and caller uid. If {@code callerPackage} is provided, it's validated
     * against the caller uid. If a valid {@code adminComponent} is provided but not
     * {@code callerPackage}, the package name of the {@code adminComponent} is used instead.
     */
    @VisibleForTesting
    CallerIdentity getCallerIdentity(@Nullable ComponentName adminComponent,
            @Nullable String callerPackage) {
        final int callerUid = mInjector.binderGetCallingUid();

        if (callerPackage != null) {
            if (!isCallingFromPackage(callerPackage, callerUid)) {
                throw new SecurityException(
                        String.format("Caller with uid %d is not %s", callerUid, callerPackage));
            }
        }

        if (adminComponent != null) {
            final DevicePolicyData policy = getUserData(UserHandle.getUserId(callerUid));
            ActiveAdmin admin = policy.mAdminMap.get(adminComponent);

            // Throwing combined exception message for both the cases here, because from different
            // security exceptions it could be deduced if particular package is admin package.
            if (admin == null || admin.getUid() != callerUid) {
                throw new SecurityException(String.format(
                        "Admin %s does not exist or is not owned by uid %d", adminComponent,
                        callerUid));
            }
            if (callerPackage != null) {
                Preconditions.checkArgument(callerPackage.equals(adminComponent.getPackageName()));
            } else {
                callerPackage = adminComponent.getPackageName();
            }
        }

        return new CallerIdentity(callerUid, callerPackage, adminComponent);
    }

    /**
     * Checks if the device is in COMP mode, and if so migrates it to managed profile on a
     * corporate owned device.
     */
    @GuardedBy("getLockObject()")
    private void migrateToProfileOnOrganizationOwnedDeviceIfCompLocked() {
        if (VERBOSE_LOG) Slogf.d(LOG_TAG, "Checking whether we need to migrate COMP ");
        final int doUserId = mOwners.getDeviceOwnerUserId();
        if (doUserId == UserHandle.USER_NULL) {
            if (VERBOSE_LOG) Slogf.d(LOG_TAG, "No DO found, skipping migration.");
            return;
        }

        final List<UserInfo> profiles = mUserManager.getProfiles(doUserId);
        if (profiles.size() != 2) {
            if (profiles.size() == 1) {
                if (VERBOSE_LOG) Slogf.d(LOG_TAG, "Profile not found, skipping migration.");
            } else {
                Slogf.wtf(LOG_TAG, "Found " + profiles.size() + " profiles, skipping migration");
            }
            return;
        }

        final int poUserId = getManagedUserId(doUserId);
        if (poUserId < 0) {
            Slogf.wtf(LOG_TAG, "Found DO and a profile, but it is not managed, skipping migration");
            return;
        }

        final ActiveAdmin doAdmin = getDeviceOwnerAdminLocked();
        final ActiveAdmin poAdmin = getProfileOwnerAdminLocked(poUserId);
        if (doAdmin == null || poAdmin == null) {
            Slogf.wtf(LOG_TAG, "Failed to get either PO or DO admin, aborting migration.");
            return;
        }

        final ComponentName doAdminComponent = mOwners.getDeviceOwnerComponent();
        final ComponentName poAdminComponent = mOwners.getProfileOwnerComponent(poUserId);
        if (doAdminComponent == null || poAdminComponent == null) {
            Slogf.wtf(LOG_TAG, "Cannot find PO or DO component name, aborting migration.");
            return;
        }
        if (!doAdminComponent.getPackageName().equals(poAdminComponent.getPackageName())) {
            Slogf.e(LOG_TAG, "DO and PO are different packages, aborting migration.");
            return;
        }

        Slogf.i(LOG_TAG, "Migrating COMP to PO on a corp owned device; primary user: %d; "
                + "profile: %d", doUserId, poUserId);

        Slogf.i(LOG_TAG, "Giving the PO additional power...");
        setProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(poAdminComponent, poUserId, true);
        Slogf.i(LOG_TAG, "Migrating DO policies to PO...");
        moveDoPoliciesToProfileParentAdminLocked(doAdmin, poAdmin.getParentActiveAdmin());
        migratePersonalAppSuspensionLocked(doUserId, poUserId, poAdmin);
        saveSettingsLocked(poUserId);
        Slogf.i(LOG_TAG, "Clearing the DO...");
        final ComponentName doAdminReceiver = doAdmin.info.getComponent();
        clearDeviceOwnerLocked(doAdmin, doUserId);
        Slogf.i(LOG_TAG, "Removing admin artifacts...");
        removeAdminArtifacts(doAdminReceiver, doUserId);
        Slogf.i(LOG_TAG, "Uninstalling the DO...");
        uninstallOrDisablePackage(doAdminComponent.getPackageName(), doUserId);
        Slogf.i(LOG_TAG, "Migration complete.");

        // Note: KeyChain keys are not removed and will remain accessible for the apps that have
        // been given grants to use them.

        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.COMP_TO_ORG_OWNED_PO_MIGRATED)
                .setAdmin(poAdminComponent)
                .write();
    }

    @GuardedBy("getLockObject()")
    private void migratePersonalAppSuspensionLocked(
            int doUserId, int poUserId, ActiveAdmin poAdmin) {
        final PackageManagerInternal pmi = mInjector.getPackageManagerInternal();
        if (!pmi.isAdminSuspendingAnyPackages(doUserId)) {
            Slogf.i(LOG_TAG, "DO is not suspending any apps.");
            return;
        }

        if (getTargetSdk(poAdmin.info.getPackageName(), poUserId) >= Build.VERSION_CODES.R) {
            Slogf.i(LOG_TAG, "PO is targeting R+, keeping personal apps suspended.");
            getUserData(doUserId).mAppsSuspended = true;
            poAdmin.mSuspendPersonalApps = true;
        } else {
            Slogf.i(LOG_TAG, "PO isn't targeting R+, unsuspending personal apps.");
            pmi.unsuspendAdminSuspendedPackages(doUserId);
        }
    }

    private void uninstallOrDisablePackage(String packageName, @UserIdInt int userId) {
        final ApplicationInfo appInfo;
        try {
            appInfo = mIPackageManager.getApplicationInfo(
                    packageName, MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, userId);
        } catch (RemoteException e) {
            // Shouldn't happen.
            Slogf.wtf(LOG_TAG, "Error getting application info", e);
            return;
        }
        if (appInfo == null) {
            Slogf.wtf(LOG_TAG, "Failed to get package info for " + packageName);
            return;
        }
        if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
            Slogf.i(LOG_TAG, "Package %s is pre-installed, marking disabled until used",
                    packageName);
            mContext.getPackageManager().setApplicationEnabledSetting(packageName,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED, /* flags= */ 0);
            return;
        }

        final IIntentSender.Stub mLocalSender = new IIntentSender.Stub() {
            @Override
            public void send(int code, Intent intent, String resolvedType, IBinder allowlistToken,
                    IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) {
                final int status = intent.getIntExtra(
                        PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE);
                if (status == PackageInstaller.STATUS_SUCCESS) {
                    Slogf.i(LOG_TAG, "Package %s uninstalled for user %d", packageName, userId);
                } else {
                    Slogf.e(LOG_TAG, "Failed to uninstall %s; status: %d", packageName, status);
                }
            }
        };

        final PackageInstaller pi = mInjector.getPackageManager(userId).getPackageInstaller();
        pi.uninstall(packageName, /* flags= */ 0, new IntentSender((IIntentSender) mLocalSender));
    }

    @GuardedBy("getLockObject()")
    private void moveDoPoliciesToProfileParentAdminLocked(
            ActiveAdmin doAdmin, ActiveAdmin parentAdmin) {
        // The following policies can be already controlled via parent instance, skip if so.
        if (parentAdmin.mPasswordPolicy.quality == PASSWORD_QUALITY_UNSPECIFIED) {
            parentAdmin.mPasswordPolicy = doAdmin.mPasswordPolicy;
        }
        if (parentAdmin.passwordHistoryLength == ActiveAdmin.DEF_PASSWORD_HISTORY_LENGTH) {
            parentAdmin.passwordHistoryLength = doAdmin.passwordHistoryLength;
        }
        if (parentAdmin.passwordExpirationTimeout == ActiveAdmin.DEF_PASSWORD_HISTORY_LENGTH) {
            parentAdmin.passwordExpirationTimeout = doAdmin.passwordExpirationTimeout;
        }
        if (parentAdmin.maximumFailedPasswordsForWipe
                == ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
            parentAdmin.maximumFailedPasswordsForWipe = doAdmin.maximumFailedPasswordsForWipe;
        }
        if (parentAdmin.maximumTimeToUnlock == ActiveAdmin.DEF_MAXIMUM_TIME_TO_UNLOCK) {
            parentAdmin.maximumTimeToUnlock = doAdmin.maximumTimeToUnlock;
        }
        if (parentAdmin.strongAuthUnlockTimeout
                == DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
            parentAdmin.strongAuthUnlockTimeout = doAdmin.strongAuthUnlockTimeout;
        }
        parentAdmin.disabledKeyguardFeatures |=
                doAdmin.disabledKeyguardFeatures & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;

        parentAdmin.trustAgentInfos.putAll(doAdmin.trustAgentInfos);

        // The following policies weren't available to PO, but will be available after migration.
        parentAdmin.disableCamera = doAdmin.disableCamera;
        parentAdmin.disableScreenCapture = doAdmin.disableScreenCapture;
        parentAdmin.accountTypesWithManagementDisabled.addAll(
                doAdmin.accountTypesWithManagementDisabled);

        moveDoUserRestrictionsToCopeParent(doAdmin, parentAdmin);

        // From Android 11, {@link setAutoTimeRequired} is no longer used. The user restriction
        // {@link UserManager#DISALLOW_CONFIG_DATE_TIME} should be used to enforce auto time
        // settings instead.
        if (doAdmin.requireAutoTime) {
            parentAdmin.ensureUserRestrictions().putBoolean(
                    UserManager.DISALLOW_CONFIG_DATE_TIME, true);
        }
    }

    private void moveDoUserRestrictionsToCopeParent(ActiveAdmin doAdmin, ActiveAdmin parentAdmin) {
        if (doAdmin.userRestrictions == null) {
            return;
        }
        for (final String restriction : doAdmin.userRestrictions.keySet()) {
            if (UserRestrictionsUtils.canProfileOwnerOfOrganizationOwnedDeviceChange(restriction)) {
                parentAdmin.ensureUserRestrictions().putBoolean(
                        restriction, doAdmin.userRestrictions.getBoolean(restriction));
            }
        }
    }

    /**
     * If the device is in Device Owner mode, apply the restriction on adding
     * a managed profile.
     */
    @GuardedBy("getLockObject()")
    private void applyProfileRestrictionsIfDeviceOwnerLocked() {
        final int doUserId = mOwners.getDeviceOwnerUserId();
        if (doUserId == UserHandle.USER_NULL) {
            if (VERBOSE_LOG) Slogf.d(LOG_TAG, "No DO found, skipping application of restriction.");
            return;
        }

        for (UserInfo userInfo : mUserManager.getUsers()) {
            UserHandle userHandle = userInfo.getUserHandle();
            // Based on  CDD : https://source.android.com/compatibility/12/android-12-cdd#95_multi-user_support,
            // creation of clone profile is not allowed in case device owner is set.
            // Enforcing this restriction on setting up of device owner.
            if (!mUserManager.hasUserRestriction(
                    UserManager.DISALLOW_ADD_CLONE_PROFILE, userHandle)) {
                mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_CLONE_PROFILE, true,
                        userHandle);
            }
            // Enforcing the restriction of private profile creation in case device owner is set.
            if (!mUserManager.hasUserRestriction(
                    UserManager.DISALLOW_ADD_PRIVATE_PROFILE, userHandle)) {
                mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_PRIVATE_PROFILE, true,
                        userHandle);
            }
            // Creation of managed profile is restricted in case device owner is set, enforcing this
            // restriction by setting user level restriction at time of device owner setup.
            if (!mUserManager.hasUserRestriction(
                    UserManager.DISALLOW_ADD_MANAGED_PROFILE, userHandle)) {
                mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, true,
                        userHandle);
            }
        }
    }

    /** Apply default restrictions that haven't been applied to profile owners yet. */
    private void maybeSetDefaultProfileOwnerUserRestrictions() {
        synchronized (getLockObject()) {
            for (final int userId : mOwners.getProfileOwnerKeys()) {
                final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
                // The following restrictions used to be applied to managed profiles by different
                // means (via Settings or by disabling components). Now they are proper user
                // restrictions so we apply them to managed profile owners. Non-managed secondary
                // users didn't have those restrictions so we skip them to keep existing behavior.
                if (profileOwner == null || !mUserManager.isManagedProfile(userId)) {
                    continue;
                }
                maybeSetDefaultRestrictionsForAdminLocked(userId, profileOwner);
                ensureUnknownSourcesRestrictionForProfileOwnerLocked(
                        userId, profileOwner, false /* newOwner */);
            }
        }
    }

    /**
     * Checks whether {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES} should be added to the
     * set of restrictions for this profile owner.
     */
    private void ensureUnknownSourcesRestrictionForProfileOwnerLocked(int userId,
            ActiveAdmin profileOwner, boolean newOwner) {
        if (newOwner || mInjector.settingsSecureGetIntForUser(
                Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId) != 0) {
            mDevicePolicyEngine.setLocalPolicy(
                    PolicyDefinition.getPolicyDefinitionForUserRestriction(
                            UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
                    EnforcingAdmin.createEnterpriseEnforcingAdmin(
                            profileOwner.info.getComponent(),
                            profileOwner.getUserHandle().getIdentifier()),
                    new BooleanPolicyValue(true),
                    userId);
            mInjector.settingsSecurePutIntForUser(
                    Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId);
        }
    }

    /**
     * Apply default restrictions that haven't been applied to a given admin yet.
     */
    private void maybeSetDefaultRestrictionsForAdminLocked(int userId, ActiveAdmin admin) {
        Set<String> defaultRestrictions =
                UserRestrictionsUtils.getDefaultEnabledForManagedProfiles();
        if (defaultRestrictions.equals(admin.defaultEnabledRestrictionsAlreadySet)) {
            return; // The same set of default restrictions has been already applied.
        }
        for (String restriction : defaultRestrictions) {
            mDevicePolicyEngine.setLocalPolicy(
                    PolicyDefinition.getPolicyDefinitionForUserRestriction(restriction),
                    EnforcingAdmin.createEnterpriseEnforcingAdmin(
                            admin.info.getComponent(),
                            admin.getUserHandle().getIdentifier()),
                    new BooleanPolicyValue(true),
                    userId);
        }
        admin.defaultEnabledRestrictionsAlreadySet.addAll(defaultRestrictions);
        Slogf.i(LOG_TAG, "Enabled the following restrictions by default: "
                + defaultRestrictions);
    }

    private void setDeviceOwnershipSystemPropertyLocked() {
        final boolean deviceProvisioned =
                mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) != 0;
        final boolean hasDeviceOwner = mOwners.hasDeviceOwner();
        final boolean hasOrgOwnedProfile = isOrganizationOwnedDeviceWithManagedProfile();
        // If the device is not provisioned and there is currently no management, do not set the
        // read-only system property yet, since device owner / org-owned profile may still be
        // provisioned.
        if (!hasDeviceOwner && !hasOrgOwnedProfile && !deviceProvisioned) {
            return;
        }
        final String value = Boolean.toString(hasDeviceOwner || hasOrgOwnedProfile);
        final String currentVal = mInjector.systemPropertiesGet(PROPERTY_ORGANIZATION_OWNED, null);
        if (TextUtils.isEmpty(currentVal)) {
            Slogf.i(LOG_TAG, "Set ro.organization_owned property to " + value);
            mInjector.systemPropertiesSet(PROPERTY_ORGANIZATION_OWNED, value);
        } else if (!value.equals(currentVal)) {
            Slogf.w(LOG_TAG, "Cannot change existing ro.organization_owned to " + value);
        }
    }

    private void maybeStartSecurityLogMonitorOnActivityManagerReady() {
        synchronized (getLockObject()) {
            if (mInjector.securityLogIsLoggingEnabled()) {
                mSecurityLogMonitor.start(getSecurityLoggingEnabledUser());
                mInjector.runCryptoSelfTest();
                maybePauseDeviceWideLoggingLocked();
            }
        }
    }

    /**
     * Fix left-over restrictions and auto-time policy during COMP -> COPE migration.
     *
     * When a COMP device with requireAutoTime policy set was migrated to an
     * organization-owned profile, a DISALLOW_CONFIG_DATE_TIME restriction is set
     * on user 0 from the DO user, which becomes unremovable by the organization-owned
     * profile owner. Fix this by force removing that restriction. Also revert the
     * parentAdmin.requireAutoTime bit (since the COPE PO cannot unset this bit)
     * and replace it with DISALLOW_CONFIG_DATE_TIME on the correct
     * admin, in line with the deprecation recommendation of setAutoTimeRequired().
     */
    private void fixupAutoTimeRestrictionDuringOrganizationOwnedDeviceMigration() {
        for (UserInfo ui : mUserManager.getUsers()) {
            final int userId = ui.id;
            if (isProfileOwnerOfOrganizationOwnedDevice(userId)) {
                final ActiveAdmin parent = getProfileOwnerAdminLocked(userId).parentAdmin;
                if (parent != null && parent.requireAutoTime) {
                    // Remove deprecated requireAutoTime
                    parent.requireAutoTime = false;
                    saveSettingsLocked(userId);

                    // Remove user restrictions set by the device owner before the upgrade to
                    // Android 11.
                    mUserManagerInternal.setDevicePolicyUserRestrictions(UserHandle.USER_SYSTEM,
                            new Bundle(), new RestrictionsSet(), /* isDeviceOwner */ false);

                    // Apply user restriction to parent active admin instead
                    parent.ensureUserRestrictions().putBoolean(
                            UserManager.DISALLOW_CONFIG_DATE_TIME, true);
                }
            }
        }
    }

    /**
     * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
     * reminders.  Clears alarm if no expirations are configured.
     */
    private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
        final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
        final long now = System.currentTimeMillis();
        final long timeToExpire = expiration - now;
        final long alarmTime;
        if (expiration == 0) {
            // No expirations are currently configured:  Cancel alarm.
            alarmTime = 0;
        } else if (timeToExpire <= 0) {
            // The password has already expired:  Repeat every 24 hours.
            alarmTime = now + MS_PER_DAY;
        } else {
            // Selecting the next alarm time:  Roll forward to the next 24 hour multiple before
            // the expiration time.
            long alarmInterval = timeToExpire % MS_PER_DAY;
            if (alarmInterval == 0) {
                alarmInterval = MS_PER_DAY;
            }
            alarmTime = now + alarmInterval;
        }

        mInjector.binderWithCleanCallingIdentity(() -> {
            int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
            AlarmManager am = mInjector.getAlarmManager();
            // Broadcast alarms sent by system are immutable
            PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
                    new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
                    PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT
                            | PendingIntent.FLAG_IMMUTABLE,
                    UserHandle.of(affectedUserHandle));
            am.cancel(pi);
            if (alarmTime != 0) {
                am.set(AlarmManager.RTC, alarmTime, pi);
            }
        });
    }

    ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
        ensureLocked();
        ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
        if (admin != null
                && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
                && who.getClassName().equals(admin.info.getActivityInfo().name)) {
            return admin;
        }
        return null;
    }

    ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
        ensureLocked();
        if (parent) {
            Preconditions.checkCallAuthorization(isManagedProfile(userHandle),
                    "You can not call APIs on the parent profile outside a managed profile, "
                            + "userId = %d", userHandle);
        }
        ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
        if (admin != null && parent) {
            admin = admin.getParentActiveAdmin();
        }
        return admin;
    }

    ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
            throws SecurityException {
        return getActiveAdminOrCheckPermissionForCallerLocked(who,
                reqPolicy, /* permission= */ null);
    }

    ActiveAdmin getDeviceOwnerLocked(@UserIdInt int userId) {
        ensureLocked();
        ComponentName doComponent = mOwners.getDeviceOwnerComponent();
        ActiveAdmin doAdmin = getUserData(userId).mAdminMap.get(doComponent);
        return doAdmin;
    }

    ActiveAdmin getDefaultDeviceOwnerLocked(@UserIdInt int userId) {
        ensureLocked();
        ComponentName doComponent = mOwners.getDeviceOwnerComponent();
        if (mOwners.getDeviceOwnerType(doComponent.getPackageName()) == DEFAULT_DEVICE_OWNER) {
            ActiveAdmin doAdmin = getUserData(userId).mAdminMap.get(doComponent);
            return doAdmin;
        }
        return null;
    }

    ActiveAdmin getProfileOwnerLocked(@UserIdInt int userId) {
        ensureLocked();
        final ComponentName poAdminComponent = mOwners.getProfileOwnerComponent(userId);
        ActiveAdmin poAdmin = getUserData(userId).mAdminMap.get(poAdminComponent);
        return poAdmin;
    }

    @NonNull ActiveAdmin getOrganizationOwnedProfileOwnerLocked(final CallerIdentity caller) {
        Preconditions.checkCallAuthorization(
                mOwners.isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId()),
                "Caller %s is not an admin of an org-owned device",
                caller.getComponentName());
        final ActiveAdmin profileOwner = getProfileOwnerLocked(caller.getUserId());

        return profileOwner;
    }

    ActiveAdmin getProfileOwnerOrDeviceOwnerLocked(@UserIdInt int userId) {
        ensureLocked();
        // Try to find an admin which can use reqPolicy
        final ComponentName poAdminComponent = mOwners.getProfileOwnerComponent(userId);

        if (poAdminComponent != null) {
            return getProfileOwnerLocked(userId);
        }

        return getDeviceOwnerLocked(userId);
    }

    ActiveAdmin getProfileOwnerOrDefaultDeviceOwnerLocked(@UserIdInt int userId) {
        ensureLocked();
        // Try to find an admin which can use reqPolicy
        final ComponentName poAdminComponent = mOwners.getProfileOwnerComponent(userId);

        if (poAdminComponent != null) {
            return getProfileOwnerLocked(userId);
        }

        return getDefaultDeviceOwnerLocked(userId);
    }

    @NonNull ActiveAdmin getParentOfAdminIfRequired(ActiveAdmin admin, boolean parent) {
        Objects.requireNonNull(admin);
        return parent ? admin.getParentActiveAdmin() : admin;
    }

    /**
     * Finds an active admin for the caller then checks {@code permission} if admin check failed.
     *
     * @return an active admin or {@code null} if there is no active admin but
     * {@code permission} is granted
     * @throws SecurityException if caller neither has an active admin nor {@code permission}
     */
    @Nullable
    ActiveAdmin getActiveAdminOrCheckPermissionForCallerLocked(
            ComponentName who,
            int reqPolicy,
            @Nullable String permission) throws SecurityException {
        return getActiveAdminOrCheckPermissionsForCallerLocked(
                who, reqPolicy, permission == null ? Set.of() : Set.of(permission));
    }

    /**
     * Finds an active admin for the caller then checks {@code permissions} if admin check failed.
     *
     * @return an active admin or {@code null} if there is no active admin but
     * one of {@code permissions} is granted
     * @throws SecurityException if caller neither has an active admin nor {@code permission}
     */
    @Nullable
    ActiveAdmin getActiveAdminOrCheckPermissionsForCallerLocked(
            ComponentName who,
            int reqPolicy,
            Set<String> permissions) throws SecurityException {
        ensureLocked();
        final CallerIdentity caller = getCallerIdentity();

        ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, caller.getUid());
        if (result != null) {
            return result;
        } else {
            for (String permission : permissions) {
                if (hasCallingPermission(permission)) {
                    return null;
                }
            }
        }

        // Code for handling failure from getActiveAdminWithPolicyForUidLocked to find an admin
        // that satisfies the required policy.
        // Throws a security exception with the right error message.
        if (who != null) {
            final DevicePolicyData policy = getUserData(caller.getUserId());
            ActiveAdmin admin = policy.mAdminMap.get(who);
            final boolean isDeviceOwner = isDeviceOwner(admin.info.getComponent(),
                    caller.getUserId());
            final boolean isProfileOwner = isProfileOwner(admin.info.getComponent(),
                    caller.getUserId());

            if (DA_DISALLOWED_POLICIES.contains(reqPolicy) && !isDeviceOwner && !isProfileOwner) {
                throw new SecurityException("Admin " + admin.info.getComponent()
                        + " is not a device owner or profile owner, so may not use policy: "
                        + admin.info.getTagForPolicy(reqPolicy));
            }
            throw new SecurityException("Admin " + admin.info.getComponent()
                    + " did not specify uses-policy for: "
                    + admin.info.getTagForPolicy(reqPolicy));
        } else {
            throw new SecurityException("No active admin owned by uid "
                    + caller.getUid() + " for policy #" + reqPolicy + (permissions.isEmpty() ? ""
                    : ", which doesn't have " + permissions));
        }
    }

    ActiveAdmin getActiveAdminForCallerLocked(@Nullable ComponentName who, int reqPolicy,
            boolean parent) throws SecurityException {
        return getActiveAdminOrCheckPermissionForCallerLocked(
                who, reqPolicy, parent, /* permission= */ null);
    }

    /**
     * Finds an active admin for the caller then checks {@code permission} if admin check failed.
     *
     * @return an active admin or {@code null} if there is no active admin but
     * {@code permission} is granted
     * @throws SecurityException if caller neither has an active admin nor {@code permission}
     */
    @Nullable
    ActiveAdmin getActiveAdminOrCheckPermissionForCallerLocked(
            @Nullable ComponentName who,
            int reqPolicy,
            boolean parent,
            @Nullable String permission) throws SecurityException {
        return getActiveAdminOrCheckPermissionsForCallerLocked(
                who, reqPolicy, parent, permission == null ? Set.of() : Set.of(permission));
    }

    /**
     * Finds an active admin for the caller then checks {@code permission} if admin check failed.
     *
     * @return an active admin or {@code null} if there is no active admin but
     * {@code permission} is granted
     * @throws SecurityException if caller neither has an active admin nor {@code permission}
     */
    @Nullable
    ActiveAdmin getActiveAdminOrCheckPermissionsForCallerLocked(
            @Nullable ComponentName who,
            int reqPolicy,
            boolean parent,
            Set<String> permissions) throws SecurityException {
        ensureLocked();
        if (parent) {
            Preconditions.checkCallingUser(isManagedProfile(getCallerIdentity().getUserId()));
        }
        ActiveAdmin admin = getActiveAdminOrCheckPermissionsForCallerLocked(
                who, reqPolicy, permissions);
        return parent ? admin.getParentActiveAdmin() : admin;
    }

    /**
     * Find the admin for the component and userId bit of the uid, then check
     * the admin's uid matches the uid.
     */
    private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
        ensureLocked();
        final int userId = UserHandle.getUserId(uid);
        final DevicePolicyData policy = getUserData(userId);
        ActiveAdmin admin = policy.mAdminMap.get(who);
        if (admin == null) {
            throw new SecurityException("No active admin " + who + " for UID " + uid);
        }
        if (admin.getUid() != uid) {
            throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
        }
        return admin;
    }

    /**
     * Returns the active admin for the user of the caller as denoted by uid, which implements
     * the {@code reqPolicy}.
     *
     * The {@code who} parameter is used as a hint:
     * If provided, it must be the component name of the active admin for that user and the caller
     * uid must match the uid of the admin.
     * If not provided, iterate over all of the active admins in the DevicePolicyData for that user
     * and return the one with the uid specified as parameter, and has the policy specified.
     */
    @Nullable
    private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
            int uid) {
        ensureLocked();
        // Try to find an admin which can use reqPolicy
        final int userId = UserHandle.getUserId(uid);
        final DevicePolicyData policy = getUserData(userId);
        if (who != null) {
            ActiveAdmin admin = policy.mAdminMap.get(who);
            if (admin == null || admin.getUid() != uid) {
                throw new SecurityException(
                        "Admin " + who + " is not active or not owned by uid " + uid);
            }
            if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
                return admin;
            }
        } else {
            for (ActiveAdmin admin : policy.mAdminList) {
                if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
                        userId)) {
                    return admin;
                }
            }
        }

        return null;
    }

    @VisibleForTesting
    boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
            int userId) {
        ensureLocked();
        final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
        final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);

        boolean allowedToUsePolicy = ownsDevice || ownsProfile
                || !DA_DISALLOWED_POLICIES.contains(reqPolicy)
                || getTargetSdk(admin.info.getPackageName(), userId) < Build.VERSION_CODES.Q;
        return allowedToUsePolicy && admin.info.usesPolicy(reqPolicy);
    }

    void sendAdminCommandLocked(ActiveAdmin admin, String action) {
        sendAdminCommandLocked(admin, action, null);
    }

    void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
        sendAdminCommandLocked(admin, action, null, result);
    }

    void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
            BroadcastReceiver result) {
        sendAdminCommandLocked(admin, action, adminExtras, result, false);
    }

    /**
     * Send an update to one specific admin, get notified when that admin returns a result.
     *
     * @return whether the broadcast was successfully sent
     */
    boolean sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
            BroadcastReceiver result, boolean inForeground) {
        Intent intent = new Intent(action);
        intent.setComponent(admin.info.getComponent());
        if (UserManager.isDeviceInDemoMode(mContext)) {
            intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        }
        if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
            intent.putExtra("expiration", admin.passwordExpirationDate);
        }
        if (inForeground) {
            intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        }
        if (adminExtras != null) {
            intent.putExtras(adminExtras);
        }
        if (mInjector.getPackageManager().queryBroadcastReceiversAsUser(
                intent,
                PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
                admin.getUserHandle()).isEmpty()) {
            return false;
        }

        final BroadcastOptions options = BroadcastOptions.makeBasic();
        options.setBackgroundActivityStartsAllowed(true);

        if (result != null) {
            mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
                    null, AppOpsManager.OP_NONE, options.toBundle(),
                    result, mHandler, Activity.RESULT_OK, null, null);
        } else {
            mContext.sendBroadcastAsUser(intent, admin.getUserHandle(), null, options.toBundle());
        }

        return true;
    }

    /**
     * Send an update to all admins of a user that enforce a specified policy.
     */
    void sendAdminCommandLocked(String action, int reqPolicy, int userHandle, Bundle adminExtras) {
        final DevicePolicyData policy = getUserData(userHandle);
        final int count = policy.mAdminList.size();
        for (int i = 0; i < count; i++) {
            final ActiveAdmin admin = policy.mAdminList.get(i);
            if (admin.info.usesPolicy(reqPolicy)) {
                sendAdminCommandLocked(admin, action, adminExtras, null);
            }
        }
    }

    /**
     * Send an update intent to all admins of a user and its profiles. Only send to admins that
     * enforce a specified policy.
     */
    private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
            int userHandle, Bundle adminExtras) {
        int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
        for (int profileId : profileIds) {
            sendAdminCommandLocked(action, reqPolicy, profileId, adminExtras);
        }
    }

    /**
     * Sends a broadcast to each profile that share the password unlock with the given user id.
     */
    private void sendAdminCommandForLockscreenPoliciesLocked(
            String action, int reqPolicy, int userHandle) {
        final Bundle extras = new Bundle();
        extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
        if (isSeparateProfileChallengeEnabled(userHandle)) {
            sendAdminCommandLocked(action, reqPolicy, userHandle, extras);
        } else {
            sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle, extras);
        }
    }

    void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
        final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
        DevicePolicyData policy = getUserData(userHandle);
        if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) {
            Slogf.d(LOG_TAG, "Adding " + adminReceiver + " for user " + userHandle
                    + " to list of removing admins.");
            logStackTrace("removeActiveAdminLocked");

            policy.mRemovingAdmins.add(adminReceiver);
            sendAdminCommandLocked(admin,
                    DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
                    new BroadcastReceiver() {
                        @Override
                        public void onReceive(Context context, Intent intent) {
                            removeAdminArtifacts(adminReceiver, userHandle);
                            removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
                        }
                    });
        }
    }

    private DeviceAdminInfo findAdmin(final ComponentName adminName, final int userHandle,
            boolean throwForMissingPermission) {
        final ActivityInfo ai = mInjector.binderWithCleanCallingIdentity(() -> {
            try {
                return mIPackageManager.getReceiverInfo(adminName,
                        GET_META_DATA
                        | PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS
                        | PackageManager.MATCH_DIRECT_BOOT_AWARE
                        | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
            } catch (RemoteException e) {
                // shouldn't happen.
                Slogf.wtf(LOG_TAG, "Error getting receiver info", e);
                return null;
            }
        });
        if (ai == null) {
            throw new IllegalArgumentException("Unknown admin: " + adminName);
        }

        if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
            final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
                    + permission.BIND_DEVICE_ADMIN;
            Slogf.w(LOG_TAG, message);
            if (throwForMissingPermission &&
                    ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
                throw new IllegalArgumentException(message);
            }
        }

        try {
            return new DeviceAdminInfo(mContext, ai);
        } catch (XmlPullParserException | IOException e) {
            Slogf.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
                    e);
            return null;
        }
    }

    private File getPolicyFileDirectory(@UserIdInt int userId) {
        return userId == UserHandle.USER_SYSTEM
                ? mPathProvider.getDataSystemDirectory()
                : mPathProvider.getUserSystemDirectory(userId);
    }

    private JournaledFile makeJournaledFile(@UserIdInt int userId, String fileName) {
        final String base = new File(getPolicyFileDirectory(userId), fileName)
                .getAbsolutePath();
        if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Opening %s", base);
        return new JournaledFile(new File(base), new File(base + ".tmp"));
    }

    private JournaledFile makeJournaledFile(@UserIdInt int userId) {
        return makeJournaledFile(userId, DEVICE_POLICIES_XML);
    }

    /**
     * Persist modified values to disk by calling {@link #saveSettingsLocked} for each
     * affected user ID.
     */
    @GuardedBy("getLockObject()")
    private void saveSettingsForUsersLocked(Set<Integer> affectedUserIds) {
        for (int userId : affectedUserIds) {
            saveSettingsLocked(userId);
        }
    }

    private void saveSettingsLocked(int userHandle) {
        if (DevicePolicyData.store(getUserData(userHandle), makeJournaledFile(userHandle))) {
            sendChangedNotification(userHandle);
        }
        invalidateBinderCaches();
    }

    private void sendChangedNotification(int userHandle) {
        Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
        intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
        Bundle options = new BroadcastOptions()
                .setDeliveryGroupPolicy(BroadcastOptions.DELIVERY_GROUP_POLICY_MOST_RECENT)
                .setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_UNTIL_ACTIVE)
                .toBundle();
        mInjector.binderWithCleanCallingIdentity(() ->
                mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle), null, options));
    }

    private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
        DevicePolicyData.load(policy,
                makeJournaledFile(userHandle),
                component -> findAdmin(
                        component, userHandle, /* throwForMissingPermission= */ false),
                getOwnerComponent(userHandle));

        policy.validatePasswordOwner();
        updateMaximumTimeToLockLocked(userHandle);
        if (policy.mStatusBarDisabled) {
            setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
        }
    }

    static void updateLockTaskPackagesLocked(Context context, List<String> packages, int userId) {
        Binder.withCleanCallingIdentity(() -> {

            String[] packagesArray = null;
            if (!packages.isEmpty()) {
                // When adding packages, we need to include the exempt apps so they can still be
                // launched (ideally we should use a different AM API as these apps don't need to
                // use lock-task mode).
                // They're not added when the packages is empty though, as in that case we're
                // disabling lock-task mode.
                List<String> exemptApps = listPolicyExemptAppsUnchecked(context);
                if (!exemptApps.isEmpty()) {
                    // TODO(b/175377361): add unit test to verify it (cannot be CTS because the
                    //  policy-exempt apps are provided by OEM and the test would have no control
                    //  over it) once tests are migrated to the new infra-structure
                    HashSet<String> updatedPackages = new HashSet<>(packages);
                    updatedPackages.addAll(exemptApps);
                    if (VERBOSE_LOG) {
                        Slogf.v(LOG_TAG, "added %d policy-exempt apps to %d lock task "
                                + "packages. Final list: %s",
                                exemptApps.size(), packages.size(), updatedPackages);
                    }
                    packagesArray = updatedPackages.toArray(new String[updatedPackages.size()]);
                }
            }

            if (packagesArray == null) {
                packagesArray = packages.toArray(new String[packages.size()]);
            }
            try {
                ActivityManager.getService().updateLockTaskPackages(userId, packagesArray);
            } catch (RemoteException e) {
                // Shouldn't happen.
                Slog.wtf(LOG_TAG, "Remote Exception: ", e);
            }
        });
    }

    static void updateLockTaskFeaturesLocked(int flags, int userId) {
        Binder.withCleanCallingIdentity(() -> {
            try {
                ActivityTaskManager.getService().updateLockTaskFeatures(userId, flags);
            } catch (RemoteException e) {
                // Shouldn't happen.
                Slog.wtf(LOG_TAG, "Remote Exception: ", e);
            }
        });
    }

    static void validateQualityConstant(int quality) {
        switch (quality) {
            case PASSWORD_QUALITY_UNSPECIFIED:
            case PASSWORD_QUALITY_BIOMETRIC_WEAK:
            case PASSWORD_QUALITY_SOMETHING:
            case PASSWORD_QUALITY_NUMERIC:
            case PASSWORD_QUALITY_NUMERIC_COMPLEX:
            case PASSWORD_QUALITY_ALPHABETIC:
            case PASSWORD_QUALITY_ALPHANUMERIC:
            case PASSWORD_QUALITY_COMPLEX:
            case PASSWORD_QUALITY_MANAGED:
                return;
        }
        throw new IllegalArgumentException("Invalid quality constant: 0x"
                + Integer.toHexString(quality));
    }

    @VisibleForTesting
    void systemReady(int phase) {
        if (!mHasFeature) {
            return;
        }
        switch (phase) {
            case SystemService.PHASE_LOCK_SETTINGS_READY:
                onLockSettingsReady();
                loadAdminDataAsync();
                mOwners.systemReady();
                applyManagedSubscriptionsPolicyIfRequired();
                break;
            case SystemService.PHASE_SYSTEM_SERVICES_READY:
                synchronized (getLockObject()) {
                    mDevicePolicyEngine.reapplyAllPoliciesLocked();
                }
                break;
            case SystemService.PHASE_ACTIVITY_MANAGER_READY:
                synchronized (getLockObject()) {
                    migrateToProfileOnOrganizationOwnedDeviceIfCompLocked();
                    applyProfileRestrictionsIfDeviceOwnerLocked();

                    // TODO: Is this the right place to trigger the migration?
                    if (shouldMigrateToDevicePolicyEngine()) {
                        migratePoliciesToDevicePolicyEngine();
                    }
                }
                maybeStartSecurityLogMonitorOnActivityManagerReady();
                break;
            case SystemService.PHASE_BOOT_COMPLETED:
                // Ideally it should be done earlier, but currently it relies on RecoverySystem,
                // which would hang on earlier phases
                factoryResetIfDelayedEarlier();

                ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
                break;
        }
    }

    private void applyManagedSubscriptionsPolicyIfRequired() {
        int copeProfileUserId = getOrganizationOwnedProfileUserId();
        // This policy is relevant only for COPE devices.
        if (copeProfileUserId != UserHandle.USER_NULL) {
            unregisterOnSubscriptionsChangedListener();
            int policyType = getManagedSubscriptionsPolicy().getPolicyType();
            if (policyType == ManagedSubscriptionsPolicy.TYPE_ALL_PERSONAL_SUBSCRIPTIONS) {
                clearManagedSubscriptionsPolicy();
            } else if (policyType == ManagedSubscriptionsPolicy.TYPE_ALL_MANAGED_SUBSCRIPTIONS) {
                // Add listener to assign all current and future subs to managed profile.
                registerListenerToAssignSubscriptionsToUser(copeProfileUserId);
            }
        }
    }

    private void updatePersonalAppsSuspensionOnUserStart(int userHandle) {
        final int profileUserHandle = getManagedUserId(userHandle);
        if (profileUserHandle >= 0) {
            // Given that the parent user has just started, profile should be locked.
            updatePersonalAppsSuspension(profileUserHandle);
        } else {
            suspendPersonalAppsInternal(userHandle, profileUserHandle, false);
        }
    }

    private void onLockSettingsReady() {
        synchronized (getLockObject()) {
            fixupAutoTimeRestrictionDuringOrganizationOwnedDeviceMigration();
        }
        getUserData(UserHandle.USER_SYSTEM);
        cleanUpOldUsers();
        maybeSetDefaultProfileOwnerUserRestrictions();
        handleStartUser(UserHandle.USER_SYSTEM);
        maybeLogStart();

        // Register an observer for watching for user setup complete and settings changes.
        mSetupContentObserver.register();
        // Initialize the user setup state, to handle the upgrade case.
        updateUserSetupCompleteAndPaired();

        List<String> packageList;
        synchronized (getLockObject()) {
            packageList = getKeepUninstalledPackagesLocked();
        }
        if (packageList != null) {
            mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
        }

        synchronized (getLockObject()) {
            ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
            if (deviceOwner != null) {
                // Push the force-ephemeral-users policy to the user manager.
                mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);

                // Update user switcher message to activity manager.
                ActivityManagerInternal activityManagerInternal =
                        mInjector.getActivityManagerInternal();
                activityManagerInternal.setSwitchingFromSystemUserMessage(
                        deviceOwner.startUserSessionMessage);
                activityManagerInternal.setSwitchingToSystemUserMessage(
                        deviceOwner.endUserSessionMessage);
            }

            revertTransferOwnershipIfNecessaryLocked();
            if (!policyEngineMigrationV2Enabled()) {
                updateUsbDataSignal(mContext, isUsbDataSignalingEnabledInternalLocked());
            }
        }

        // Check whether work apps were paused via suspension and unsuspend if necessary.
        // TODO: move it into PolicyVersionUpgrader so that it is executed only once.
        unsuspendWorkAppsIfNecessary();
    }

    // TODO(b/230841522) Make it static.
    private class DpmsUpgradeDataProvider implements PolicyUpgraderDataProvider {
        @Override
        public JournaledFile makeDevicePoliciesJournaledFile(int userId) {
            return DevicePolicyManagerService.this.makeJournaledFile(userId, DEVICE_POLICIES_XML);
        }

        @Override
        public JournaledFile makePoliciesVersionJournaledFile(int userId) {
            return DevicePolicyManagerService.this.makeJournaledFile(userId, POLICIES_VERSION_XML);
        }

        @Override
        public Function<ComponentName, DeviceAdminInfo> getAdminInfoSupplier(int userId) {
            return component ->
                    findAdmin(component, userId, /* throwForMissingPermission= */ false);
        }

        @Override
        public int[] getUsersForUpgrade() {
            List<UserInfo> allUsers = mUserManager.getUsers();
            return allUsers.stream().mapToInt(u -> u.id).toArray();
        }

        @Override
        public List<String> getPlatformSuspendedPackages(int userId) {
            PackageManagerInternal pmi = mInjector.getPackageManagerInternal();
            return mInjector.getPackageManager(userId)
                    .getInstalledPackages(PackageManager.PackageInfoFlags.of(
                            MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE))
                    .stream()
                    .map(packageInfo -> packageInfo.packageName)
                    .filter(pkg ->
                            PLATFORM_PACKAGE_NAME.equals(pmi.getSuspendingPackage(pkg, userId))
                    )
                    .collect(Collectors.toList());
        }
    }

    private void performPolicyVersionUpgrade() {
        PolicyVersionUpgrader upgrader = new PolicyVersionUpgrader(
                new DpmsUpgradeDataProvider(), mPathProvider);
        upgrader.upgradePolicy(DPMS_VERSION);
    }

    private void revertTransferOwnershipIfNecessaryLocked() {
        if (!mTransferOwnershipMetadataManager.metadataFileExists()) {
            return;
        }
        Slogf.e(LOG_TAG, "Owner transfer metadata file exists! Reverting transfer.");
        final TransferOwnershipMetadataManager.Metadata metadata =
                mTransferOwnershipMetadataManager.loadMetadataFile();
        // Revert transfer
        if (metadata.adminType.equals(ADMIN_TYPE_PROFILE_OWNER)) {
            transferProfileOwnershipLocked(metadata.targetComponent, metadata.sourceComponent,
                    metadata.userId);
            deleteTransferOwnershipMetadataFileLocked();
            deleteTransferOwnershipBundleLocked(metadata.userId);
        } else if (metadata.adminType.equals(ADMIN_TYPE_DEVICE_OWNER)) {
            transferDeviceOwnershipLocked(metadata.targetComponent, metadata.sourceComponent,
                    metadata.userId);
            deleteTransferOwnershipMetadataFileLocked();
            deleteTransferOwnershipBundleLocked(metadata.userId);
        }
        updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ true);
    }

    private void maybeLogStart() {
        if (!SecurityLog.isLoggingEnabled()) {
            return;
        }
        final String verifiedBootState =
                mInjector.systemPropertiesGet("ro.boot.verifiedbootstate");
        final String verityMode = mInjector.systemPropertiesGet("ro.boot.veritymode");
        SecurityLog.writeEvent(SecurityLog.TAG_OS_STARTUP, verifiedBootState, verityMode);
    }

    private void ensureDeviceOwnerUserStarted() {
        final int userId;
        synchronized (getLockObject()) {
            if (!mOwners.hasDeviceOwner()) {
                return;
            }
            userId = mOwners.getDeviceOwnerUserId();
        }
        if (VERBOSE_LOG) {
            Slogf.v(LOG_TAG, "Starting non-system DO user: " + userId);
        }
        if (userId != UserHandle.USER_SYSTEM) {
            try {
                mInjector.getIActivityManager().startUserInBackground(userId);

                // STOPSHIP Prevent the DO user from being killed.

            } catch (RemoteException e) {
                Slogf.w(LOG_TAG, "Exception starting user", e);
            }
        }
    }

    void handleStartUser(int userId) {
        // When system user is started (device boot), load cache for all users.
        // This is to mitigate the potential race between loading the cache and keyguard
        // reading the value during user switch, due to onStartUser() being asynchronous.
        updatePasswordQualityCacheForUserGroup(
                userId == UserHandle.USER_SYSTEM ? UserHandle.USER_ALL : userId);
        updatePermissionPolicyCache(userId);
        updateAdminCanGrantSensorsPermissionCache(userId);

        final List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs;
        synchronized (getLockObject()) {
            ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId);
            preferentialNetworkServiceConfigs = owner != null
                    ? owner.mPreferentialNetworkServiceConfigs
                    : List.of(PreferentialNetworkServiceConfig.DEFAULT);
        }
        updateNetworkPreferenceForUser(userId, preferentialNetworkServiceConfigs);

        if (isProfileOwnerOfOrganizationOwnedDevice(userId)
                && getManagedSubscriptionsPolicy().getPolicyType()
                == ManagedSubscriptionsPolicy.TYPE_ALL_MANAGED_SUBSCRIPTIONS) {
            updateDialerAndSmsManagedShortcutsOverrideCache();
        }

        startOwnerService(userId, "start-user");
        mDevicePolicyEngine.handleStartUser(userId);
    }

    void pushUserControlDisabledPackagesLocked(int userId) {
        final int targetUserId;
        final ActiveAdmin owner;
        if (getDeviceOwnerUserIdUncheckedLocked() == userId) {
            owner = getDeviceOwnerAdminLocked();
            targetUserId = UserHandle.USER_ALL;
        } else {
            owner = getProfileOwnerAdminLocked(userId);
            targetUserId = userId;
        }

        List<String> protectedPackages = (owner == null || owner.protectedPackages == null)
                ? null : owner.protectedPackages;
        mInjector.binderWithCleanCallingIdentity(() ->
                mInjector.getPackageManagerInternal().setOwnerProtectedPackages(
                        targetUserId, protectedPackages));
        mUsageStatsManagerInternal.setAdminProtectedPackages(new ArraySet(protectedPackages),
                targetUserId);
    }

    void handleUnlockUser(int userId) {
        startOwnerService(userId, "unlock-user");
        mDevicePolicyEngine.handleUnlockUser(userId);
    }

    void handleOnUserUnlocked(int userId) {
        showNewUserDisclaimerIfNecessary(userId);
    }

    void handleStopUser(int userId) {
        updateNetworkPreferenceForUser(userId, List.of(PreferentialNetworkServiceConfig.DEFAULT));
        mDeviceAdminServiceController.stopServicesForUser(userId, /* actionForLog= */ "stop-user");
        mDevicePolicyEngine.handleStopUser(userId);
    }

    private void startOwnerService(int userId, String actionForLog) {
        final ComponentName owner = getOwnerComponent(userId);
        if (owner != null) {
            mDeviceAdminServiceController.startServiceForAdmin(
                    owner.getPackageName(), userId, actionForLog);
            invalidateBinderCaches();
        }
    }

    private void cleanUpOldUsers() {
        // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
        // before reboot
        Set<Integer> usersWithProfileOwners;
        Set<Integer> usersWithData;
        synchronized (getLockObject()) {
            usersWithProfileOwners = mOwners.getProfileOwnerKeys();
            usersWithData = new ArraySet<>();
            for (int i = 0; i < mUserData.size(); i++) {
                usersWithData.add(mUserData.keyAt(i));
            }
        }
        List<UserInfo> allUsers = mUserManager.getUsers();

        Set<Integer> deletedUsers = new ArraySet<>();
        deletedUsers.addAll(usersWithProfileOwners);
        deletedUsers.addAll(usersWithData);
        for (UserInfo userInfo : allUsers) {
            deletedUsers.remove(userInfo.id);
        }
        for (Integer userId : deletedUsers) {
            removeUserData(userId);
            mDevicePolicyEngine.handleUserRemoved(userId);
        }
    }

    private void handlePasswordExpirationNotification(int userHandle) {
        final Bundle adminExtras = new Bundle();
        adminExtras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));

        synchronized (getLockObject()) {
            final long now = System.currentTimeMillis();

            List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle);
            final int N = admins.size();
            for (int i = 0; i < N; i++) {
                ActiveAdmin admin = admins.get(i);
                if ((admin.isPermissionBased || admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD))
                        && admin.passwordExpirationTimeout > 0L
                        && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
                        && admin.passwordExpirationDate > 0L) {
                    sendAdminCommandLocked(admin,
                            DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING, adminExtras, null);
                }
            }
            setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
        }
    }

    /**
     * Clean up internal state when the set of installed trusted CA certificates changes.
     *
     * @param userHandle user to check for. This must be a real user and not, for example,
     *        {@link UserHandle#ALL}.
     * @param installedCertificates the full set of certificate authorities currently installed for
     *        {@param userHandle}. After calling this function, {@code mAcceptedCaCertificates} will
     *        correspond to some subset of this.
     */
    protected void onInstalledCertificatesChanged(final UserHandle userHandle,
            final @NonNull Collection<String> installedCertificates) {
        if (!mHasFeature) {
            return;
        }
        Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));

        synchronized (getLockObject()) {
            final DevicePolicyData policy = getUserData(userHandle.getIdentifier());

            boolean changed = false;
            changed |= policy.mAcceptedCaCertificates.retainAll(installedCertificates);
            changed |= policy.mOwnerInstalledCaCerts.retainAll(installedCertificates);
            if (changed) {
                saveSettingsLocked(userHandle.getIdentifier());
            }
        }
    }

    /**
     * Internal method used by {@link CertificateMonitor}.
     */
    protected Set<String> getAcceptedCaCertificates(final UserHandle userHandle) {
        if (!mHasFeature) {
            return Collections.<String> emptySet();
        }
        synchronized (getLockObject()) {
            final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
            return policy.mAcceptedCaCertificates;
        }
    }

    /**
     * @param adminReceiver The admin to add
     * @param refreshing true = update an active admin, no error
     */
    @Override
    public void setActiveAdmin(
            ComponentName adminReceiver, boolean refreshing, int userHandle) {
        if (!mHasFeature) {
            return;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS));
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));

        DevicePolicyData policy = getUserData(userHandle);
        DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
                /* throwForMissingPermission= */ true);
        synchronized (getLockObject()) {
            checkActiveAdminPrecondition(adminReceiver, info, policy);
            mInjector.binderWithCleanCallingIdentity(() -> {
                final ActiveAdmin existingAdmin
                        = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
                if (!refreshing && existingAdmin != null) {
                    throw new IllegalArgumentException("Admin is already added");
                }
                ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
                newAdmin.testOnlyAdmin =
                        (existingAdmin != null) ? existingAdmin.testOnlyAdmin
                                : isPackageTestOnly(adminReceiver.getPackageName(), userHandle);
                policy.mAdminMap.put(adminReceiver, newAdmin);
                int replaceIndex = -1;
                final int N = policy.mAdminList.size();
                for (int i=0; i < N; i++) {
                    ActiveAdmin oldAdmin = policy.mAdminList.get(i);
                    if (oldAdmin.info.getComponent().equals(adminReceiver)) {
                        replaceIndex = i;
                        break;
                    }
                }
                if (replaceIndex == -1) {
                    policy.mAdminList.add(newAdmin);
                    enableIfNecessary(info.getPackageName(), userHandle);
                    mUsageStatsManagerInternal.onActiveAdminAdded(
                            adminReceiver.getPackageName(), userHandle);
                } else {
                    policy.mAdminList.set(replaceIndex, newAdmin);
                }
                saveSettingsLocked(userHandle);
                sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
                        /* adminExtras= */ null, /* result= */ null);
            });
        }
    }

    private void loadAdminDataAsync() {
        mInjector.postOnSystemServerInitThreadPool(() -> {
            pushActiveAdminPackages();
            mUsageStatsManagerInternal.onAdminDataAvailable();
            pushAllMeteredRestrictedPackages();
            mInjector.getNetworkPolicyManagerInternal().onAdminDataAvailable();
        });
    }

    private void pushActiveAdminPackages() {
        synchronized (getLockObject()) {
            final List<UserInfo> users = mUserManager.getUsers();
            for (int i = users.size() - 1; i >= 0; --i) {
                final int userId = users.get(i).id;
                mUsageStatsManagerInternal.setActiveAdminApps(
                        getActiveAdminPackagesLocked(userId), userId);
            }
        }
    }

    private void pushAllMeteredRestrictedPackages() {
        synchronized (getLockObject()) {
            final List<UserInfo> users = mUserManager.getUsers();
            for (int i = users.size() - 1; i >= 0; --i) {
                final int userId = users.get(i).id;
                mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackagesAsync(
                        getMeteredDisabledPackages(userId), userId);
            }
        }
    }

    private void pushActiveAdminPackagesLocked(int userId) {
        mUsageStatsManagerInternal.setActiveAdminApps(
                getActiveAdminPackagesLocked(userId), userId);
    }

    private Set<String> getActiveAdminPackagesLocked(int userId) {
        final DevicePolicyData policy = getUserData(userId);
        Set<String> adminPkgs = null;
        for (int i = policy.mAdminList.size() - 1; i >= 0; --i) {
            final String pkgName = policy.mAdminList.get(i).info.getPackageName();
            if (adminPkgs == null) {
                adminPkgs = new ArraySet<>();
            }
            adminPkgs.add(pkgName);
        }
        return adminPkgs;
    }

    private void transferActiveAdminUncheckedLocked(ComponentName incomingReceiver,
            ComponentName outgoingReceiver, int userHandle) {
        final DevicePolicyData policy = getUserData(userHandle);
        if (!policy.mAdminMap.containsKey(outgoingReceiver)
                && policy.mAdminMap.containsKey(incomingReceiver)) {
            // Nothing to transfer - the incoming receiver is already the active admin.
            return;
        }
        final DeviceAdminInfo incomingDeviceInfo = findAdmin(incomingReceiver, userHandle,
            /* throwForMissingPermission= */ true);
        final ActiveAdmin adminToTransfer = policy.mAdminMap.get(outgoingReceiver);
        final int oldAdminUid = adminToTransfer.getUid();

        EnforcingAdmin oldAdmin =
                EnforcingAdmin.createEnterpriseEnforcingAdmin(
                        outgoingReceiver, userHandle, adminToTransfer);
        EnforcingAdmin newAdmin =
                EnforcingAdmin.createEnterpriseEnforcingAdmin(
                        incomingReceiver, userHandle, adminToTransfer);

        mDevicePolicyEngine.transferPolicies(oldAdmin, newAdmin);

        adminToTransfer.transfer(incomingDeviceInfo);
        policy.mAdminMap.remove(outgoingReceiver);
        policy.mAdminMap.put(incomingReceiver, adminToTransfer);
        if (policy.mPasswordOwner == oldAdminUid) {
            policy.mPasswordOwner = adminToTransfer.getUid();
        }

        saveSettingsLocked(userHandle);
        sendAdminCommandLocked(adminToTransfer, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
                null, null);
    }

    private void checkActiveAdminPrecondition(ComponentName adminReceiver, DeviceAdminInfo info,
            DevicePolicyData policy) {
        if (info == null) {
            throw new IllegalArgumentException("Bad admin: " + adminReceiver);
        }
        if (!info.getActivityInfo().applicationInfo.isInternal()) {
            throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
                    + adminReceiver);
        }
        if (info.getActivityInfo().applicationInfo.isInstantApp()) {
            throw new IllegalArgumentException("Instant apps cannot be device admins: "
                    + adminReceiver);
        }
        if (policy.mRemovingAdmins.contains(adminReceiver)) {
            throw new IllegalArgumentException(
                    "Trying to set an admin which is being removed");
        }
    }

    private void checkAllUsersAreAffiliatedWithDevice() {
        Preconditions.checkCallAuthorization(areAllUsersAffiliatedWithDeviceLocked(),
                "operation not allowed when device has unaffiliated users");
    }

    @Override
    public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
        if (!mHasFeature) {
            return false;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));

        synchronized (getLockObject()) {
            return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
        }
    }

    @Override
    public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
        if (!mHasFeature) {
            return false;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));

        synchronized (getLockObject()) {
            DevicePolicyData policyData = getUserData(userHandle);
            return policyData.mRemovingAdmins.contains(adminReceiver);
        }
    }

    @Override
    public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
        if (!mHasFeature) {
            return false;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
        Preconditions.checkCallAuthorization(
                isCallingFromPackage(adminReceiver.getPackageName(), caller.getUid())
                        || isSystemUid(caller));

        synchronized (getLockObject()) {
            ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
            if (administrator == null) {
                throw new SecurityException("No active admin " + adminReceiver);
            }
            return administrator.info.usesPolicy(policyId);
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<ComponentName> getActiveAdmins(int userHandle) {
        if (!mHasFeature) {
            return Collections.EMPTY_LIST;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));

        synchronized (getLockObject()) {
            DevicePolicyData policy = getUserData(userHandle);
            final int N = policy.mAdminList.size();
            if (N <= 0) {
                return null;
            }
            ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
            for (int i=0; i<N; i++) {
                res.add(policy.mAdminList.get(i).info.getComponent());
            }
            return res;
        }
    }

    @Override
    public boolean packageHasActiveAdmins(String packageName, int userHandle) {
        if (!mHasFeature) {
            return false;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));

        synchronized (getLockObject()) {
            DevicePolicyData policy = getUserData(userHandle);
            final int N = policy.mAdminList.size();
            for (int i=0; i<N; i++) {
                if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
                    return true;
                }
            }
            return false;
        }
    }

    @Override
    public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
        if (!mHasFeature) {
            return;
        }
        Objects.requireNonNull(adminReceiver, "ComponentName is null");
        Preconditions.checkCallAuthorization(isAdb(getCallerIdentity())
                        || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS),
                "Caller must be shell or hold MANAGE_PROFILE_AND_DEVICE_OWNERS to call "
                        + "forceRemoveActiveAdmin");
        mInjector.binderWithCleanCallingIdentity(() -> {
            boolean isOrgOwnedProfile = false;
            synchronized (getLockObject()) {
                if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) {
                    throw new SecurityException("Attempt to remove non-test admin "
                            + adminReceiver + " " + userHandle);
                }

                // If admin is a device or profile owner tidy that up first.
                if (isDeviceOwner(adminReceiver, userHandle)) {
                    clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
                }
                if (isProfileOwner(adminReceiver, userHandle)) {
                    isOrgOwnedProfile = isProfileOwnerOfOrganizationOwnedDevice(userHandle);
                    final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
                            userHandle, /* parent */ false);
                    clearProfileOwnerLocked(admin, userHandle);
                }
            }
            // Remove the admin skipping sending the broadcast.
            removeAdminArtifacts(adminReceiver, userHandle);

            // In case of PO on org owned device, clean device-wide policies and restrictions.
            if (isOrgOwnedProfile) {
                final UserHandle parentUser = UserHandle.of(getProfileParentId(userHandle));
                clearOrgOwnedProfileOwnerUserRestrictions(parentUser);
                clearOrgOwnedProfileOwnerDeviceWidePolicies(parentUser.getIdentifier());
            }

            Slogf.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle);
        });
    }

    private void clearOrgOwnedProfileOwnerUserRestrictions(UserHandle parentUserHandle) {
        mUserManager.setUserRestriction(
                UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, false, parentUserHandle);
        mUserManager.setUserRestriction(
                UserManager.DISALLOW_ADD_USER, false, parentUserHandle);
    }

    private void clearDeviceOwnerUserRestriction(UserHandle userHandle) {
        for (int userId : mUserManagerInternal.getUserIds()) {
            UserHandle user = UserHandle.of(userId);
            // ManagedProvisioning/DPC sets DISALLOW_ADD_USER. Clear to recover to the
            // original state
            if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, user)) {
                mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER,
                        false, user);
            }
            // When a device owner is set, the system automatically restricts adding a
            // managed profile.
            // Remove this restriction when the device owner is cleared.
            if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE,
                    user)) {
                mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE,
                        false,
                        user);
            }
            // When a device owner is set, the system automatically restricts adding a
            // clone profile.
            // Remove this restriction when the device owner is cleared.
            if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_CLONE_PROFILE, user)) {
                mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_CLONE_PROFILE,
                        false, user);
            }

            // When a device owner is set, the system automatically restricts adding a
            // private profile.
            // Remove this restriction when the device owner is cleared.
            if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_PRIVATE_PROFILE,
                    user)) {
                mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_PRIVATE_PROFILE,
                        false, user);
            }
        }

    }

    /**
     * Return if a given package has testOnly="true", in which case we'll relax certain rules
     * for CTS.
     *
     * DO NOT use this method except in {@link #setActiveAdmin}.  Use {@link #isAdminTestOnlyLocked}
     * to check wehter an active admin is test-only or not.
     *
     * The system allows this flag to be changed when an app is updated, which is not good
     * for us.  So we persist the flag in {@link ActiveAdmin} when an admin is first installed,
     * and used the persisted version in actual checks. (See b/31382361 and b/28928996)
     */
    private boolean isPackageTestOnly(String packageName, int userHandle) {
        final ApplicationInfo ai;
        try {
            ai = mInjector.getIPackageManager().getApplicationInfo(packageName,
                    (PackageManager.MATCH_DIRECT_BOOT_AWARE
                            | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle);
        } catch (RemoteException e) {
            throw new IllegalStateException(e);
        }
        if (ai == null) {
            throw new IllegalStateException("Couldn't find package: "
                    + packageName + " on user " + userHandle);
        }
        return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0;
    }

    /**
     * See {@link #isPackageTestOnly}.
     */
    private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) {
        final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
        return (admin != null) && admin.testOnlyAdmin;
    }

    @Override
    public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
        if (!mHasFeature) {
            return;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS)
                ? getCallerIdentity() : getCallerIdentity(adminReceiver);
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REMOVE_ACTIVE_ADMIN);
        enforceUserUnlocked(userHandle);

        ActiveAdmin admin;
        synchronized (getLockObject()) {
            admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
            if (admin == null) {
                return;
            }
            // Active device/profile owners must remain active admins.
            if (isDeviceOwner(adminReceiver, userHandle)
                    || isProfileOwner(adminReceiver, userHandle)) {
                Slogf.e(LOG_TAG, "Device/profile owner cannot be removed: component="
                        + adminReceiver);
                return;
            }
            mInjector.binderWithCleanCallingIdentity(() ->
                    removeActiveAdminLocked(adminReceiver, userHandle));
        }
        mDevicePolicyEngine.removePoliciesForAdmin(
                EnforcingAdmin.createEnterpriseEnforcingAdmin(
                        adminReceiver, userHandle, admin));
    }

    private boolean canSetPasswordQualityOnParent(String packageName, final CallerIdentity caller) {
        return !mInjector.isChangeEnabled(
                PREVENT_SETTING_PASSWORD_QUALITY_ON_PARENT, packageName, caller.getUserId())
            || isProfileOwnerOfOrganizationOwnedDevice(caller);
    }

    private boolean isPasswordLimitingAdminTargetingP(CallerIdentity caller) {
        if (!caller.hasAdminComponent()) {
            return false;
        }

        synchronized (getLockObject()) {
            return getActiveAdminWithPolicyForUidLocked(
                    caller.getComponentName(), DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD,
                    caller.getUid()) != null;
        }
    }

    private boolean notSupportedOnAutomotive(String method) {
        if (mIsAutomotive) {
            Slogf.i(LOG_TAG, "%s is not supported on automotive builds", method);
            return true;
        }
        return false;
    }

    @Override
    public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
        if (!mHasFeature || notSupportedOnAutomotive("setPasswordQuality")) {
            return;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        validateQualityConstant(quality);

        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isProfileOwner(caller) || isDefaultDeviceOwner(caller)
                        || isSystemUid(caller) || isPasswordLimitingAdminTargetingP(caller));

        if (parent) {
            Preconditions.checkCallAuthorization(
                    canSetPasswordQualityOnParent(who.getPackageName(), caller),
                    "Profile Owner may not apply password quality requirements device-wide");
        }

        final int userId = caller.getUserId();
        synchronized (getLockObject()) {
            ActiveAdmin ap = getActiveAdminForCallerLocked(
                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);

            // If setPasswordQuality is called on the parent, ensure that
            // the primary admin does not have password complexity state (this is an
            // unsupported state).
            if (parent) {
                final ActiveAdmin primaryAdmin = getActiveAdminForCallerLocked(
                        who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, false);
                final boolean hasComplexitySet =
                        primaryAdmin.mPasswordComplexity != PASSWORD_COMPLEXITY_NONE;
                Preconditions.checkState(!hasComplexitySet,
                        "Cannot set password quality when complexity is set on the primary admin."
                        + " Set the primary admin's complexity to NONE first.");
            }
            mInjector.binderWithCleanCallingIdentity(() -> {
                final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
                if (passwordPolicy.quality != quality) {
                    passwordPolicy.quality = quality;
                    ap.mPasswordComplexity = PASSWORD_COMPLEXITY_NONE;
                    resetInactivePasswordRequirementsIfRPlus(userId, ap);
                    updatePasswordValidityCheckpointLocked(userId, parent);
                    updatePasswordQualityCacheForUserGroup(userId);
                    saveSettingsLocked(userId);
                }
                logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
            });
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_PASSWORD_QUALITY)
                .setAdmin(who)
                .setInt(quality)
                .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT)
                .write();
    }

    private boolean passwordQualityInvocationOrderCheckEnabled(String packageName, int userId) {
        return mInjector.isChangeEnabled(ADMIN_APP_PASSWORD_COMPLEXITY, packageName, userId);
    }

    /**
     * For admins targeting R+ reset various password constraints to default values when quality is
     * set to a value that makes those constraints that have no effect.
     */
    private void resetInactivePasswordRequirementsIfRPlus(int userId, ActiveAdmin admin) {
        if (passwordQualityInvocationOrderCheckEnabled(admin.info.getPackageName(), userId)) {
            final PasswordPolicy policy = admin.mPasswordPolicy;
            if (policy.quality < PASSWORD_QUALITY_NUMERIC) {
                policy.length = PasswordPolicy.DEF_MINIMUM_LENGTH;
            }
            if (policy.quality < PASSWORD_QUALITY_COMPLEX) {
                policy.letters = PasswordPolicy.DEF_MINIMUM_LETTERS;
                policy.upperCase = PasswordPolicy.DEF_MINIMUM_UPPER_CASE;
                policy.lowerCase = PasswordPolicy.DEF_MINIMUM_LOWER_CASE;
                policy.numeric = PasswordPolicy.DEF_MINIMUM_NUMERIC;
                policy.symbols = PasswordPolicy.DEF_MINIMUM_SYMBOLS;
                policy.nonLetter = PasswordPolicy.DEF_MINIMUM_NON_LETTER;
            }
        }
    }

    /**
     * Updates a flag that tells us whether the user's password currently satisfies the
     * requirements set by all of the user's active admins.
     * This should be called whenever the password or the admin policies have changed. The caller
     * is responsible for calling {@link #saveSettingsLocked} to persist the change.
     *
     * @return the set of user IDs that have been affected
     */
    @GuardedBy("getLockObject()")
    private Set<Integer> updatePasswordValidityCheckpointLocked(int userHandle, boolean parent) {
        final ArraySet<Integer> affectedUserIds = new ArraySet<>();
        final int credentialOwner = getCredentialOwner(userHandle, parent);
        DevicePolicyData policy = getUserData(credentialOwner);
        PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(credentialOwner);
        // Update the checkpoint only if the user's password metrics is known
        if (metrics != null) {
            final int userToCheck = getProfileParentUserIfRequested(userHandle, parent);
            final boolean newCheckpoint = isPasswordSufficientForUserWithoutCheckpointLocked(
                    metrics, userToCheck);
            if (newCheckpoint != policy.mPasswordValidAtLastCheckpoint) {
                policy.mPasswordValidAtLastCheckpoint = newCheckpoint;
                affectedUserIds.add(credentialOwner);
            }
        }
        return affectedUserIds;
    }

    /**
     * Update password quality values in policy cache for all users in the same user group as
     * the given user. The cached password quality for user X is the aggregated quality among all
     * admins who have influence of user X's screenlock, i.e. it's equivalent to the return value of
     * getPasswordQuality(null, user X, false).
     *
     * Caches for all users in the same user group often need to be updated alltogether because a
     * user's admin policy can affect another's aggregated password quality in some situation.
     * For example a managed profile's policy will affect the parent user if the profile has unified
     * challenge. A profile can also explicitly set a parent password quality which will affect the
     * aggregated password quality of the parent user.
     */
    private void updatePasswordQualityCacheForUserGroup(@UserIdInt int userId) {
        final List<UserInfo> users;
        if (userId == UserHandle.USER_ALL) {
            users = mUserManager.getUsers();
        } else {
            users = mUserManager.getProfiles(userId);
        }
        for (UserInfo userInfo : users) {
            final int currentUserId = userInfo.id;
            mPolicyCache.setPasswordQuality(currentUserId,
                    getPasswordQuality(null, currentUserId, false));
        }
    }

    @Override
    public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
        if (!mHasFeature) {
            return PASSWORD_QUALITY_UNSPECIFIED;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
        // System caller can query policy for a particular admin.
        Preconditions.checkCallAuthorization(
                who == null || isCallingFromPackage(who.getPackageName(), caller.getUid())
                        || canQueryAdminPolicy(caller));

        synchronized (getLockObject()) {
            int mode = PASSWORD_QUALITY_UNSPECIFIED;

            if (who != null) {
                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
                return admin != null ? admin.mPasswordPolicy.quality : mode;
            }

            // Return the strictest policy across all participating admins.
            List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
                    getProfileParentUserIfRequested(userHandle, parent));
            final int N = admins.size();
            for (int i = 0; i < N; i++) {
                ActiveAdmin admin = admins.get(i);
                if (mode < admin.mPasswordPolicy.quality) {
                    mode = admin.mPasswordPolicy.quality;
                }
            }
            return mode;
        }
    }

    @GuardedBy("getLockObject()")
    private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(int userHandle) {
        if (isSeparateProfileChallengeEnabled(userHandle)) {

            if (isPermissionCheckFlagEnabled()) {
                return getActiveAdminsForAffectedUserInclPermissionBasedAdminLocked(userHandle);
            }
            // If this user has a separate challenge, only return its restrictions.
            return getUserDataUnchecked(userHandle).mAdminList;
        }
        // If isSeparateProfileChallengeEnabled is false and userHandle points to a managed profile
        // we need to query the parent user who owns the credential.
        if (isPermissionCheckFlagEnabled()) {
            return getActiveAdminsForUserAndItsManagedProfilesInclPermissionBasedAdminLocked(getProfileParentId(userHandle),
                    (user) -> !mLockPatternUtils.isSeparateProfileChallengeEnabled(user.id));
        } else {
            return getActiveAdminsForUserAndItsManagedProfilesLocked(getProfileParentId(userHandle),
                    (user) -> !mLockPatternUtils.isSeparateProfileChallengeEnabled(user.id));
        }

    }

    /**
     * Get the list of active admins for an affected user:
     * <ul>
     * <li>The active admins associated with the userHandle itself</li>
     * <li>The parent active admins for each managed profile associated with the userHandle</li>
     * </ul>
     *
     * @param userHandle the affected user for whom to get the active admins
     * @return the list of active admins for the affected user
     */
    @GuardedBy("getLockObject()")
    private List<ActiveAdmin> getActiveAdminsForAffectedUserLocked(int userHandle) {
        if (isManagedProfile(userHandle)) {
            return getUserDataUnchecked(userHandle).mAdminList;
        }
        return getActiveAdminsForUserAndItsManagedProfilesLocked(userHandle,
                /* shouldIncludeProfileAdmins */ (user) -> false);
    }

    /**
     * Get the list of active admins for an affected user:
     * <ul>
     * <li>The active admins associated with the userHandle itself</li>
     * <li>The parent active admins for each managed profile associated with the userHandle</li>
     * <li>The permission based admin associated with the userHandle itself</li>
     * </ul>
     *
     * @param userHandle the affected user for whom to get the active admins
     * @return the list of active admins for the affected user
     */
    @GuardedBy("getLockObject()")
    private List<ActiveAdmin> getActiveAdminsForAffectedUserInclPermissionBasedAdminLocked(
            int userHandle) {
        List<ActiveAdmin> list;

        if (isManagedProfile(userHandle)) {
            list = getUserDataUnchecked(userHandle).mAdminList;
        }
        list = getActiveAdminsForUserAndItsManagedProfilesInclPermissionBasedAdminLocked(userHandle,
                /* shouldIncludeProfileAdmins */ (user) -> false);

        if (getUserData(userHandle).mPermissionBasedAdmin != null) {
            list.add(getUserData(userHandle).mPermissionBasedAdmin);
        }
        return list;
    }

    /**
     * Returns the list of admins on the given user, as well as parent admins for each managed
     * profile associated with the given user. Optionally also include the admin of each managed
     * profile.
     * <p> Should not be called on a profile user.
     */
    @GuardedBy("getLockObject()")
    private List<ActiveAdmin> getActiveAdminsForUserAndItsManagedProfilesLocked(int userHandle,
            Predicate<UserInfo> shouldIncludeProfileAdmins) {
        ArrayList<ActiveAdmin> admins = new ArrayList<>();
        mInjector.binderWithCleanCallingIdentity(() -> {
            for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
                DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
                if (userInfo.id == userHandle) {
                    admins.addAll(policy.mAdminList);
                } else if (userInfo.isManagedProfile()) {
                    for (int i = 0; i < policy.mAdminList.size(); i++) {
                        ActiveAdmin admin = policy.mAdminList.get(i);
                        if (admin.hasParentActiveAdmin()) {
                            admins.add(admin.getParentActiveAdmin());
                        }
                        if (shouldIncludeProfileAdmins.test(userInfo)) {
                            admins.add(admin);
                        }
                    }
                }
            }
        });
        return admins;
    }

    /**
     * Returns the list of admins on the given user, as well as parent admins for each managed
     * profile associated with the given user. Optionally also include the admin of each managed
     * profile.
     * <p> Should not be called on a profile user.
     */
    @GuardedBy("getLockObject()")
    private List<ActiveAdmin> getActiveAdminsForUserAndItsManagedProfilesInclPermissionBasedAdminLocked(int userHandle,
            Predicate<UserInfo> shouldIncludeProfileAdmins) {
        ArrayList<ActiveAdmin> admins = new ArrayList<>();
        mInjector.binderWithCleanCallingIdentity(() -> {
            for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
                DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
                if (userInfo.id == userHandle) {
                    admins.addAll(policy.mAdminList);
                    if (policy.mPermissionBasedAdmin != null) {
                        admins.add(policy.mPermissionBasedAdmin);
                    }
                } else if (userInfo.isManagedProfile()) {
                    for (int i = 0; i < policy.mAdminList.size(); i++) {
                        ActiveAdmin admin = policy.mAdminList.get(i);
                        if (admin.hasParentActiveAdmin()) {
                            admins.add(admin.getParentActiveAdmin());
                        }
                        if (shouldIncludeProfileAdmins.test(userInfo)) {
                            admins.add(admin);
                        }
                    }
                    if (policy.mPermissionBasedAdmin != null
                            && shouldIncludeProfileAdmins.test(userInfo)) {
                        admins.add(policy.mPermissionBasedAdmin);
                    }
                }
            }
        });
        return admins;
    }

    private boolean isSeparateProfileChallengeEnabled(int userHandle) {
        return mInjector.binderWithCleanCallingIdentity(() ->
                mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle));
    }

    @Override
    public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
        if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumLength")) {
            return;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final int userId = mInjector.userHandleGetCallingUserId();
        synchronized (getLockObject()) {
            ActiveAdmin ap = getActiveAdminForCallerLocked(
                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
            ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_NUMERIC, "setPasswordMinimumLength");
            final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
            if (passwordPolicy.length != length) {
                passwordPolicy.length = length;
                updatePasswordValidityCheckpointLocked(userId, parent);
                saveSettingsLocked(userId);
            }
            logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LENGTH)
                .setAdmin(who)
                .setInt(length)
                .write();
    }

    private void ensureMinimumQuality(
            int userId, ActiveAdmin admin, int minimumQuality, String operation) {
        mInjector.binderWithCleanCallingIdentity(() -> {
            // This check will also take care of the case where the password requirements
            // are specified as complexity rather than quality: When a password complexity
            // is set, the quality is reset to "unspecified" which will be below any value
            // of minimumQuality.
            if (admin.mPasswordPolicy.quality < minimumQuality
                    && passwordQualityInvocationOrderCheckEnabled(admin.info.getPackageName(),
                    userId)) {
                throw new IllegalStateException(String.format(
                        "password quality should be at least %d for %s",
                        minimumQuality, operation));
            }
        });
    }

    @Override
    public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
        return getStrictestPasswordRequirement(who, userHandle, parent,
                admin -> admin.mPasswordPolicy.length, PASSWORD_QUALITY_NUMERIC);
    }

    @Override
    public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
        if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
            return;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final int userId = mInjector.userHandleGetCallingUserId();
        synchronized (getLockObject()) {
            ActiveAdmin ap = getActiveAdminForCallerLocked(
                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
            if (ap.passwordHistoryLength != length) {
                ap.passwordHistoryLength = length;
                updatePasswordValidityCheckpointLocked(userId, parent);
                saveSettingsLocked(userId);
            }
        }
        if (SecurityLog.isLoggingEnabled()) {
            final int affectedUserId = parent ? getProfileParentId(userId) : userId;
            SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_HISTORY_LENGTH_SET,
                    who.getPackageName(), userId, affectedUserId, length);
        }
    }

    @Override
    public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
        if (!mLockPatternUtils.hasSecureLockScreen()) {
            return 0;
        }
        return getStrictestPasswordRequirement(who, userHandle, parent,
                admin -> admin.passwordHistoryLength, PASSWORD_QUALITY_UNSPECIFIED);
    }

    @Override
    public void setPasswordExpirationTimeout(ComponentName who, String callerPackageName,
            long timeout, boolean parent) {
        if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
            return;
        }
        if (!isPermissionCheckFlagEnabled()) {
            Objects.requireNonNull(who, "ComponentName is null");
        }

        Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
        int userHandle = mInjector.userHandleGetCallingUserId();
        int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
        synchronized (getLockObject()) {
            ActiveAdmin ap;
            if (isPermissionCheckFlagEnabled()) {
                CallerIdentity caller = getCallerIdentity(who, callerPackageName);
                ap = enforcePermissionAndGetEnforcingAdmin(
                        who, MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
                        caller.getPackageName(), affectedUserId)
                        .getActiveAdmin();
            } else {
                ap = getActiveAdminForCallerLocked(
                        who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
            }
            // Calling this API automatically bumps the expiration date
            final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
            ap.passwordExpirationDate = expiration;
            ap.passwordExpirationTimeout = timeout;
            if (timeout > 0L) {
                Slogf.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
                        + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
                        .format(new Date(expiration)));
            }
            saveSettingsLocked(userHandle);

            // in case this is the first one, set the alarm on the appropriate user.
            setExpirationAlarmCheckLocked(mContext, userHandle, parent);
        }
        if (SecurityLog.isLoggingEnabled()) {
            SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_EXPIRATION_SET, callerPackageName,
                    userHandle, affectedUserId, timeout);
        }
    }

    /**
     * Return a single admin's expiration cycle time, or the min of all cycle times.
     * Returns 0 if not configured.
     */
    @Override
    public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
        if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
            return 0L;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));

        synchronized (getLockObject()) {
            long timeout = 0L;

            if (who != null) {
                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
                return admin != null ? admin.passwordExpirationTimeout : timeout;
            }

            // Return the strictest policy across all participating admins.
            List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
                    getProfileParentUserIfRequested(userHandle, parent));
            final int N = admins.size();
            for (int i = 0; i < N; i++) {
                ActiveAdmin admin = admins.get(i);
                if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
                        && timeout > admin.passwordExpirationTimeout)) {
                    timeout = admin.passwordExpirationTimeout;
                }
            }
            return timeout;
        }
    }

    @Override
    public boolean addCrossProfileWidgetProvider(ComponentName admin, String callerPackageName,
            String packageName) {
        CallerIdentity caller;

        if (isPermissionCheckFlagEnabled()) {
            caller = getCallerIdentity(admin, callerPackageName);
        } else {
            caller = getCallerIdentity(admin);
        }
        ActiveAdmin activeAdmin;

        if (isPermissionCheckFlagEnabled()) {
            EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                    admin,
                    MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
                    caller.getPackageName(),
                    caller.getUserId());
            activeAdmin = enforcingAdmin.getActiveAdmin();
        } else {
            Objects.requireNonNull(admin, "ComponentName is null");
            Preconditions.checkCallAuthorization(isProfileOwner(caller));
            synchronized (getLockObject()) {
                activeAdmin = getProfileOwnerLocked(caller.getUserId());
            }
        }
        List<String> changedProviders = null;

        synchronized (getLockObject()) {
            if (activeAdmin.crossProfileWidgetProviders == null) {
                activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
            }
            List<String> providers = activeAdmin.crossProfileWidgetProviders;
            if (!providers.contains(packageName)) {
                providers.add(packageName);
                changedProviders = new ArrayList<>(providers);
                saveSettingsLocked(caller.getUserId());
            }
        }

        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.ADD_CROSS_PROFILE_WIDGET_PROVIDER)
                .setAdmin(caller.getPackageName())
                .write();

        if (changedProviders != null) {
            mLocalService.notifyCrossProfileProvidersChanged(caller.getUserId(),
                    changedProviders);
            return true;
        }

        return false;
    }

    @Override
    public boolean removeCrossProfileWidgetProvider(ComponentName admin, String callerPackageName,
            String packageName) {
        CallerIdentity caller;
        if (isPermissionCheckFlagEnabled()) {
            caller = getCallerIdentity(admin, callerPackageName);
        } else {
            caller = getCallerIdentity(admin);
        }

        ActiveAdmin activeAdmin;

        if (isPermissionCheckFlagEnabled()) {
            EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                    admin,
                    MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
                    caller.getPackageName(),
                    caller.getUserId());
            activeAdmin = enforcingAdmin.getActiveAdmin();
        } else {
            Objects.requireNonNull(admin, "ComponentName is null");
            Preconditions.checkCallAuthorization(isProfileOwner(caller));
            synchronized (getLockObject()) {
                activeAdmin = getProfileOwnerLocked(caller.getUserId());
            }
        }
        List<String> changedProviders = null;

        synchronized (getLockObject()) {
            if (activeAdmin.crossProfileWidgetProviders == null
                    || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
                return false;
            }
            List<String> providers = activeAdmin.crossProfileWidgetProviders;
            if (providers.remove(packageName)) {
                changedProviders = new ArrayList<>(providers);
                saveSettingsLocked(caller.getUserId());
            }
        }

        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.REMOVE_CROSS_PROFILE_WIDGET_PROVIDER)
                .setAdmin(caller.getPackageName())
                .write();

        if (changedProviders != null) {
            mLocalService.notifyCrossProfileProvidersChanged(caller.getUserId(),
                    changedProviders);
            return true;
        }

        return false;
    }

    @Override
    public List<String> getCrossProfileWidgetProviders(ComponentName admin,
            String callerPackageName) {
        CallerIdentity caller;
        if (isPermissionCheckFlagEnabled()) {
            caller = getCallerIdentity(admin, callerPackageName);
        } else {
            caller = getCallerIdentity(admin);
        }
        ActiveAdmin activeAdmin;

        if (isPermissionCheckFlagEnabled()) {
            EnforcingAdmin enforcingAdmin = enforceCanQueryAndGetEnforcingAdmin(
                    admin,
                    MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
                    caller.getPackageName(),
                    caller.getUserId());
            activeAdmin = enforcingAdmin.getActiveAdmin();
        } else {
            Objects.requireNonNull(admin, "ComponentName is null");
            Preconditions.checkCallAuthorization(isProfileOwner(caller));
            synchronized (getLockObject()) {
                activeAdmin = getProfileOwnerLocked(caller.getUserId());
            }
        }

        synchronized (getLockObject()) {
            if (activeAdmin.crossProfileWidgetProviders == null
                    || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
                return null;
            }
            if (mInjector.binderIsCallingUidMyUid()) {
                return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
            } else {
                return activeAdmin.crossProfileWidgetProviders;
            }
        }
    }

    /**
     * Return a single admin's expiration date/time, or the min (soonest) for all admins.
     * Returns 0 if not configured.
     */
    @GuardedBy("getLockObject()")
    private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
        long timeout = 0L;

        if (who != null) {
            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
            return admin != null ? admin.passwordExpirationDate : timeout;
        }

        // Return the strictest policy across all participating admins.
        List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
                getProfileParentUserIfRequested(userHandle, parent));
        final int N = admins.size();
        for (int i = 0; i < N; i++) {
            ActiveAdmin admin = admins.get(i);
            if (timeout == 0L || (admin.passwordExpirationDate != 0
                    && timeout > admin.passwordExpirationDate)) {
                timeout = admin.passwordExpirationDate;
            }
        }
        return timeout;
    }

    @Override
    public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
        if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
            return 0L;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));

        synchronized (getLockObject()) {
            return getPasswordExpirationLocked(who, userHandle, parent);
        }
    }

    @Override
    public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
        if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumUpperCase")) {
            return;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final int userId = mInjector.userHandleGetCallingUserId();
        synchronized (getLockObject()) {
            final ActiveAdmin ap = getActiveAdminForCallerLocked(
                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
            ensureMinimumQuality(
                    userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumUpperCase");
            final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
            if (passwordPolicy.upperCase != length) {
                passwordPolicy.upperCase = length;
                updatePasswordValidityCheckpointLocked(userId, parent);
                saveSettingsLocked(userId);
            }
            logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_UPPER_CASE)
                .setAdmin(who)
                .setInt(length)
                .write();
    }

    @Override
    public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
        return getStrictestPasswordRequirement(who, userHandle, parent,
                admin -> admin.mPasswordPolicy.upperCase, PASSWORD_QUALITY_COMPLEX);
    }

    @Override
    public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
        if (notSupportedOnAutomotive("setPasswordMinimumLowerCase")) {
            return;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final int userId = mInjector.userHandleGetCallingUserId();
        synchronized (getLockObject()) {
            ActiveAdmin ap = getActiveAdminForCallerLocked(
                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
            ensureMinimumQuality(
                    userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumLowerCase");
            final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
            if (passwordPolicy.lowerCase != length) {
                passwordPolicy.lowerCase = length;
                updatePasswordValidityCheckpointLocked(userId, parent);
                saveSettingsLocked(userId);
            }
            logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LOWER_CASE)
                .setAdmin(who)
                .setInt(length)
                .write();
    }

    @Override
    public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
        return getStrictestPasswordRequirement(who, userHandle, parent,
                admin -> admin.mPasswordPolicy.lowerCase, PASSWORD_QUALITY_COMPLEX);
    }

    @Override
    public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
        if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumLetters")) {
            return;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final int userId = mInjector.userHandleGetCallingUserId();
        synchronized (getLockObject()) {
            ActiveAdmin ap = getActiveAdminForCallerLocked(
                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
            ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumLetters");
            final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
            if (passwordPolicy.letters != length) {
                passwordPolicy.letters = length;
                updatePasswordValidityCheckpointLocked(userId, parent);
                saveSettingsLocked(userId);
            }
            logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LETTERS)
                .setAdmin(who)
                .setInt(length)
                .write();
    }

    @Override
    public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
        return getStrictestPasswordRequirement(who, userHandle, parent,
                admin -> admin.mPasswordPolicy.letters, PASSWORD_QUALITY_COMPLEX);
    }

    @Override
    public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
        if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumNumeric")) {
            return;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final int userId = mInjector.userHandleGetCallingUserId();
        synchronized (getLockObject()) {
            ActiveAdmin ap = getActiveAdminForCallerLocked(
                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
            ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumNumeric");
            final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
            if (passwordPolicy.numeric != length) {
                passwordPolicy.numeric = length;
                updatePasswordValidityCheckpointLocked(userId, parent);
                saveSettingsLocked(userId);
            }
            logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_NUMERIC)
                .setAdmin(who)
                .setInt(length)
                .write();
    }

    @Override
    public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
        return getStrictestPasswordRequirement(who, userHandle, parent,
                admin -> admin.mPasswordPolicy.numeric, PASSWORD_QUALITY_COMPLEX);
    }

    @Override
    public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
        if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumSymbols")) {
            return;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final int userId = mInjector.userHandleGetCallingUserId();
        synchronized (getLockObject()) {
            ActiveAdmin ap = getActiveAdminForCallerLocked(
                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
            ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumSymbols");
            final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
            if (passwordPolicy.symbols != length) {
                ap.mPasswordPolicy.symbols = length;
                updatePasswordValidityCheckpointLocked(userId, parent);
                saveSettingsLocked(userId);
            }
            logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_SYMBOLS)
                .setAdmin(who)
                .setInt(length)
                .write();
    }

    @Override
    public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
        return getStrictestPasswordRequirement(who, userHandle, parent,
                admin -> admin.mPasswordPolicy.symbols, PASSWORD_QUALITY_COMPLEX);
    }

    @Override
    public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
        if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumNonLetter")) {
            return;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final int userId = mInjector.userHandleGetCallingUserId();
        synchronized (getLockObject()) {
            ActiveAdmin ap = getActiveAdminForCallerLocked(
                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
            ensureMinimumQuality(
                    userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumNonLetter");
            final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
            if (passwordPolicy.nonLetter != length) {
                ap.mPasswordPolicy.nonLetter = length;
                updatePasswordValidityCheckpointLocked(userId, parent);
                saveSettingsLocked(userId);
            }
            logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_NON_LETTER)
                .setAdmin(who)
                .setInt(length)
                .write();
    }

    @Override
    public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
        return getStrictestPasswordRequirement(who, userHandle, parent,
                admin -> admin.mPasswordPolicy.nonLetter, PASSWORD_QUALITY_COMPLEX);
    }

    /**
     * Calculates strictest (maximum) value for a given password property enforced by admin[s].
     */
    private int getStrictestPasswordRequirement(ComponentName who, int userHandle,
            boolean parent, Function<ActiveAdmin, Integer> getter, int minimumPasswordQuality) {
        if (!mHasFeature) {
            return 0;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));

        synchronized (getLockObject()) {
            if (who != null) {
                final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
                return admin != null ? getter.apply(admin) : 0;
            }

            int maxValue = 0;
            final List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
                    getProfileParentUserIfRequested(userHandle, parent));
            final int N = admins.size();
            for (int i = 0; i < N; i++) {
                final ActiveAdmin admin = admins.get(i);
                if (!isLimitPasswordAllowed(admin, minimumPasswordQuality)) {
                    continue;
                }
                final Integer adminValue = getter.apply(admin);
                if (adminValue > maxValue) {
                    maxValue = adminValue;
                }
            }
            return maxValue;
        }
    }

    /**
     * Calculates strictest (maximum) value for a given password property enforced by admin[s].
     */
    @Override
    public PasswordMetrics getPasswordMinimumMetrics(@UserIdInt int userHandle,
            boolean deviceWideOnly) {
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)
                && (isSystemUid(caller)
                    // Accept any permission that ILockSettings#setLockCredential() accepts.
                    || hasCallingOrSelfPermission(permission.SET_INITIAL_LOCK)
                    || hasCallingOrSelfPermission(permission.SET_AND_VERIFY_LOCKSCREEN_CREDENTIALS)
                    || hasCallingOrSelfPermission(permission.ACCESS_KEYGUARD_SECURE_STORAGE)));
        return getPasswordMinimumMetricsUnchecked(userHandle, deviceWideOnly);
    }

    private PasswordMetrics getPasswordMinimumMetricsUnchecked(@UserIdInt int userId) {
        return getPasswordMinimumMetricsUnchecked(userId, false);
    }

    private PasswordMetrics getPasswordMinimumMetricsUnchecked(@UserIdInt int userId,
            boolean deviceWideOnly) {
        if (!mHasFeature) {
            new PasswordMetrics(CREDENTIAL_TYPE_NONE);
        }
        Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
        if (deviceWideOnly) {
            Preconditions.checkArgument(!isManagedProfile(userId));
        }

        ArrayList<PasswordMetrics> adminMetrics = new ArrayList<>();
        final List<ActiveAdmin> admins;
        synchronized (getLockObject()) {
            if (deviceWideOnly) {
                admins = getActiveAdminsForUserAndItsManagedProfilesLocked(userId,
                        /* shouldIncludeProfileAdmins */ (user) -> false);
            } else {
                admins = getActiveAdminsForLockscreenPoliciesLocked(userId);
            }
            for (ActiveAdmin admin : admins) {
                adminMetrics.add(admin.mPasswordPolicy.getMinMetrics());
            }
        }
        return PasswordMetrics.merge(adminMetrics);
    }

    @Override
    public boolean isActivePasswordSufficient(
            String callerPackageName, int userHandle, boolean parent) {
        if (!mHasFeature) {
            return true;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
        enforceUserUnlocked(userHandle, parent);

        synchronized (getLockObject()) {
            if (isPermissionCheckFlagEnabled()) {
                int affectedUser = parent ? getProfileParentId(userHandle) : userHandle;
                enforcePermission(MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
                        callerPackageName, affectedUser);
            } else {
                // This API can only be called by an active device admin,
                // so try to retrieve it to check that the caller is one.
                getActiveAdminForCallerLocked(
                        null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
            }

            int credentialOwner = getCredentialOwner(userHandle, parent);
            DevicePolicyData policy = getUserDataUnchecked(credentialOwner);
            PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(credentialOwner);
            final int userToCheck = getProfileParentUserIfRequested(userHandle, parent);
            boolean activePasswordSufficientForUserLocked = isActivePasswordSufficientForUserLocked(
                    policy.mPasswordValidAtLastCheckpoint, metrics, userToCheck);
            return activePasswordSufficientForUserLocked;
        }
    }

    @Override
    public boolean isActivePasswordSufficientForDeviceRequirement() {
        if (!mHasFeature) {
            return true;
        }
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(isProfileOwner(caller));

        final int profileUserId = caller.getUserId();
        Preconditions.checkCallingUser(isManagedProfile(profileUserId));

        // This method is always called on the parent DPM instance to check if its password (i.e.
        // the device password) is sufficient for all explicit password requirement set on it
        // So retrieve the parent user Id to which the device password belongs.
        final int parentUser = getProfileParentId(profileUserId);
        enforceUserUnlocked(parentUser);

        final boolean isSufficient;
        synchronized (getLockObject()) {

            int complexity = getAggregatedPasswordComplexityLocked(parentUser, true);
            PasswordMetrics minMetrics = getPasswordMinimumMetricsUnchecked(parentUser, true);

            PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(parentUser);
            final List<PasswordValidationError> passwordValidationErrors =
                    PasswordMetrics.validatePasswordMetrics(minMetrics, complexity, metrics);
            isSufficient = passwordValidationErrors.isEmpty();
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.IS_ACTIVE_PASSWORD_SUFFICIENT_FOR_DEVICE)
                .setStrings(mOwners.getProfileOwnerComponent(caller.getUserId()).getPackageName())
                .write();
        return isSufficient;
    }

    @Override
    public boolean isUsingUnifiedPassword(ComponentName admin) {
        if (!mHasFeature) {
            return true;
        }
        Objects.requireNonNull(admin, "ComponentName is null");

        final CallerIdentity caller = getCallerIdentity(admin);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
                || isProfileOwner(caller));
        Preconditions.checkCallingUser(isManagedProfile(caller.getUserId()));

        return !isSeparateProfileChallengeEnabled(caller.getUserId());
    }

    @Override
    public boolean isPasswordSufficientAfterProfileUnification(int userHandle, int profileUser) {
        if (!mHasFeature) {
            return true;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
        Preconditions.checkCallAuthorization(!isManagedProfile(userHandle),
                "You can not check password sufficiency for a managed profile, userId = %d",
                userHandle);
        enforceUserUnlocked(userHandle);

        synchronized (getLockObject()) {
            PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(userHandle);

            // Combine password policies across the user and its profiles. Profile admins are
            // included if the profile is to be unified or currently has unified challenge
            List<ActiveAdmin> admins = getActiveAdminsForUserAndItsManagedProfilesLocked(userHandle,
                    /* shouldIncludeProfileAdmins */ (user) -> user.id == profileUser
                    || !mLockPatternUtils.isSeparateProfileChallengeEnabled(user.id));
            ArrayList<PasswordMetrics> adminMetrics = new ArrayList<>(admins.size());
            int maxRequiredComplexity = PASSWORD_COMPLEXITY_NONE;
            for (ActiveAdmin admin : admins) {
                adminMetrics.add(admin.mPasswordPolicy.getMinMetrics());
                maxRequiredComplexity = Math.max(maxRequiredComplexity, admin.mPasswordComplexity);
            }
            return PasswordMetrics.validatePasswordMetrics(PasswordMetrics.merge(adminMetrics),
                    maxRequiredComplexity, metrics).isEmpty();
        }
    }

    private boolean isActivePasswordSufficientForUserLocked(
            boolean passwordValidAtLastCheckpoint, @Nullable PasswordMetrics metrics,
            int userHandle) {
        if (!mInjector.storageManagerIsFileBasedEncryptionEnabled() && (metrics == null)) {
            // Before user enters their password for the first time after a reboot, return the
            // value of this flag, which tells us whether the password was valid the last time
            // settings were saved.  If DPC changes password requirements on boot so that the
            // current password no longer meets the requirements, this value will be stale until
            // the next time the password is entered.
            return passwordValidAtLastCheckpoint;
        }

        if (metrics == null) {
            // Called on a FBE device when the user password exists but its metrics is unknown.
            // This shouldn't happen since we enforce the user to be unlocked (which would result
            // in the metrics known to the framework on a FBE device) at all call sites.
            throw new IllegalStateException("isActivePasswordSufficient called on FBE-locked user");
        }

        return isPasswordSufficientForUserWithoutCheckpointLocked(metrics, userHandle);
    }

    /**
     * Returns {@code true} if the password represented by the {@code metrics} argument
     * sufficiently fulfills the password requirements for the user corresponding to
     * {@code userId}.
     */
    private boolean isPasswordSufficientForUserWithoutCheckpointLocked(
            @NonNull PasswordMetrics metrics, @UserIdInt int userId) {
        final int complexity = getAggregatedPasswordComplexityLocked(userId);
        PasswordMetrics minMetrics = getPasswordMinimumMetricsUnchecked(userId);
        final List<PasswordValidationError> passwordValidationErrors =
                PasswordMetrics.validatePasswordMetrics(minMetrics, complexity, metrics);
        return passwordValidationErrors.isEmpty();
    }

    @Override
    @PasswordComplexity
    public int getPasswordComplexity(boolean parent) {
        final CallerIdentity caller = getCallerIdentity();
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.GET_USER_PASSWORD_COMPLEXITY_LEVEL)
                .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT,
                        mInjector.getPackageManager().getPackagesForUid(caller.getUid()))
                .write();

        enforceUserUnlocked(caller.getUserId());
        if (parent) {
            Preconditions.checkCallAuthorization(
                    isDefaultDeviceOwner(caller) || isProfileOwner(caller) || isSystemUid(caller),
                    "Only profile owner, device owner and system may call this method on parent.");
        } else {
            if (isPermissionCheckFlagEnabled()) {
                Preconditions.checkCallAuthorization(
                        hasCallingOrSelfPermission(REQUEST_PASSWORD_COMPLEXITY)
                                || hasCallingOrSelfPermission(MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS)
                                || isDefaultDeviceOwner(caller) || isProfileOwner(caller),
                        "Must have " + REQUEST_PASSWORD_COMPLEXITY + " or " +
                                MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS
                                + " permissions, or be a profile owner or device owner.");
            } else {
                Preconditions.checkCallAuthorization(
                        hasCallingOrSelfPermission(REQUEST_PASSWORD_COMPLEXITY)
                                || isDefaultDeviceOwner(caller) || isProfileOwner(caller),
                        "Must have " + REQUEST_PASSWORD_COMPLEXITY
                                + " permission, or be a profile owner or device owner.");
            }
        }

        synchronized (getLockObject()) {
            final int credentialOwner = getCredentialOwner(caller.getUserId(), parent);
            PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(credentialOwner);
            return metrics == null ? PASSWORD_COMPLEXITY_NONE : metrics.determineComplexity();
        }
    }

    @Override
    public void setRequiredPasswordComplexity(
            String callerPackageName, int passwordComplexity, boolean calledOnParent) {
        if (!mHasFeature) {
            return;
        }
        final Set<Integer> allowedModes = Set.of(PASSWORD_COMPLEXITY_NONE, PASSWORD_COMPLEXITY_LOW,
                PASSWORD_COMPLEXITY_MEDIUM, PASSWORD_COMPLEXITY_HIGH);
        Preconditions.checkArgument(allowedModes.contains(passwordComplexity),
                "Provided complexity is not one of the allowed values.");

        CallerIdentity caller = getCallerIdentity(callerPackageName);
        if (!isPermissionCheckFlagEnabled()) {
            Preconditions.checkCallAuthorization(
                    isDefaultDeviceOwner(caller) || isProfileOwner(caller));
            Preconditions.checkArgument(!calledOnParent || isProfileOwner(caller));
        }

        synchronized (getLockObject()) {
            ActiveAdmin admin;
            if (isPermissionCheckFlagEnabled()) {
                // TODO: Make sure this returns the parent of the fake admin
                // TODO: Deal with null componentname
                int affectedUser = calledOnParent
                        ? getProfileParentId(caller.getUserId()) : caller.getUserId();
                admin = enforcePermissionAndGetEnforcingAdmin(
                        null, MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
                        caller.getPackageName(), affectedUser).getActiveAdmin();
            } else {
                admin = getParentOfAdminIfRequired(
                        getProfileOwnerOrDeviceOwnerLocked(caller.getUserId()), calledOnParent);
            }

            if (admin.mPasswordComplexity != passwordComplexity) {
                // We require the caller to explicitly clear any password quality requirements set
                // on the parent DPM instance, to avoid the case where password requirements are
                // specified in the form of quality on the parent but complexity on the profile
                // itself.
                if (!calledOnParent) {
                    final boolean hasQualityRequirementsOnParent = admin.hasParentActiveAdmin()
                            && admin.getParentActiveAdmin().mPasswordPolicy.quality
                            != PASSWORD_QUALITY_UNSPECIFIED;
                    Preconditions.checkState(!hasQualityRequirementsOnParent,
                            "Password quality is set on the parent when attempting to set password"
                            + "complexity. Clear the quality by setting the password quality "
                            + "on the parent to PASSWORD_QUALITY_UNSPECIFIED first");
                }

                mInjector.binderWithCleanCallingIdentity(() -> {
                    admin.mPasswordComplexity = passwordComplexity;
                    // Reset the password policy.
                    admin.mPasswordPolicy = new PasswordPolicy();
                    updatePasswordValidityCheckpointLocked(caller.getUserId(), calledOnParent);
                    updatePasswordQualityCacheForUserGroup(caller.getUserId());
                    saveSettingsLocked(caller.getUserId());
                });


                //TODO(b/276855301): caller.getPackageName() will be null when the coexistence flags are
                // turned off. Change back to caller.getPackageName once this API is unflagged.
                DevicePolicyEventLogger
                        .createEvent(DevicePolicyEnums.SET_PASSWORD_COMPLEXITY)
                        .setAdmin(admin.info.getPackageName())
                        .setInt(passwordComplexity)
                        .setBoolean(calledOnParent)
                        .write();
            }
            logPasswordComplexityRequiredIfSecurityLogEnabled(caller.getPackageName(),
                    caller.getUserId(), calledOnParent, passwordComplexity);
        }
    }

    private void logPasswordComplexityRequiredIfSecurityLogEnabled(String adminPackageName,
            int userId,
            boolean parent, int complexity) {
        if (SecurityLog.isLoggingEnabled()) {
            final int affectedUserId = parent ? getProfileParentId(userId) : userId;
            SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_COMPLEXITY_REQUIRED,
                    adminPackageName, userId, affectedUserId, complexity);
        }
    }
    @GuardedBy("getLockObject()")
    private int getAggregatedPasswordComplexityLocked(@UserIdInt int userHandle) {
        return getAggregatedPasswordComplexityLocked(userHandle, false);
    }

    @GuardedBy("getLockObject()")
    private int getAggregatedPasswordComplexityLocked(@UserIdInt int userHandle,
            boolean deviceWideOnly) {
        ensureLocked();
        final List<ActiveAdmin> admins;
        if (deviceWideOnly) {
            admins = getActiveAdminsForUserAndItsManagedProfilesLocked(userHandle,
                    /* shouldIncludeProfileAdmins */ (user) -> false);
        } else {
            admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle);
        }
        int maxRequiredComplexity = PASSWORD_COMPLEXITY_NONE;
        for (ActiveAdmin admin : admins) {
            maxRequiredComplexity = Math.max(maxRequiredComplexity, admin.mPasswordComplexity);
        }
        return maxRequiredComplexity;
    }

    @Override
    public int getRequiredPasswordComplexity(String callerPackageName, boolean calledOnParent) {
        if (!mHasFeature) {
            return PASSWORD_COMPLEXITY_NONE;
        }

        final CallerIdentity caller = getCallerIdentity();

        if (isPermissionCheckFlagEnabled()) {
            int affectedUser = calledOnParent ? getProfileParentId(caller.getUserId())
                    : caller.getUserId();
            enforcePermission(MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
                    callerPackageName, affectedUser);
        } else {
            Preconditions.checkCallAuthorization(
                    isDefaultDeviceOwner(caller) || isProfileOwner(caller));

            Preconditions.checkArgument(!calledOnParent || isProfileOwner(caller));
        }

        synchronized (getLockObject()) {
            final ActiveAdmin requiredAdmin = getParentOfAdminIfRequired(
                    getDeviceOrProfileOwnerAdminLocked(caller.getUserId()), calledOnParent);
            return requiredAdmin.mPasswordComplexity;
        }
    }

    @Override
    public int getAggregatedPasswordComplexityForUser(int userId, boolean deviceWideOnly) {
        if (!mHasFeature) {
            return PASSWORD_COMPLEXITY_NONE;
        }

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId));

        synchronized (getLockObject()) {
            return getAggregatedPasswordComplexityLocked(userId, deviceWideOnly);
        }
    }


    @Override
    public int getCurrentFailedPasswordAttempts(
            String callerPackageName, int userHandle, boolean parent) {
        if (!mLockPatternUtils.hasSecureLockScreen()) {
            return 0;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));

        synchronized (getLockObject()) {
            if (!isSystemUid(caller)) {
                // This API can be called by an active device admin or by keyguard code.
                if (!hasCallingPermission(permission.ACCESS_KEYGUARD_SECURE_STORAGE)) {
                    if (isPermissionCheckFlagEnabled()) {
                        int affectedUser = parent ? getProfileParentId(userHandle) : userHandle;
                        enforcePermission(MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
                                callerPackageName, affectedUser);
                    } else {
                        getActiveAdminForCallerLocked(
                                null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
                    }
                }
            }

            DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));

            return policy.mFailedPasswordAttempts;
        }
    }

    @Override
    public void setMaximumFailedPasswordsForWipe(
            ComponentName who, String callerPackageName, int num, boolean parent) {
        if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
            return;
        }

        if (!isPermissionCheckFlagEnabled()) {
            Objects.requireNonNull(who, "ComponentName is null");
        }


        int userId = mInjector.userHandleGetCallingUserId();
        int affectedUserId = parent ? getProfileParentId(userId) : userId;

        synchronized (getLockObject()) {
            ActiveAdmin ap;
            if (isPermissionCheckFlagEnabled()) {
                CallerIdentity caller = getCallerIdentity(who, callerPackageName);
                ap = enforcePermissionAndGetEnforcingAdmin(
                        who,
                        /*permission=*/ MANAGE_DEVICE_POLICY_WIPE_DATA,
                        /* adminPolicy=*/ DeviceAdminInfo.USES_POLICY_WIPE_DATA,
                        caller.getPackageName(), affectedUserId).getActiveAdmin();
            } else {
                // This API can only be called by an active device admin,
                // so try to retrieve it to check that the caller is one.
                getActiveAdminForCallerLocked(
                        who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
                ap = getActiveAdminForCallerLocked(
                        who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
            }

            if (ap.maximumFailedPasswordsForWipe != num) {
                ap.maximumFailedPasswordsForWipe = num;
                saveSettingsLocked(userId);
            }
        }
        if (SecurityLog.isLoggingEnabled()) {
            SecurityLog.writeEvent(SecurityLog.TAG_MAX_PASSWORD_ATTEMPTS_SET, callerPackageName,
                    userId, affectedUserId, num);
        }
    }

    @Override
    public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
        if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
            return 0;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
        // System caller can query policy for a particular admin.
        Preconditions.checkCallAuthorization(
                who == null || isCallingFromPackage(who.getPackageName(), caller.getUid())
                        || canQueryAdminPolicy(caller));

        synchronized (getLockObject()) {
            ActiveAdmin admin = (who != null)
                    ? getActiveAdminUncheckedLocked(who, userHandle, parent)
                    : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
            return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
        }
    }

    @Override
    public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
        if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
            return UserHandle.USER_NULL;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));

        synchronized (getLockObject()) {
            ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
                    userHandle, parent);
            return admin != null ? getUserIdToWipeForFailedPasswords(admin) : UserHandle.USER_NULL;
        }
    }

    /**
     * Returns the admin with the strictest policy on maximum failed passwords for:
     * <ul>
     *   <li>this user if it has a separate profile challenge, or
     *   <li>this user and all profiles that don't have their own challenge otherwise.
     * </ul>
     * <p>If the policy for the primary and any other profile are equal, it returns the admin for
     * the primary profile. Policy of a PO on an organization-owned device applies to the primary
     * profile.
     * Returns {@code null} if no participating admin has that policy set.
     */
    @GuardedBy("getLockObject()")
    private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
            int userHandle, boolean parent) {
        int count = 0;
        ActiveAdmin strictestAdmin = null;

        // Return the strictest policy across all participating admins.
        List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
                getProfileParentUserIfRequested(userHandle, parent));
        final int N = admins.size();
        for (int i = 0; i < N; i++) {
            ActiveAdmin admin = admins.get(i);
            if (admin.maximumFailedPasswordsForWipe ==
                    ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
                continue;  // No max number of failed passwords policy set for this profile.
            }

            // We always favor the primary profile if several profiles have the same value set.
            final int userId = getUserIdToWipeForFailedPasswords(admin);
            if (count == 0 ||
                    count > admin.maximumFailedPasswordsForWipe ||
                    (count == admin.maximumFailedPasswordsForWipe &&
                            getUserInfo(userId).isPrimary())) {
                count = admin.maximumFailedPasswordsForWipe;
                strictestAdmin = admin;
            }
        }
        return strictestAdmin;
    }

    private UserInfo getUserInfo(@UserIdInt int userId) {
        return mInjector.binderWithCleanCallingIdentity(() -> mUserManager.getUserInfo(userId));
    }

    private boolean setPasswordPrivileged(@NonNull String password, int flags,
            CallerIdentity caller) {
        // Only allow setting password on an unsecured user
        if (isLockScreenSecureUnchecked(caller.getUserId())) {
            throw new SecurityException("Cannot change current password");
        }
        return resetPasswordInternal(password, 0, null, flags, caller);
    }

    @Override
    public boolean resetPassword(@Nullable String password, int flags) throws RemoteException {
        if (!mLockPatternUtils.hasSecureLockScreen()) {
            Slogf.w(LOG_TAG, "Cannot reset password when the device has no lock screen");
            return false;
        }
        if (password == null) password = "";
        final CallerIdentity caller = getCallerIdentity();
        final int userHandle = caller.getUserId();

        // As of R, only privileged caller holding RESET_PASSWORD can call resetPassword() to
        // set password to an unsecured user.
        if (hasCallingPermission(permission.RESET_PASSWORD)) {
            final boolean result = setPasswordPrivileged(password, flags, caller);
            if (result) {
                DevicePolicyEventLogger
                        .createEvent(DevicePolicyEnums.RESET_PASSWORD)
                        .write();
            }
            return result;
        }

        // If caller has PO (or DO) throw or fail silently depending on its target SDK level.
        if (isDefaultDeviceOwner(caller) || isProfileOwner(caller)) {
            synchronized (getLockObject()) {
                ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
                if (getTargetSdk(admin.info.getPackageName(), userHandle) < Build.VERSION_CODES.O) {
                    Slogf.e(LOG_TAG, "DPC can no longer call resetPassword()");
                    return false;
                }
                throw new SecurityException("Device admin can no longer call resetPassword()");
            }
        }

        // Caller is not DO or PO, could either be unauthorized or Device Admin.
        synchronized (getLockObject()) {
            // Legacy device admin cannot call resetPassword either
            ActiveAdmin admin = getActiveAdminForCallerLocked(
                    null, DeviceAdminInfo.USES_POLICY_RESET_PASSWORD, false);
            Preconditions.checkCallAuthorization(admin != null,
                    "Unauthorized caller cannot call resetPassword.");
            if (getTargetSdk(admin.info.getPackageName(),
                    userHandle) <= android.os.Build.VERSION_CODES.M) {
                Slogf.e(LOG_TAG, "Device admin can no longer call resetPassword()");
                return false;
            }
            throw new SecurityException("Device admin can no longer call resetPassword()");
        }
    }

    private boolean resetPasswordInternal(String password, long tokenHandle, byte[] token,
            int flags, CallerIdentity caller) {
        final int callingUid = caller.getUid();
        final int userHandle = UserHandle.getUserId(callingUid);
        final boolean isPin = PasswordMetrics.isNumericOnly(password);
        final LockscreenCredential newCredential;
        if (isPin) {
            newCredential = LockscreenCredential.createPin(password);
        } else {
            newCredential = LockscreenCredential.createPasswordOrNone(password);
        }
        synchronized (getLockObject()) {
            final PasswordMetrics minMetrics = getPasswordMinimumMetricsUnchecked(userHandle);
            final int complexity = getAggregatedPasswordComplexityLocked(userHandle);
            final List<PasswordValidationError> validationErrors =
                    PasswordMetrics.validateCredential(minMetrics, complexity, newCredential);
            if (!validationErrors.isEmpty()) {
                Slogf.w(LOG_TAG, "Failed to reset password due to constraint violation: %s",
                        validationErrors.get(0));
                return false;
            }
        }

        DevicePolicyData policy = getUserData(userHandle);
        if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
            Slogf.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
            return false;
        }

        boolean callerIsDeviceOwnerAdmin = isDefaultDeviceOwner(caller);
        boolean doNotAskCredentialsOnBoot =
                (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
        if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
            setDoNotAskCredentialsOnBoot();
        }

        // Don't do this with the lock held, because it is going to call
        // back in to the service.
        final long ident = mInjector.binderClearCallingIdentity();
        try {
            if (tokenHandle == 0 || token == null) {
                if (!mLockPatternUtils.setLockCredential(newCredential,
                        LockscreenCredential.createNone(), userHandle)) {
                    return false;
                }
            } else {
                if (!mLockPatternUtils.setLockCredentialWithToken(newCredential, tokenHandle,
                        token, userHandle)) {
                    return false;
                }
            }
            boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
            if (requireEntry) {
                mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
                        UserHandle.USER_ALL);
            }
            synchronized (getLockObject()) {
                int newOwner = requireEntry ? callingUid : -1;
                if (policy.mPasswordOwner != newOwner) {
                    policy.mPasswordOwner = newOwner;
                    saveSettingsLocked(userHandle);
                }
            }
        } finally {
            mInjector.binderRestoreCallingIdentity(ident);
        }
        return true;
    }

    private boolean isLockScreenSecureUnchecked(int userId) {
        return mInjector.binderWithCleanCallingIdentity(() -> mLockPatternUtils.isSecure(userId));
    }

    private void setDoNotAskCredentialsOnBoot() {
        synchronized (getLockObject()) {
            DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
            if (!policyData.mDoNotAskCredentialsOnBoot) {
                policyData.mDoNotAskCredentialsOnBoot = true;
                saveSettingsLocked(UserHandle.USER_SYSTEM);
            }
        }
    }

    @Override
    public boolean getDoNotAskCredentialsOnBoot() {
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT));
        synchronized (getLockObject()) {
            DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
            return policyData.mDoNotAskCredentialsOnBoot;
        }
    }

    @Override
    public void setMaximumTimeToLock(ComponentName who, String callerPackageName,
            long timeMs, boolean parent) {
        if (!mHasFeature) {
            return;
        }
        if (!isPermissionCheckFlagEnabled()) {
            Objects.requireNonNull(who, "ComponentName is null");
        }
        int userHandle = mInjector.userHandleGetCallingUserId();
        int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
        synchronized (getLockObject()) {
            ActiveAdmin ap;
            if (isPermissionCheckFlagEnabled()) {
                CallerIdentity caller = getCallerIdentity(who, callerPackageName);
                ap = enforcePermissionAndGetEnforcingAdmin(
                        who,
                        /*permission=*/ MANAGE_DEVICE_POLICY_LOCK,
                        /*AdminPolicy=*/DeviceAdminInfo.USES_POLICY_FORCE_LOCK,
                        caller.getPackageName(),
                        affectedUserId).getActiveAdmin();
            } else {
                ap = getActiveAdminForCallerLocked(
                        who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
            }

            if (ap.maximumTimeToUnlock != timeMs) {
                ap.maximumTimeToUnlock = timeMs;
                saveSettingsLocked(userHandle);
                updateMaximumTimeToLockLocked(userHandle);
            }
        }
        if (SecurityLog.isLoggingEnabled()) {
            SecurityLog.writeEvent(SecurityLog.TAG_MAX_SCREEN_LOCK_TIMEOUT_SET,
                    callerPackageName, userHandle, affectedUserId, timeMs);
        }
    }

    @GuardedBy("getLockObject()")
    private void updateMaximumTimeToLockLocked(@UserIdInt int userId) {
        // Update the profile's timeout
        if (isManagedProfile(userId)) {
            updateProfileLockTimeoutLocked(userId);
        }

        mInjector.binderWithCleanCallingIdentity(() -> {
            // Update the device timeout
            final int parentId = getProfileParentId(userId);
            final long timeMs = getMaximumTimeToLockPolicyFromAdmins(
                    getActiveAdminsForLockscreenPoliciesLocked(parentId));

            final DevicePolicyData policy = getUserDataUnchecked(parentId);
            if (policy.mLastMaximumTimeToLock == timeMs) {
                return;
            }
            policy.mLastMaximumTimeToLock = timeMs;

            if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
                // Make sure KEEP_SCREEN_ON is disabled, since that
                // would allow bypassing of the maximum time to lock.
                mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
            }
            getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(parentId, timeMs);
        });
    }

    @GuardedBy("getLockObject()")
    private void updateProfileLockTimeoutLocked(@UserIdInt int userId) {
        final long timeMs;
        if (isSeparateProfileChallengeEnabled(userId)) {
            timeMs = getMaximumTimeToLockPolicyFromAdmins(
                    getActiveAdminsForLockscreenPoliciesLocked(userId));
        } else {
            timeMs = Long.MAX_VALUE;
        }

        final DevicePolicyData policy = getUserDataUnchecked(userId);
        if (policy.mLastMaximumTimeToLock == timeMs) {
            return;
        }
        policy.mLastMaximumTimeToLock = timeMs;

        mInjector.binderWithCleanCallingIdentity(() ->
                getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
                        userId, policy.mLastMaximumTimeToLock));
    }

    @Override
    public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
        if (!mHasFeature) {
            return 0;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
        // System caller can query policy for a particular admin.
        Preconditions.checkCallAuthorization(
                who == null || isCallingFromPackage(who.getPackageName(), caller.getUid())
                        || canQueryAdminPolicy(caller));

        synchronized (getLockObject()) {
            if (who != null) {
                final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
                return admin != null ? admin.maximumTimeToUnlock : 0;
            }
            // Return the strictest policy across all participating admins.
            final List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
                    getProfileParentUserIfRequested(userHandle, parent));
            final long timeMs = getMaximumTimeToLockPolicyFromAdmins(admins);
            return timeMs == Long.MAX_VALUE ? 0 : timeMs;
        }
    }

    private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
        long time = Long.MAX_VALUE;
        for (final ActiveAdmin admin : admins) {
            if (admin.maximumTimeToUnlock > 0 && admin.maximumTimeToUnlock < time) {
                time = admin.maximumTimeToUnlock;
            }
        }
        return time;
    }

    @Override
    public void setRequiredStrongAuthTimeout(ComponentName who, String callerPackageName, long timeoutMs,
            boolean parent) {
        if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
            return;
        }
        Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number.");
        CallerIdentity caller;
        if (isPermissionCheckFlagEnabled()) {
            caller = getCallerIdentity(who, callerPackageName);
        } else {
            caller = getCallerIdentity(who);
            Objects.requireNonNull(who, "ComponentName is null");
            Preconditions.checkCallAuthorization(
                    isDefaultDeviceOwner(caller) || isProfileOwner(caller));
        }
        // timeoutMs with value 0 means that the admin doesn't participate
        // timeoutMs is clamped to the interval in case the internal constants change in the future
        final long minimumStrongAuthTimeout = getMinimumStrongAuthTimeoutMs();
        if (timeoutMs != 0 && timeoutMs < minimumStrongAuthTimeout) {
            timeoutMs = minimumStrongAuthTimeout;
        }
        if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
            timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
        }

        final int userHandle = caller.getUserId();
        boolean changed = false;
        synchronized (getLockObject()) {
            ActiveAdmin ap;
            if (isPermissionCheckFlagEnabled()) {
                int affectedUser = parent
                        ? getProfileParentId(caller.getUserId()) : caller.getUserId();
                ap = enforcePermissionAndGetEnforcingAdmin(
                        who, MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
                        caller.getPackageName(), affectedUser).getActiveAdmin();
            } else {
                ap = getParentOfAdminIfRequired(
                        getProfileOwnerOrDeviceOwnerLocked(caller.getUserId()), parent);
            }
            if (ap.strongAuthUnlockTimeout != timeoutMs) {
                ap.strongAuthUnlockTimeout = timeoutMs;
                saveSettingsLocked(userHandle);
                changed = true;
            }
        }
        if (changed) {
            mLockSettingsInternal.refreshStrongAuthTimeout(userHandle);
            // Refreshes the parent if profile has unified challenge, since the timeout would
            // also affect the parent user in this case.
            if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) {
                mLockSettingsInternal.refreshStrongAuthTimeout(getProfileParentId(userHandle));
            }
        }
    }

    /**
     * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all
     * admins if who is null.
     * Returns 0 if not configured for the provided admin.
     */
    @Override
    public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) {
        if (!mHasFeature) {
            return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
        }
        Preconditions.checkArgumentNonnegative(userId, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId));

        if (!mLockPatternUtils.hasSecureLockScreen()) {
            // No strong auth timeout on devices not supporting the
            // {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature
            return 0;
        }
        synchronized (getLockObject()) {
            if (who != null) {
                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent);
                return admin != null ? admin.strongAuthUnlockTimeout : 0;
            }

            // Return the strictest policy across all participating admins.
            List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
                    getProfileParentUserIfRequested(userId, parent));

            long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
            for (int i = 0; i < admins.size(); i++) {
                final long timeout = admins.get(i).strongAuthUnlockTimeout;
                if (timeout != 0) { // take only participating admins into account
                    strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout);
                }
            }
            return Math.max(strongAuthUnlockTimeout, getMinimumStrongAuthTimeoutMs());
        }
    }

    private long getMinimumStrongAuthTimeoutMs() {
        if (!mInjector.isBuildDebuggable()) {
            return MINIMUM_STRONG_AUTH_TIMEOUT_MS;
        }
        // ideally the property was named persist.sys.min_strong_auth_timeout, but system property
        // name cannot be longer than 31 characters
        return Math.min(mInjector.systemPropertiesGetLong("persist.sys.min_str_auth_timeo",
                MINIMUM_STRONG_AUTH_TIMEOUT_MS),
                MINIMUM_STRONG_AUTH_TIMEOUT_MS);
    }

    @Override
    public void lockNow(int flags, String callerPackageName, boolean parent) {
        CallerIdentity caller;
        if (isUnicornFlagEnabled()) {
            caller = getCallerIdentity(callerPackageName);
        } else {
            caller = getCallerIdentity();
        }

        final int callingUserId = caller.getUserId();
        ComponentName adminComponent = null;
        synchronized (getLockObject()) {
            ActiveAdmin admin;
            // Make sure the caller has any active admin with the right policy or
            // the required permission.
            if (isUnicornFlagEnabled()) {
                admin = enforcePermissionAndGetEnforcingAdmin(
                        /* admin= */ null,
                        /* permission= */ MANAGE_DEVICE_POLICY_LOCK,
                        USES_POLICY_FORCE_LOCK,
                        caller.getPackageName(),
                        getAffectedUser(parent)
                 ).getActiveAdmin();
            } else {
                admin = getActiveAdminOrCheckPermissionForCallerLocked(
                        null,
                        DeviceAdminInfo.USES_POLICY_FORCE_LOCK,
                        parent,
                        LOCK_DEVICE);
            }
            checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_LOCK_NOW);
            final long ident = mInjector.binderClearCallingIdentity();
            try {
                adminComponent = admin == null ? null : admin.info.getComponent();
                if (adminComponent != null) {
                    // For Profile Owners only, callers with only permission not allowed.
                    if ((flags & DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY) != 0) {
                        // Evict key
                        Preconditions.checkCallingUser(isManagedProfile(callingUserId));
                        Preconditions.checkArgument(!parent,
                                "Cannot set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY for the parent");
                        if (!isProfileOwner(adminComponent, callingUserId)) {
                            throw new SecurityException("Only profile owner admins can set "
                                    + "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY");
                        }
                        if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
                            throw new UnsupportedOperationException(
                                    "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY only applies to FBE"
                                        + " devices");
                        }
                        mUserManager.evictCredentialEncryptionKey(callingUserId);
                    }
                }

                // Lock all users unless this is a managed profile with a separate challenge
                final int userToLock = (parent || !isSeparateProfileChallengeEnabled(callingUserId)
                        ? UserHandle.USER_ALL : callingUserId);
                mLockPatternUtils.requireStrongAuth(
                        STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);

                // Require authentication for the device or profile
                if (userToLock == UserHandle.USER_ALL) {
                    if (mIsAutomotive) {
                        if (VERBOSE_LOG) {
                            Slogf.v(LOG_TAG, "lockNow(): not powering off display on automotive"
                                    + " build");
                        }
                    } else {
                        // Power off the display
                        mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
                                PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
                    }
                    mInjector.getIWindowManager().lockNow(null);
                } else {
                    mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
                }

                if (SecurityLog.isLoggingEnabled() && adminComponent != null) {
                    final int affectedUserId =
                            parent ? getProfileParentId(callingUserId) : callingUserId;
                    SecurityLog.writeEvent(SecurityLog.TAG_REMOTE_LOCK,
                            adminComponent.getPackageName(), callingUserId, affectedUserId);
                }
            } catch (RemoteException e) {
            } finally {
                mInjector.binderRestoreCallingIdentity(ident);
            }
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.LOCK_NOW)
                .setAdmin(adminComponent)
                .setInt(flags)
                .write();
    }

    @Override
    public void enforceCanManageCaCerts(ComponentName who, String callerPackage) {
        final CallerIdentity caller = getCallerIdentity(who, callerPackage);
        Preconditions.checkCallAuthorization(canManageCaCerts(caller));
    }

    private boolean canManageCaCerts(CallerIdentity caller) {
        return (caller.hasAdminComponent() && (isDefaultDeviceOwner(caller)
                || isProfileOwner(caller)))
                || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_CERT_INSTALL))
                || hasCallingOrSelfPermission(MANAGE_CA_CERTIFICATES);
    }

    @Override
    public boolean approveCaCert(String alias, int userId, boolean approval) {
        Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));

        synchronized (getLockObject()) {
            Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
            boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
            if (!changed) {
                return false;
            }
            saveSettingsLocked(userId);
        }
        mCertificateMonitor.onCertificateApprovalsChanged(userId);
        return true;
    }

    @Override
    public boolean isCaCertApproved(String alias, int userId) {
        Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));

        synchronized (getLockObject()) {
            return getUserData(userId).mAcceptedCaCertificates.contains(alias);
        }
    }

    private Set<Integer> removeCaApprovalsIfNeeded(int userId) {
        final ArraySet<Integer> affectedUserIds = new ArraySet<>();
        for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
            boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
            if (userInfo.isManagedProfile()){
                isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
            }
            if (!isSecure) {
                synchronized (getLockObject()) {
                    getUserData(userInfo.id).mAcceptedCaCertificates.clear();
                    affectedUserIds.add(userInfo.id);
                }
                mCertificateMonitor.onCertificateApprovalsChanged(userId);
            }
        }
        return affectedUserIds;
    }

    @Override
    public boolean installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer) {
        if (!mHasFeature) {
            return false;
        }
        final CallerIdentity caller = getCallerIdentity(admin, callerPackage);
        Preconditions.checkCallAuthorization(canManageCaCerts(caller));
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_INSTALL_CA_CERT);

        final String alias = mInjector.binderWithCleanCallingIdentity(() -> {
            String installedAlias = mCertificateMonitor.installCaCert(
                    caller.getUserHandle(), certBuffer);
            DevicePolicyEventLogger
                    .createEvent(DevicePolicyEnums.INSTALL_CA_CERT)
                    .setAdmin(caller.getPackageName())
                    .setBoolean(/* isDelegate */ admin == null)
                    .write();

            if (mInjector.isAdminInstalledCaCertAutoApproved()
                    && installedAlias != null
                    && admin != null) {
                // If device admin called this, approve cert to avoid notifications
                Slogf.i(LOG_TAG, "Approving admin installed cert");
                approveCaCert(
                        installedAlias,
                        caller.getUserId(),
                        /* approved */ true);
            }

            return installedAlias;
        });

        if (alias == null) {
            Slogf.w(LOG_TAG, "Problem installing cert");
            return false;
        }

        synchronized (getLockObject()) {
            getUserData(caller.getUserId()).mOwnerInstalledCaCerts.add(alias);
            saveSettingsLocked(caller.getUserId());
        }
        return true;
    }

    @Override
    public void uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases) {
        if (!mHasFeature) {
            return;
        }
        final CallerIdentity caller = getCallerIdentity(admin, callerPackage);
        Preconditions.checkCallAuthorization(canManageCaCerts(caller));
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_UNINSTALL_CA_CERT);

        mInjector.binderWithCleanCallingIdentity(() -> {
            mCertificateMonitor.uninstallCaCerts(caller.getUserHandle(), aliases);
            DevicePolicyEventLogger
                    .createEvent(DevicePolicyEnums.UNINSTALL_CA_CERTS)
                    .setAdmin(caller.getPackageName())
                    .setBoolean(/* isDelegate */ admin == null)
                    .write();
        });

        synchronized (getLockObject()) {
            if (getUserData(caller.getUserId()).mOwnerInstalledCaCerts.removeAll(
                    Arrays.asList(aliases))) {
                saveSettingsLocked(caller.getUserId());
            }
        }
    }

    @Override
    public boolean installKeyPair(ComponentName who, String callerPackage, byte[] privKey,
            byte[] cert, byte[] chain, String alias, boolean requestAccess,
            boolean isUserSelectable) {
        final CallerIdentity caller = getCallerIdentity(who, callerPackage);
        final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL);
        final boolean isCredentialManagementApp = isCredentialManagementApp(caller);
        if (isPermissionCheckFlagEnabled()) {
            Preconditions.checkCallAuthorization(
                    hasPermission(MANAGE_DEVICE_POLICY_CERTIFICATES,
                            caller.getPackageName(), caller.getUserId())
                            || isCredentialManagementApp);
        }  else {
            Preconditions.checkCallAuthorization((caller.hasAdminComponent()
                    && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
                    || (caller.hasPackage() && (isCallerDelegate || isCredentialManagementApp)));
        }
        if (isCredentialManagementApp) {
            Preconditions.checkCallAuthorization(!isUserSelectable, "The credential "
                    + "management app is not allowed to install a user selectable key pair");
            Preconditions.checkCallAuthorization(
                    isAliasInCredentialManagementAppPolicy(caller, alias),
                    CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG);
        }
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_INSTALL_KEY_PAIR);

        final long id = mInjector.binderClearCallingIdentity();
        try {
            final KeyChainConnection keyChainConnection =
                    KeyChain.bindAsUser(mContext, caller.getUserHandle());
            try {
                IKeyChainService keyChain = keyChainConnection.getService();
                if (!keyChain.installKeyPair(privKey, cert, chain, alias, KeyProperties.UID_SELF)) {
                    logInstallKeyPairFailure(caller, isCredentialManagementApp);
                    return false;
                }
                if (requestAccess) {
                    keyChain.setGrant(caller.getUid(), alias, true);
                }
                keyChain.setUserSelectable(alias, isUserSelectable);
                DevicePolicyEventLogger
                        .createEvent(DevicePolicyEnums.INSTALL_KEY_PAIR)
                        .setAdmin(caller.getPackageName())
                        .setBoolean(/* isDelegate */ isCallerDelegate)
                        .setStrings(isCredentialManagementApp
                                ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP)
                        .write();
                return true;
            } catch (RemoteException e) {
                Slogf.e(LOG_TAG, "Installing certificate", e);
            } finally {
                keyChainConnection.close();
            }
        } catch (InterruptedException e) {
            Slogf.w(LOG_TAG, "Interrupted while installing certificate", e);
            Thread.currentThread().interrupt();
        } finally {
            mInjector.binderRestoreCallingIdentity(id);
        }
        logInstallKeyPairFailure(caller, isCredentialManagementApp);
        return false;
    }

    private void logInstallKeyPairFailure(CallerIdentity caller,
            boolean isCredentialManagementApp) {
        if (!isCredentialManagementApp) {
            return;
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.CREDENTIAL_MANAGEMENT_APP_INSTALL_KEY_PAIR_FAILED)
                .setStrings(caller.getPackageName())
                .write();
    }

    @Override
    public boolean removeKeyPair(ComponentName who, String callerPackage, String alias) {
        final CallerIdentity caller = getCallerIdentity(who, callerPackage);
        final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL);
        final boolean isCredentialManagementApp = isCredentialManagementApp(caller);
        if (isPermissionCheckFlagEnabled()) {
            Preconditions.checkCallAuthorization(
                    hasPermission(MANAGE_DEVICE_POLICY_CERTIFICATES,
                            caller.getPackageName(), caller.getUserId())
                            || isCredentialManagementApp);
        }  else {
            Preconditions.checkCallAuthorization((caller.hasAdminComponent()
                    && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
                    || (caller.hasPackage() && (isCallerDelegate || isCredentialManagementApp)));
        }
        if (isCredentialManagementApp) {
            Preconditions.checkCallAuthorization(
                    isAliasInCredentialManagementAppPolicy(caller, alias),
                    CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG);
        }
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REMOVE_KEY_PAIR);

        final long id = Binder.clearCallingIdentity();
        try {
            final KeyChainConnection keyChainConnection =
                    KeyChain.bindAsUser(mContext, caller.getUserHandle());
            try {
                IKeyChainService keyChain = keyChainConnection.getService();
                DevicePolicyEventLogger
                        .createEvent(DevicePolicyEnums.REMOVE_KEY_PAIR)
                        .setAdmin(caller.getPackageName())
                        .setBoolean(/* isDelegate */ isCallerDelegate)
                        .setStrings(isCredentialManagementApp
                                ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP)
                        .write();
                return keyChain.removeKeyPair(alias);
            } catch (RemoteException e) {
                Slogf.e(LOG_TAG, "Removing keypair", e);
            } finally {
                keyChainConnection.close();
            }
        } catch (InterruptedException e) {
            Slogf.w(LOG_TAG, "Interrupted while removing keypair", e);
            Thread.currentThread().interrupt();
        } finally {
            Binder.restoreCallingIdentity(id);
        }
        return false;
    }

    @Override
    public boolean hasKeyPair(String callerPackage, String alias) {
        final CallerIdentity caller = getCallerIdentity(callerPackage);
        final boolean isCredentialManagementApp = isCredentialManagementApp(caller);
        Preconditions.checkCallAuthorization(canInstallCertificates(caller)
                || isCredentialManagementApp);
        if (isCredentialManagementApp) {
            Preconditions.checkCallAuthorization(
                    isAliasInCredentialManagementAppPolicy(caller, alias),
                    CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG);
        }

        return mInjector.binderWithCleanCallingIdentity(() -> {
            try (KeyChainConnection keyChainConnection =
                         KeyChain.bindAsUser(mContext, caller.getUserHandle())) {
                return keyChainConnection.getService().containsKeyPair(alias);
            } catch (RemoteException e) {
                Slogf.e(LOG_TAG, "Querying keypair", e);
            } catch (InterruptedException e) {
                Slogf.w(LOG_TAG, "Interrupted while querying keypair", e);
                Thread.currentThread().interrupt();
            }
            return false;
        });
    }

    private boolean canInstallCertificates(CallerIdentity caller) {
        if (isPermissionCheckFlagEnabled()) {
            return hasPermission(MANAGE_DEVICE_POLICY_CERTIFICATES,
                    caller.getPackageName(), caller.getUserId());
        }  else {
            return isProfileOwner(caller) || isDefaultDeviceOwner(caller)
                    || isCallerDelegate(caller, DELEGATION_CERT_INSTALL);
        }
    }

    private boolean canChooseCertificates(CallerIdentity caller) {
        return isProfileOwner(caller) || isDefaultDeviceOwner(caller)
                || isCallerDelegate(caller, DELEGATION_CERT_SELECTION);
    }

    @Override
    public boolean setKeyGrantToWifiAuth(String callerPackage, String alias, boolean hasGrant) {
        Preconditions.checkStringNotEmpty(alias, "Alias to grant cannot be empty");

        final CallerIdentity caller = getCallerIdentity(callerPackage);
        Preconditions.checkCallAuthorization(canChooseCertificates(caller));
        try {
            return setKeyChainGrantInternal(
                    alias, hasGrant, Process.WIFI_UID, caller.getUserHandle());
        } catch (IllegalArgumentException e) {
            if (mInjector.isChangeEnabled(THROW_EXCEPTION_WHEN_KEY_MISSING, caller.getPackageName(),
                    caller.getUserId())) {
                throw e;
            }
            return false;
        }
    }

    @Override
    public boolean isKeyPairGrantedToWifiAuth(String callerPackage, String alias) {
        Preconditions.checkStringNotEmpty(alias, "Alias to check cannot be empty");

        final CallerIdentity caller = getCallerIdentity(callerPackage);
        Preconditions.checkCallAuthorization(canChooseCertificates(caller));

        return mInjector.binderWithCleanCallingIdentity(() -> {
            try (KeyChainConnection keyChainConnection =
                         KeyChain.bindAsUser(mContext, caller.getUserHandle())) {
                final List<String> result = new ArrayList<>();
                final int[] granteeUids = keyChainConnection.getService().getGrants(alias);

                for (final int uid : granteeUids) {
                    if (uid == Process.WIFI_UID) {
                        return true;
                    }
                }
                return false;
            } catch (RemoteException e) {
                Slogf.e(LOG_TAG, "Querying grant to wifi auth.", e);
                return false;
            }
        });
    }

    @Override
    public boolean setKeyGrantForApp(ComponentName who, String callerPackage, String alias,
            String packageName, boolean hasGrant) {
        Preconditions.checkStringNotEmpty(alias, "Alias to grant cannot be empty");
        Preconditions.checkStringNotEmpty(packageName, "Package to grant to cannot be empty");

        final CallerIdentity caller = getCallerIdentity(who, callerPackage);
        Preconditions.checkCallAuthorization((caller.hasAdminComponent()
                && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
                || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_CERT_SELECTION)));

        final int granteeUid;
        try {
            ApplicationInfo ai = mInjector.getIPackageManager().getApplicationInfo(
                    packageName, 0, caller.getUserId());
            Preconditions.checkArgument(ai != null,
                    "Provided package %s is not installed", packageName);
            granteeUid = ai.uid;
        } catch (RemoteException e) {
            throw new IllegalStateException("Failure getting grantee uid", e);
        }
        try {
            return setKeyChainGrantInternal(alias, hasGrant, granteeUid, caller.getUserHandle());
        } catch (IllegalArgumentException e) {
            if (mInjector.isChangeEnabled(THROW_EXCEPTION_WHEN_KEY_MISSING, callerPackage,
                    caller.getUserId())) {
                throw e;
            }
            return false;
        }
    }

    private boolean setKeyChainGrantInternal(String alias, boolean hasGrant, int granteeUid,
            UserHandle userHandle) {
        final long id = mInjector.binderClearCallingIdentity();
        try {
            try (KeyChainConnection keyChainConnection =
                         KeyChain.bindAsUser(mContext, userHandle)) {
                IKeyChainService keyChain = keyChainConnection.getService();
                return keyChain.setGrant(granteeUid, alias, hasGrant);
            } catch (RemoteException | AssertionError e) {
                Slogf.e(LOG_TAG, "Setting grant for package.", e);
                return false;
            }
        } catch (InterruptedException e) {
            Slogf.w(LOG_TAG, "Interrupted while setting key grant", e);
            Thread.currentThread().interrupt();
        } finally {
            mInjector.binderRestoreCallingIdentity(id);
        }
        return false;
    }

    @Override
    public ParcelableGranteeMap getKeyPairGrants(String callerPackage, String alias) {
        final CallerIdentity caller = getCallerIdentity(callerPackage);
        Preconditions.checkCallAuthorization(canChooseCertificates(caller));

        final ArrayMap<Integer, Set<String>> result = new ArrayMap<>();
        mInjector.binderWithCleanCallingIdentity(() -> {
            try (KeyChainConnection keyChainConnection =
                         KeyChain.bindAsUser(mContext, caller.getUserHandle())) {
                final int[] granteeUids = keyChainConnection.getService().getGrants(alias);
                final PackageManager pm = mInjector.getPackageManager(caller.getUserId());

                for (final int uid : granteeUids) {
                    final String[] packages = pm.getPackagesForUid(uid);
                    if (packages == null) {
                        Slogf.wtf(LOG_TAG, "No packages found for uid " + uid);
                        continue;
                    }
                    result.put(uid, new ArraySet<String>(packages));
                }
            } catch (RemoteException e) {
                Slogf.e(LOG_TAG, "Querying keypair grants", e);
            } catch (InterruptedException e) {
                Slogf.w(LOG_TAG, "Interrupted while querying keypair grants", e);
                Thread.currentThread().interrupt();
            }
        });
        return new ParcelableGranteeMap(result);
    }

    @VisibleForTesting
    public static int[] translateIdAttestationFlags(
            int idAttestationFlags) {
        Map<Integer, Integer> idTypeToAttestationFlag = new HashMap();
        idTypeToAttestationFlag.put(ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_SERIAL);
        idTypeToAttestationFlag.put(ID_TYPE_IMEI, AttestationUtils.ID_TYPE_IMEI);
        idTypeToAttestationFlag.put(ID_TYPE_MEID, AttestationUtils.ID_TYPE_MEID);
        idTypeToAttestationFlag.put(
                ID_TYPE_INDIVIDUAL_ATTESTATION, USE_INDIVIDUAL_ATTESTATION);

        int numFlagsSet = Integer.bitCount(idAttestationFlags);
        // No flags are set - return null to indicate no device ID attestation information should
        // be included in the attestation record.
        if (numFlagsSet == 0) {
            return null;
        }

        // If the ID_TYPE_BASE_INFO is set, make sure that a non-null array is returned, even if
        // no other flag is set. That will lead to inclusion of general device make data in the
        // attestation record, but no specific device identifiers.
        if ((idAttestationFlags & ID_TYPE_BASE_INFO) != 0) {
            numFlagsSet -= 1;
            idAttestationFlags = idAttestationFlags & (~ID_TYPE_BASE_INFO);
        }

        int[] attestationUtilsFlags = new int[numFlagsSet];
        int i = 0;
        for (Integer idType: idTypeToAttestationFlag.keySet()) {
            if ((idType & idAttestationFlags) != 0) {
                attestationUtilsFlags[i++] = idTypeToAttestationFlag.get(idType);
            }
        }

        return attestationUtilsFlags;
    }

    @Override
    public boolean generateKeyPair(ComponentName who, String callerPackage, String algorithm,
            ParcelableKeyGenParameterSpec parcelableKeySpec, int idAttestationFlags,
            KeymasterCertificateChain attestationChain) {
        // Get attestation flags, if any.
        final int[] attestationUtilsFlags = translateIdAttestationFlags(idAttestationFlags);
        final boolean deviceIdAttestationRequired = attestationUtilsFlags != null;
        KeyGenParameterSpec keySpec = parcelableKeySpec.getSpec();
        final String alias = keySpec.getKeystoreAlias();
        Preconditions.checkStringNotEmpty(alias, "Empty alias provided");
        Preconditions.checkArgument(
                !deviceIdAttestationRequired || keySpec.getAttestationChallenge() != null,
                "Requested Device ID attestation but challenge is empty");

        final CallerIdentity caller = getCallerIdentity(who, callerPackage);
        final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL);
        final boolean isCredentialManagementApp = isCredentialManagementApp(caller);
        if (deviceIdAttestationRequired && attestationUtilsFlags.length > 0) {
            Preconditions.checkCallAuthorization(hasDeviceIdAccessUnchecked(
                    caller.getPackageName(), caller.getUid()));
            enforceIndividualAttestationSupportedIfRequested(attestationUtilsFlags);
        } else {
            if (isPermissionCheckFlagEnabled()) {
                Preconditions.checkCallAuthorization(
                        hasPermission(MANAGE_DEVICE_POLICY_CERTIFICATES,
                                caller.getPackageName(), caller.getUserId())
                                || isCredentialManagementApp);
            }  else {
                Preconditions.checkCallAuthorization((caller.hasAdminComponent() && (isProfileOwner(
                        caller) || isDefaultDeviceOwner(caller))) || (caller.hasPackage() && (
                        isCallerDelegate || isCredentialManagementApp)));
            }
            if (isCredentialManagementApp) {
                Preconditions.checkCallAuthorization(
                        isAliasInCredentialManagementAppPolicy(caller, alias),
                        CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG);
            }
        }

        if (TextUtils.isEmpty(alias)) {
            throw new IllegalArgumentException("Empty alias provided.");
        }
        // As the caller will be granted access to the key, ensure no UID was specified, as
        // it will not have the desired effect.
        if (keySpec.getUid() != KeyProperties.UID_SELF) {
            Slogf.e(LOG_TAG, "Only the caller can be granted access to the generated keypair.");
            logGenerateKeyPairFailure(caller, isCredentialManagementApp);
            return false;
        }

        if (deviceIdAttestationRequired) {
            if (keySpec.getAttestationChallenge() == null) {
                throw new IllegalArgumentException(
                        "Requested Device ID attestation but challenge is empty.");
            }
            KeyGenParameterSpec.Builder specBuilder = new KeyGenParameterSpec.Builder(keySpec);
            specBuilder.setAttestationIds(attestationUtilsFlags);
            specBuilder.setDevicePropertiesAttestationIncluded(true);
            keySpec = specBuilder.build();
        }

        final long id = mInjector.binderClearCallingIdentity();
        try {
            try (KeyChainConnection keyChainConnection =
                    KeyChain.bindAsUser(mContext, caller.getUserHandle())) {
                IKeyChainService keyChain = keyChainConnection.getService();

                final int generationResult = keyChain.generateKeyPair(algorithm,
                        new ParcelableKeyGenParameterSpec(keySpec));
                if (generationResult != KeyChain.KEY_GEN_SUCCESS) {
                    Slogf.e(LOG_TAG, "KeyChain failed to generate a keypair, error %d.",
                            generationResult);
                    logGenerateKeyPairFailure(caller, isCredentialManagementApp);
                    switch (generationResult) {
                        case KeyChain.KEY_GEN_STRONGBOX_UNAVAILABLE:
                            throw new ServiceSpecificException(
                                    DevicePolicyManager.KEY_GEN_STRONGBOX_UNAVAILABLE,
                                    String.format("KeyChain error: %d", generationResult));
                        case KeyChain.KEY_ATTESTATION_CANNOT_ATTEST_IDS:
                            throw new UnsupportedOperationException(
                                "Device does not support Device ID attestation.");
                        default:
                            return false;
                    }
                }

                // Set a grant for the caller here so that when the client calls
                // requestPrivateKey, it will be able to get the key from Keystore.
                // Note the use of the calling  UID, since the request for the private
                // key will come from the client's process, so the grant has to be for
                // that UID.
                keyChain.setGrant(caller.getUid(), alias, true);

                try {
                    final List<byte[]> encodedCerts = new ArrayList();
                    final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
                    final byte[] certChainBytes = keyChain.getCaCertificates(alias);
                    encodedCerts.add(keyChain.getCertificate(alias));
                    if (certChainBytes != null) {
                        final Collection<X509Certificate> certs =
                                (Collection<X509Certificate>) certFactory.generateCertificates(
                                    new ByteArrayInputStream(certChainBytes));
                        for (X509Certificate cert : certs) {
                            encodedCerts.add(cert.getEncoded());
                        }
                    }

                    attestationChain.shallowCopyFrom(new KeymasterCertificateChain(encodedCerts));
                } catch (CertificateException e) {
                    logGenerateKeyPairFailure(caller, isCredentialManagementApp);
                    Slogf.e(LOG_TAG, "While retrieving certificate chain.", e);
                    return false;
                }

                DevicePolicyEventLogger
                        .createEvent(DevicePolicyEnums.GENERATE_KEY_PAIR)
                        .setAdmin(caller.getPackageName())
                        .setBoolean(/* isDelegate */ isCallerDelegate)
                        .setInt(idAttestationFlags)
                        .setStrings(algorithm, isCredentialManagementApp
                                ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP)
                        .write();
                return true;
            }
        } catch (RemoteException e) {
            Slogf.e(LOG_TAG, "KeyChain error while generating a keypair", e);
        } catch (InterruptedException e) {
            Slogf.w(LOG_TAG, "Interrupted while generating keypair", e);
            Thread.currentThread().interrupt();
        } finally {
            mInjector.binderRestoreCallingIdentity(id);
        }
        logGenerateKeyPairFailure(caller, isCredentialManagementApp);
        return false;
    }

    private void logGenerateKeyPairFailure(CallerIdentity caller,
            boolean isCredentialManagementApp) {
        if (!isCredentialManagementApp) {
            return;
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.CREDENTIAL_MANAGEMENT_APP_GENERATE_KEY_PAIR_FAILED)
                .setStrings(caller.getPackageName())
                .write();
    }

    private void enforceIndividualAttestationSupportedIfRequested(int[] attestationUtilsFlags) {
        for (int attestationFlag : attestationUtilsFlags) {
            if (attestationFlag == USE_INDIVIDUAL_ATTESTATION
                    && !mInjector.getPackageManager().hasSystemFeature(
                    PackageManager.FEATURE_DEVICE_UNIQUE_ATTESTATION)) {
                throw new UnsupportedOperationException("Device Individual attestation is not "
                        + "supported on this device.");
            }
        }
    }

    @Override
    public boolean setKeyPairCertificate(ComponentName who, String callerPackage, String alias,
            byte[] cert, byte[] chain, boolean isUserSelectable) {
        final CallerIdentity caller = getCallerIdentity(who, callerPackage);
        final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL);
        final boolean isCredentialManagementApp = isCredentialManagementApp(caller);
        if (isPermissionCheckFlagEnabled()) {
            Preconditions.checkCallAuthorization(
                    hasPermission(MANAGE_DEVICE_POLICY_CERTIFICATES,
                            caller.getPackageName(), caller.getUserId())
                            || isCredentialManagementApp);
        } else {
            Preconditions.checkCallAuthorization((caller.hasAdminComponent()
                    && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
                    || (caller.hasPackage() && (isCallerDelegate || isCredentialManagementApp)));
        }
        if (isCredentialManagementApp) {
            Preconditions.checkCallAuthorization(
                    isAliasInCredentialManagementAppPolicy(caller, alias),
                    CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG);
        }

        final long id = mInjector.binderClearCallingIdentity();
        try (final KeyChainConnection keyChainConnection =
                KeyChain.bindAsUser(mContext, caller.getUserHandle())) {
            IKeyChainService keyChain = keyChainConnection.getService();
            if (!keyChain.setKeyPairCertificate(alias, cert, chain)) {
                return false;
            }
            keyChain.setUserSelectable(alias, isUserSelectable);
            DevicePolicyEventLogger
                    .createEvent(DevicePolicyEnums.SET_KEY_PAIR_CERTIFICATE)
                    .setAdmin(caller.getPackageName())
                    .setBoolean(/* isDelegate */ isCallerDelegate)
                    .setStrings(isCredentialManagementApp
                            ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP)
                    .write();
            return true;
        } catch (InterruptedException e) {
            Slogf.w(LOG_TAG, "Interrupted while setting keypair certificate", e);
            Thread.currentThread().interrupt();
        } catch (RemoteException e) {
            Slogf.e(LOG_TAG, "Failed setting keypair certificate", e);
        } finally {
            mInjector.binderRestoreCallingIdentity(id);
        }
        return false;
    }

    @Override
    public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
            final IBinder response) {
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(isSystemUid(caller),
                String.format(NOT_SYSTEM_CALLER_MSG, "choose private key alias"));

        // If there is a profile owner, redirect to that; otherwise query the device owner.
        ComponentName aliasChooser = getProfileOwnerAsUser(caller.getUserId());
        if (aliasChooser == null && caller.getUserHandle().isSystem()) {
            synchronized (getLockObject()) {
                final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
                if (deviceOwnerAdmin != null) {
                    aliasChooser = deviceOwnerAdmin.info.getComponent();
                }
            }
        }
        if (aliasChooser == null) {
            sendPrivateKeyAliasResponse(null, response);
            return;
        }

        Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);

        final ComponentName delegateReceiver;
        delegateReceiver = resolveDelegateReceiver(DELEGATION_CERT_SELECTION,
                DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS, caller.getUserId());

        final boolean isDelegate;
        if (delegateReceiver != null) {
            intent.setComponent(delegateReceiver);
            isDelegate = true;
        } else {
            intent.setComponent(aliasChooser);
            isDelegate = false;
        }

        mInjector.binderWithCleanCallingIdentity(() -> {
            mContext.sendOrderedBroadcastAsUser(intent, caller.getUserHandle(), null,
                    new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    final String chosenAlias = getResultData();
                    sendPrivateKeyAliasResponse(chosenAlias, response);
                }
            }, null, Activity.RESULT_OK, null, null);
            DevicePolicyEventLogger
                    .createEvent(DevicePolicyEnums.CHOOSE_PRIVATE_KEY_ALIAS)
                    .setAdmin(intent.getComponent())
                    .setBoolean(isDelegate)
                    .write();
        });
    }

    private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
        final IKeyChainAliasCallback keyChainAliasResponse =
                IKeyChainAliasCallback.Stub.asInterface(responseBinder);
        // Send the response. It's OK to do this from the main thread because IKeyChainAliasCallback
        // is oneway, which means it won't block if the recipient lives in another process.
        try {
            keyChainAliasResponse.alias(alias);
        } catch (Exception e) {
            // Caller could throw RuntimeException or RemoteException back across processes. Catch
            // everything just to be sure.
            Slogf.e(LOG_TAG, "error while responding to callback", e);
        }
    }

    /**
     * Determine whether DPMS should check if a delegate package is already installed before
     * granting it new delegations via {@link #setDelegatedScopes}.
     */
    private static boolean shouldCheckIfDelegatePackageIsInstalled(String delegatePackage,
            int targetSdk, List<String> scopes) {
        // 1) Never skip is installed check from N.
        if (targetSdk >= Build.VERSION_CODES.N) {
            return true;
        }
        // 2) Skip if DELEGATION_CERT_INSTALL is the only scope being given.
        if (scopes.size() == 1 && scopes.get(0).equals(DELEGATION_CERT_INSTALL)) {
            return false;
        }
        // 3) Skip if all previously granted scopes are being cleared.
        if (scopes.isEmpty()) {
            return false;
        }
        // Otherwise it should check that delegatePackage is installed.
        return true;
    }

    /**
     * Set the scopes of a device owner or profile owner delegate.
     *
     * @param who the device owner or profile owner.
     * @param delegatePackage the name of the delegate package.
     * @param scopeList the list of delegation scopes to be given to the delegate package.
     */
    @Override
    public void setDelegatedScopes(ComponentName who, String delegatePackage,
            List<String> scopeList) throws SecurityException {
        Objects.requireNonNull(who, "ComponentName is null");
        Preconditions.checkStringNotEmpty(delegatePackage, "Delegate package is null or empty");
        Preconditions.checkCollectionElementsNotNull(scopeList, "Scopes");
        final CallerIdentity caller = getCallerIdentity(who);

        // Remove possible duplicates.
        final ArrayList<String> scopes = new ArrayList(new ArraySet(scopeList));
        // Ensure given scopes are valid.
        if (scopes.retainAll(Arrays.asList(DELEGATIONS))) {
            throw new IllegalArgumentException("Unexpected delegation scopes");
        }
        // Retrieve the user ID of the calling process.
        final int userId = caller.getUserId();
        // Ensure calling process is device/profile owner.
        if (!Collections.disjoint(scopes, DEVICE_OWNER_OR_MANAGED_PROFILE_OWNER_DELEGATIONS)) {
            Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
                    || (isProfileOwner(caller) && isManagedProfile(caller.getUserId())));
        } else if (!Collections.disjoint(
                scopes, DEVICE_OWNER_OR_ORGANIZATION_OWNED_MANAGED_PROFILE_OWNER_DELEGATIONS)) {
            Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
                    || isProfileOwnerOfOrganizationOwnedDevice(caller));
        } else {
            Preconditions.checkCallAuthorization(
                    isDefaultDeviceOwner(caller) || isProfileOwner(caller));
        }

        synchronized (getLockObject()) {
            // Ensure the delegate is installed (skip this for DELEGATION_CERT_INSTALL in pre-N).
            if (shouldCheckIfDelegatePackageIsInstalled(delegatePackage,
                        getTargetSdk(who.getPackageName(), userId), scopes)) {
                // Throw when the delegate package is not installed.
                if (!isPackageInstalledForUser(delegatePackage, userId)) {
                    throw new IllegalArgumentException("Package " + delegatePackage
                            + " is not installed on the current user");
                }
            }

            // Set the new delegate in user policies.
            final DevicePolicyData policy = getUserData(userId);
            List<String> exclusiveScopes = null;
            if (!scopes.isEmpty()) {
                policy.mDelegationMap.put(delegatePackage, new ArrayList<>(scopes));
                exclusiveScopes = new ArrayList<>(scopes);
                exclusiveScopes.retainAll(EXCLUSIVE_DELEGATIONS);
            } else {
                // Remove any delegation info if the given scopes list is empty.
                policy.mDelegationMap.remove(delegatePackage);
            }
            sendDelegationChangedBroadcast(delegatePackage, scopes, userId);

            // If set, remove exclusive scopes from all other delegates
            if (exclusiveScopes != null && !exclusiveScopes.isEmpty()) {
                for (int i = policy.mDelegationMap.size() - 1; i >= 0; --i) {
                    final String currentPackage = policy.mDelegationMap.keyAt(i);
                    final List<String> currentScopes = policy.mDelegationMap.valueAt(i);

                    if (!currentPackage.equals(delegatePackage)) {
                        // Iterate through all other delegates
                        if (currentScopes.removeAll(exclusiveScopes)) {
                            // And if this delegate had some exclusive scopes which are now moved
                            // to the new delegate, notify about its delegation changes.
                            if (currentScopes.isEmpty()) {
                                policy.mDelegationMap.removeAt(i);
                            }
                            sendDelegationChangedBroadcast(currentPackage,
                                    new ArrayList<>(currentScopes), userId);
                        }
                    }
                }
            }
            // Persist updates.
            saveSettingsLocked(userId);
        }
    }

    private void sendDelegationChangedBroadcast(String delegatePackage, ArrayList<String> scopes,
            int userId) {
        // Notify delegate package of updates.
        final Intent intent = new Intent(
                DevicePolicyManager.ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED);
        // Only call receivers registered with Context#registerReceiver (don’t wake delegate).
        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
        // Limit components this intent resolves to to the delegate package.
        intent.setPackage(delegatePackage);
        // Include the list of delegated scopes as an extra.
        intent.putStringArrayListExtra(DevicePolicyManager.EXTRA_DELEGATION_SCOPES, scopes);
        // Send the broadcast.
        mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
    }

    /**
     * Get the delegation scopes given to a delegate package by a device owner or profile owner.
     *
     * A DO/PO can get the scopes of any package. A non DO/PO package can get its own scopes by
     * passing in {@code null} as the {@code who} parameter and its own name as the
     * {@code delegatepackage}.
     *
     * @param who the device owner or profile owner, or {@code null} if the caller is
     *            {@code delegatePackage}.
     * @param delegatePackage the name of the delegate package whose scopes are to be retrieved.
     * @return a list of the delegation scopes currently given to {@code delegatePackage}.
     */
    @Override
    @NonNull
    public List<String> getDelegatedScopes(ComponentName who,
            String delegatePackage) throws SecurityException {
        Objects.requireNonNull(delegatePackage, "Delegate package is null");
        final CallerIdentity caller = getCallerIdentity(who);

        // Ensure the caller may call this method:
        // * Either it's a profile owner / device owner, if componentName is provided
        // * Or it's an app querying its own delegation scopes
        if (caller.hasAdminComponent()) {
            Preconditions.checkCallAuthorization(
                    isProfileOwner(caller) || isDefaultDeviceOwner(caller));
        } else {
            Preconditions.checkCallAuthorization(isPackage(caller, delegatePackage),
                    String.format("Caller with uid %d is not %s", caller.getUid(),
                            delegatePackage));
        }
        synchronized (getLockObject()) {
            final DevicePolicyData policy = getUserData(caller.getUserId());
            // Retrieve the scopes assigned to delegatePackage, or null if no scope was given.
            final List<String> scopes = policy.mDelegationMap.get(delegatePackage);
            return scopes == null ? Collections.EMPTY_LIST : scopes;
        }
    }

    /**
     * Get a list of  packages that were given a specific delegation scopes by a device owner or
     * profile owner.
     *
     * @param who the device owner or profile owner.
     * @param scope the scope whose delegates are to be retrieved.
     * @return a list of the delegate packages currently given the {@code scope} delegation.
     */
    @NonNull
    public List<String> getDelegatePackages(ComponentName who, String scope)
            throws SecurityException {
        Objects.requireNonNull(who, "ComponentName is null");
        Objects.requireNonNull(scope, "Scope is null");
        if (!Arrays.asList(DELEGATIONS).contains(scope)) {
            throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
        }

        // Retrieve the user ID of the calling process.
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || isProfileOwner(caller));
        synchronized (getLockObject()) {
            return getDelegatePackagesInternalLocked(scope, caller.getUserId());
        }
    }

    private List<String> getDelegatePackagesInternalLocked(String scope, int userId) {
        final DevicePolicyData policy = getUserData(userId);

        // Create a list to hold the resulting delegate packages.
        final List<String> delegatePackagesWithScope = new ArrayList<>();
        // Add all delegations containing scope to the result list.
        for (int i = 0; i < policy.mDelegationMap.size(); i++) {
            if (policy.mDelegationMap.valueAt(i).contains(scope)) {
                delegatePackagesWithScope.add(policy.mDelegationMap.keyAt(i));
            }
        }
        return delegatePackagesWithScope;
    }

    /**
     * Return the ComponentName of the receiver that handles the given broadcast action, from
     * the app that holds the given delegation capability. If the app defines multiple receivers
     * with the same intent action filter, will return any one of them nondeterministically.
     *
     * @return ComponentName of the receiver or {@null} if none exists.
     */
    private ComponentName resolveDelegateReceiver(String scope, String action, int userId) {

        final List<String> delegates;
        synchronized (getLockObject()) {
            delegates = getDelegatePackagesInternalLocked(scope, userId);
        }
        if (delegates.size() == 0) {
            return null;
        } else if (delegates.size() > 1) {
            Slogf.wtf(LOG_TAG, "More than one delegate holds " + scope);
            return null;
        }
        final String pkg = delegates.get(0);
        Intent intent = new Intent(action);
        intent.setPackage(pkg);
        final List<ResolveInfo> receivers;
        try {
            receivers = mIPackageManager.queryIntentReceivers(
                    intent, null, 0, userId).getList();
        } catch (RemoteException e) {
            return null;
        }
        final int count = receivers.size();
        if (count >= 1) {
            if (count > 1) {
                Slogf.w(LOG_TAG, pkg + " defines more than one delegate receiver for " + action);
            }
            return receivers.get(0).activityInfo.getComponentName();
        } else {
            return null;
        }
    }

    /**
     * Check whether a caller application has been delegated a given scope via
     * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or
     * device owner.
     * <p>
     * This is done by checking that {@code callerPackage} was granted {@code scope} delegation and
     * then comparing the calling UID with the UID of {@code callerPackage} as reported by
     * {@link PackageManager#getPackageUidAsUser}.
     *
     * @param callerPackage the name of the package that is trying to invoke a function in the DPMS.
     * @param scope the delegation scope to be checked.
     * @return {@code true} if the calling process is a delegate of {@code scope}.
     */
    private boolean isCallerDelegate(String callerPackage, int callerUid, String scope) {
        Objects.requireNonNull(callerPackage, "callerPackage is null");
        if (!Arrays.asList(DELEGATIONS).contains(scope)) {
            throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
        }

        // Retrieve the UID and user ID of the calling process.
        final int userId = UserHandle.getUserId(callerUid);
        synchronized (getLockObject()) {
            // Retrieve user policy data.
            final DevicePolicyData policy = getUserData(userId);
            // Retrieve the list of delegation scopes granted to callerPackage.
            final List<String> scopes = policy.mDelegationMap.get(callerPackage);
            // Check callingUid only if callerPackage has the required scope delegation.
            if (scopes != null && scopes.contains(scope)) {
                // Return true if the caller is actually callerPackage.
                return isCallingFromPackage(callerPackage, callerUid);
            }
            return false;
        }
    }

    /**
     * Check whether a caller application has been delegated a given scope via
     * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or
     * device owner.
     * <p>
     * This is done by checking that the calling package was granted {@code scope} delegation and
     * then comparing the calling UID with the UID of the calling package as reported by
     * {@link PackageManager#getPackageUidAsUser}.
     *
     * @param caller the calling identity
     * @param scope the delegation scope to be checked.
     * @return {@code true} if the calling process is a delegate of {@code scope}.
     */
    private boolean isCallerDelegate(CallerIdentity caller, String scope) {
        if (caller.getPackageName() == null) {
            return false;
        }
        Preconditions.checkArgument(Arrays.asList(DELEGATIONS).contains(scope),
                "Unexpected delegation scope: %s", scope);

        synchronized (getLockObject()) {
            // Retrieve user policy data.
            final DevicePolicyData policy = getUserData(caller.getUserId());
            // Retrieve the list of delegation scopes granted to callerPackage.
            final List<String> scopes = policy.mDelegationMap.get(caller.getPackageName());
            // Check callingUid only if callerPackage has the required scope delegation.
            return scopes != null && scopes.contains(scope);
        }
    }

    /**
     * Check whether a caller application has been delegated any scope via
     * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or
     * device owner.
     * <p>
     * This is done by checking that the calling package was granted any scope delegations and
     * then comparing the calling UID with the UID of the calling package as reported by
     * {@link PackageManager#getPackageUidAsUser}.
     *
     * @param caller the calling identity
     * @return {@code true} if the calling process is a delegate of any scope.
     */
    private boolean isCallerDelegate(CallerIdentity caller) {
        Objects.requireNonNull(caller.getPackageName(), "callerPackage is null");

        synchronized (getLockObject()) {
            // Retrieve user policy data.
            final DevicePolicyData policy = getUserData(caller.getUserId());
            // Retrieve the list of delegation scopes granted to callerPackage.
            final List<String> scopes = policy.mDelegationMap.get(caller.getPackageName());
            // Check callingUid only if callerPackage has the required scope delegation.
            return scopes != null;
        }
    }

    /**
     * Helper function to preserve delegation behavior pre-O when using the deprecated functions
     * {@code #setCertInstallerPackage} and {@code #setApplicationRestrictionsManagingPackage}.
     */
    private void setDelegatedScopePreO(ComponentName who,
            String delegatePackage, String scope) {
        Objects.requireNonNull(who, "ComponentName is null");

        final CallerIdentity caller = getCallerIdentity(who);
        // Ensure calling process is device/profile owner.
        Preconditions.checkCallAuthorization(
                isProfileOwner(caller) || isDefaultDeviceOwner(caller));

        synchronized (getLockObject()) {
            final DevicePolicyData policy = getUserData(caller.getUserId());

            if (delegatePackage != null) {
                // Set package as a delegate for scope if it is not already one.
                List<String> scopes = policy.mDelegationMap.get(delegatePackage);
                if (scopes == null) {
                    scopes = new ArrayList<>();
                }
                if (!scopes.contains(scope)) {
                    scopes.add(scope);
                    setDelegatedScopes(who, delegatePackage, scopes);
                }
            }

            // Clear any existing scope delegates.
            for (int i = 0; i < policy.mDelegationMap.size(); i++) {
                final String currentPackage = policy.mDelegationMap.keyAt(i);
                final List<String> currentScopes = policy.mDelegationMap.valueAt(i);

                if (!currentPackage.equals(delegatePackage) && currentScopes.contains(scope)) {
                    final List<String> newScopes = new ArrayList(currentScopes);
                    newScopes.remove(scope);
                    setDelegatedScopes(who, currentPackage, newScopes);
                }
            }
        }
    }

    /**
     * Check whether a caller application is the credential management app, which can access
     * privileged APIs.
     * <p>
     * This is done by checking that the calling package is authorized to perform the app operation
     * {@link android.app.AppOpsManager#OP_MANAGE_CREDENTIALS}.
     *
     * @param caller the calling identity
     * @return {@code true} if the calling process is the credential management app.
     */
    private boolean isCredentialManagementApp(CallerIdentity caller) {
        return mInjector.binderWithCleanCallingIdentity(() -> {
            AppOpsManager appOpsManager = mInjector.getAppOpsManager();
            if (appOpsManager == null) return false;
            return appOpsManager.noteOpNoThrow(AppOpsManager.OP_MANAGE_CREDENTIALS, caller.getUid(),
                    caller.getPackageName(), null, null) == AppOpsManager.MODE_ALLOWED;
        });
    }

    /**
     * If the caller is the credential management app, the alias provided must be contained
     * in the aliases specified in the credential management app's authentication policy.
     */
    private boolean isAliasInCredentialManagementAppPolicy(CallerIdentity caller, String alias) {
        return mInjector.binderWithCleanCallingIdentity(() -> {
            try (KeyChainConnection connection = KeyChain.bindAsUser(mContext,
                    caller.getUserHandle())) {
                // The policy will be null if there is no credential management app
                AppUriAuthenticationPolicy policy =
                        connection.getService().getCredentialManagementAppPolicy();
                return policy != null && !policy.getAppAndUriMappings().isEmpty()
                        && containsAlias(policy, alias);
            } catch (RemoteException | InterruptedException e) {
                return false;
            }
        });
    }

    private static boolean containsAlias(AppUriAuthenticationPolicy policy, String alias) {
        for (Map.Entry<String, Map<Uri, String>> appsToUris :
                policy.getAppAndUriMappings().entrySet()) {
            for (Map.Entry<Uri, String> urisToAliases : appsToUris.getValue().entrySet()) {
                if (urisToAliases.getValue().equals(alias)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void setCertInstallerPackage(ComponentName who, String installerPackage)
            throws SecurityException {
        setDelegatedScopePreO(who, installerPackage, DELEGATION_CERT_INSTALL);
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_CERT_INSTALLER_PACKAGE)
                .setAdmin(who)
                .setStrings(installerPackage)
                .write();
    }

    @Override
    public String getCertInstallerPackage(ComponentName who) throws SecurityException {
        final List<String> delegatePackages = getDelegatePackages(who, DELEGATION_CERT_INSTALL);
        return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
    }

    /**
     * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
     * not installed and therefore not available.
     *
     * @throws SecurityException if the caller is not a profile or device owner.
     * @throws UnsupportedOperationException if the package does not support being set as always-on.
     */
    @Override
    public boolean setAlwaysOnVpnPackage(ComponentName who, String vpnPackage, boolean lockdown,
            List<String> lockdownAllowlist)
            throws SecurityException {
        Objects.requireNonNull(who, "ComponentName is null");

        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || isProfileOwner(caller));
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_ALWAYS_ON_VPN_PACKAGE);

        if (vpnPackage == null) {
            final String prevVpnPackage;
            synchronized (getLockObject()) {
                prevVpnPackage = getProfileOwnerOrDeviceOwnerLocked(
                        caller.getUserId()).mAlwaysOnVpnPackage;
                // If the admin is clearing VPN package but hasn't configure any VPN previously,
                // ignore it so that it doesn't interfere with user-configured VPNs.
                if (TextUtils.isEmpty(prevVpnPackage)) {
                    return true;
                }
            }
            revokeVpnAuthorizationForPackage(prevVpnPackage, caller.getUserId());
        }

        final int userId = caller.getUserId();
        mInjector.binderWithCleanCallingIdentity(() -> {
            if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
                Slogf.w(LOG_TAG, "Non-existent VPN package specified: " + vpnPackage);
                throw new ServiceSpecificException(
                        DevicePolicyManager.ERROR_VPN_PACKAGE_NOT_FOUND, vpnPackage);
            }

            if (vpnPackage != null && lockdown && lockdownAllowlist != null) {
                for (String packageName : lockdownAllowlist) {
                    if (!isPackageInstalledForUser(packageName, userId)) {
                        Slogf.w(LOG_TAG, "Non-existent package in VPN allowlist: " + packageName);
                        throw new ServiceSpecificException(
                                DevicePolicyManager.ERROR_VPN_PACKAGE_NOT_FOUND, packageName);
                    }
                }
            }
            // If some package is uninstalled after the check above, it will be ignored by CM.
            if (!mInjector.getVpnManager().setAlwaysOnVpnPackageForUser(
                    userId, vpnPackage, lockdown, lockdownAllowlist)) {
                throw new UnsupportedOperationException();
            }
        });
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_ALWAYS_ON_VPN_PACKAGE)
                .setAdmin(caller.getComponentName())
                .setStrings(vpnPackage)
                .setBoolean(lockdown)
                .setInt(lockdownAllowlist != null ? lockdownAllowlist.size() : 0)
                .write();
        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
            if (!TextUtils.equals(vpnPackage, admin.mAlwaysOnVpnPackage)
                    || lockdown != admin.mAlwaysOnVpnLockdown) {
                admin.mAlwaysOnVpnPackage = vpnPackage;
                admin.mAlwaysOnVpnLockdown = lockdown;
                saveSettingsLocked(userId);
            }
        }
        return true;
    }

    private void revokeVpnAuthorizationForPackage(String vpnPackage, int userId) {
        mInjector.binderWithCleanCallingIdentity(() -> {
            try {
                final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
                        vpnPackage, /* flags= */ 0, userId);
                if (ai == null) {
                    Slogf.w(LOG_TAG, "Non-existent VPN package: " + vpnPackage);
                } else {
                    mInjector.getAppOpsManager().setMode(AppOpsManager.OP_ACTIVATE_VPN,
                            ai.uid, vpnPackage, MODE_DEFAULT);
                }
            } catch (RemoteException e) {
                Slogf.e(LOG_TAG, "Can't talk to package managed", e);
            }
        });
    }

    @Override
    public String getAlwaysOnVpnPackage(ComponentName admin) throws SecurityException {
        Objects.requireNonNull(admin, "ComponentName is null");

        final CallerIdentity caller = getCallerIdentity(admin);
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || isProfileOwner(caller));

        return mInjector.binderWithCleanCallingIdentity(
                () -> mInjector.getVpnManager().getAlwaysOnVpnPackageForUser(caller.getUserId()));
    }

    @Override
    public String getAlwaysOnVpnPackageForUser(int userHandle) {
        Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
                String.format(NOT_SYSTEM_CALLER_MSG, "call getAlwaysOnVpnPackageForUser"));
        synchronized (getLockObject()) {
            ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userHandle);
            return admin != null ? admin.mAlwaysOnVpnPackage : null;
        }
    }

    @Override
    public boolean isAlwaysOnVpnLockdownEnabled(ComponentName admin) throws SecurityException {
        final CallerIdentity caller;
        if (hasCallingPermission(PERMISSION_MAINLINE_NETWORK_STACK)) {
            // TODO: CaptivePortalLoginActivity erroneously calls this method with a non-admin
            // ComponentName, so we have to use a separate code path for it:
            // getCallerIdentity(admin) will throw if the admin is not in the known admin list.
            caller = getCallerIdentity();
        } else {
            caller = getCallerIdentity(admin);
            Preconditions.checkCallAuthorization(
                    isDefaultDeviceOwner(caller) || isProfileOwner(caller));
        }

        return mInjector.binderWithCleanCallingIdentity(
                () -> mInjector.getVpnManager().isVpnLockdownEnabled(caller.getUserId()));
    }

    @Override
    public boolean isAlwaysOnVpnLockdownEnabledForUser(int userHandle) {
        Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
                String.format(NOT_SYSTEM_CALLER_MSG, "call isAlwaysOnVpnLockdownEnabledForUser"));
        synchronized (getLockObject()) {
            ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userHandle);
            return admin != null && admin.mAlwaysOnVpnLockdown;
        }
    }

    @Override
    public List<String> getAlwaysOnVpnLockdownAllowlist(ComponentName admin)
            throws SecurityException {
        Objects.requireNonNull(admin, "ComponentName is null");

        final CallerIdentity caller = getCallerIdentity(admin);
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || isProfileOwner(caller));

        return mInjector.binderWithCleanCallingIdentity(
                () -> mInjector.getVpnManager().getVpnLockdownAllowlist(caller.getUserId()));
    }

    private void forceWipeDeviceNoLock(boolean wipeExtRequested, String reason, boolean wipeEuicc,
            boolean wipeResetProtectionData) {
        wtfIfInLock();
        boolean success = false;

        try {
            boolean delayed = !mInjector.recoverySystemRebootWipeUserData(
                    /* shutdown= */ false, reason, /* force= */ true, /* wipeEuicc= */ wipeEuicc,
                    wipeExtRequested, wipeResetProtectionData);
            if (delayed) {
                // Persist the request so the device is automatically factory-reset on next start if
                // the system crashes or reboots before the {@code DevicePolicySafetyChecker} calls
                // its callback.
                Slogf.i(LOG_TAG, "Persisting factory reset request as it could be delayed by %s",
                        mSafetyChecker);
                synchronized (getLockObject()) {
                    DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
                    policy.setDelayedFactoryReset(reason, wipeExtRequested, wipeEuicc,
                            wipeResetProtectionData);
                    saveSettingsLocked(UserHandle.USER_SYSTEM);
                }
            }
            success = true;
        } catch (IOException | SecurityException e) {
            Slogf.w(LOG_TAG, "Failed requesting data wipe", e);
        } finally {
            if (!success) SecurityLog.writeEvent(SecurityLog.TAG_WIPE_FAILURE);
        }
    }

    private void factoryResetIfDelayedEarlier() {
        synchronized (getLockObject()) {
            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);

            if (policy.mFactoryResetFlags == 0) return;

            if (policy.mFactoryResetReason == null) {
                // Shouldn't happen.
                Slogf.e(LOG_TAG, "no persisted reason for factory resetting");
                policy.mFactoryResetReason = "requested before boot";
            }
            FactoryResetter factoryResetter = FactoryResetter.newBuilder(mContext)
                    .setReason(policy.mFactoryResetReason).setForce(true)
                    .setWipeEuicc((policy.mFactoryResetFlags & DevicePolicyData
                            .FACTORY_RESET_FLAG_WIPE_EUICC) != 0)
                    .setWipeAdoptableStorage((policy.mFactoryResetFlags & DevicePolicyData
                            .FACTORY_RESET_FLAG_WIPE_EXTERNAL_STORAGE) != 0)
                    .setWipeFactoryResetProtection((policy.mFactoryResetFlags & DevicePolicyData
                            .FACTORY_RESET_FLAG_WIPE_FACTORY_RESET_PROTECTION) != 0)
                    .build();
            Slogf.i(LOG_TAG, "Factory resetting on boot using " + factoryResetter);
            try {
                if (!factoryResetter.factoryReset()) {
                    // Shouldn't happen because FactoryResetter was created without a
                    // DevicePolicySafetyChecker.
                    Slogf.wtf(LOG_TAG, "Factory reset using " + factoryResetter + " failed.");
                }
            } catch (IOException e) {
                // Shouldn't happen.
                Slogf.wtf(LOG_TAG, "Could not factory reset using " + factoryResetter, e);
            }
        }
    }

    private void forceWipeUser(int userId, String wipeReasonForUser, boolean wipeSilently) {
        boolean success = false;
        try {
            if (getCurrentForegroundUserId() == userId) {
                // TODO: We need to special case headless here as we can't switch to the system user
                mInjector.getIActivityManager().switchUser(UserHandle.USER_SYSTEM);
            }

            success = mUserManagerInternal.removeUserEvenWhenDisallowed(userId);
            if (!success) {
                Slogf.w(LOG_TAG, "Couldn't remove user " + userId);
            } else if (isManagedProfile(userId) && !wipeSilently) {
                sendWipeProfileNotification(wipeReasonForUser,
                        UserHandle.of(getProfileParentId(userId)));
            }
        } catch (RemoteException re) {
            // Shouldn't happen
            Slogf.wtf(LOG_TAG, "Error forcing wipe user", re);
        } finally {
            if (!success) SecurityLog.writeEvent(SecurityLog.TAG_WIPE_FAILURE);
        }
    }

    @Override
    public void wipeDataWithReason(String callerPackageName, int flags,
            @NonNull String wipeReasonForUser, boolean calledOnParentInstance,
            boolean factoryReset) {
        if (!mHasFeature && !hasCallingOrSelfPermission(permission.MASTER_CLEAR)) {
            return;
        }
        CallerIdentity caller = getCallerIdentity(callerPackageName);

        boolean calledByProfileOwnerOnOrgOwnedDevice =
                isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId());
        EnforcingAdmin enforcingAdmin = enforcePermissionsAndGetEnforcingAdmin(
                /*admin=*/ null,
                /*permission=*/ new String[]{MANAGE_DEVICE_POLICY_WIPE_DATA, MASTER_CLEAR},
                USES_POLICY_WIPE_DATA,
                caller.getPackageName(),
                factoryReset ? UserHandle.USER_ALL : getAffectedUser(calledOnParentInstance));
        ActiveAdmin admin = enforcingAdmin.getActiveAdmin();

        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_WIPE_DATA);

        if (TextUtils.isEmpty(wipeReasonForUser)) {
            wipeReasonForUser = getGenericWipeReason(
                    calledByProfileOwnerOnOrgOwnedDevice, calledOnParentInstance);
        }

        int userId = admin != null ? admin.getUserHandle().getIdentifier()
                : caller.getUserId();
        Slogf.i(LOG_TAG, "wipeDataWithReason(%s): admin=%s, user=%d", wipeReasonForUser, admin,
                userId);
        if (calledByProfileOwnerOnOrgOwnedDevice) {
            // When wipeData is called on the parent instance, it implies wiping the entire device.
            if (calledOnParentInstance) {
                userId = UserHandle.USER_SYSTEM;
            } else {
                // when wipeData is _not_ called on the parent instance, it implies relinquishing
                // control over the device, wiping only the work profile. So the user restriction
                // on profile removal needs to be removed first.
                final UserHandle parentUser = UserHandle.of(getProfileParentId(userId));
                mInjector.binderWithCleanCallingIdentity(
                        () -> clearOrgOwnedProfileOwnerUserRestrictions(parentUser));
            }
        }
        DevicePolicyEventLogger event = DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.WIPE_DATA_WITH_REASON)
                .setInt(flags)
                .setStrings(calledOnParentInstance ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT);

        final String adminName;
        final ComponentName adminComp;
        if (admin != null) {
            if (admin.isPermissionBased) {
                adminComp = null;
                adminName = caller.getPackageName();
                event.setAdmin(adminName);
            } else {
                adminComp = admin.info.getComponent();
                adminName = adminComp.flattenToShortString();
                event.setAdmin(adminComp);
            }
        } else {
            adminComp = null;
            adminName = mInjector.getPackageManager().getPackagesForUid(caller.getUid())[0];
            Slogf.i(LOG_TAG, "Logging wipeData() event admin as " + adminName);
            event.setAdmin(adminName);
            if (mInjector.userManagerIsHeadlessSystemUserMode()) {
                // On headless system user mode, the call is meant to factory reset the whole
                // device, otherwise the caller could simply remove the current user.
                userId = UserHandle.USER_SYSTEM;
            }
        }
        event.write();

        String internalReason = String.format(
                "DevicePolicyManager.wipeDataWithReason() from %s, organization-owned? %s",
                adminName, calledByProfileOwnerOnOrgOwnedDevice);

        wipeDataNoLock(adminComp, flags, internalReason, wipeReasonForUser, userId,
                calledOnParentInstance, factoryReset);
    }

    private String getGenericWipeReason(
            boolean calledByProfileOwnerOnOrgOwnedDevice, boolean calledOnParentInstance) {
        return calledByProfileOwnerOnOrgOwnedDevice && !calledOnParentInstance
                ? getUpdatableString(
                        WORK_PROFILE_DELETED_ORG_OWNED_MESSAGE,
                        R.string.device_ownership_relinquished)
                : getUpdatableString(
                        WORK_PROFILE_DELETED_GENERIC_MESSAGE,
                        R.string.work_profile_deleted_description_dpm_wipe);
    }

    /**
     * Clears device wide policies enforced by COPE PO when relinquishing the device. This method
     * should be invoked once the admin is gone, so that all methods that rely on calculating
     * aggregate policy (e.g. strong auth timeout) from all admins aren't affected by its policies.
     * This method assumes that there is no other device or profile owners left on the device.
     * Shouldn't be called from binder thread without clearing identity.
     */
    private void clearOrgOwnedProfileOwnerDeviceWidePolicies(@UserIdInt int parentId) {
        Slogf.i(LOG_TAG, "Cleaning up device-wide policies left over from org-owned profile...");
        // Lockscreen message
        mLockPatternUtils.setDeviceOwnerInfo(null);
        // Wifi config lockdown
        mInjector.settingsGlobalPutInt(Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0);
        // Security logging
        if (mInjector.securityLogGetLoggingEnabledProperty()) {
            mSecurityLogMonitor.stop();
            mInjector.securityLogSetLoggingEnabledProperty(false);
        }
        // Network logging
        setNetworkLoggingActiveInternal(false);

        // System update policy.
        final boolean hasSystemUpdatePolicy;
        synchronized (getLockObject()) {
            hasSystemUpdatePolicy = mOwners.getSystemUpdatePolicy() != null;
            if (hasSystemUpdatePolicy) {
                mOwners.clearSystemUpdatePolicy();
                mOwners.writeDeviceOwner();
            }
        }
        if (hasSystemUpdatePolicy) {
            mContext.sendBroadcastAsUser(
                    new Intent(ACTION_SYSTEM_UPDATE_POLICY_CHANGED), UserHandle.SYSTEM);
        }

        // Unsuspend personal apps if needed.
        suspendPersonalAppsInternal(parentId, getManagedUserId(parentId), false);

        // Notify FRP agent, LSS and WindowManager to ensure they don't hold on to stale policies.
        final int frpAgentUid = getFrpManagementAgentUid();
        if (frpAgentUid > 0) {
            notifyResetProtectionPolicyChanged(frpAgentUid);
        }
        mLockSettingsInternal.refreshStrongAuthTimeout(parentId);

        clearManagedSubscriptionsPolicy();
        clearLauncherShortcutOverrides();
        updateTelephonyCrossProfileIntentFilters(parentId, UserHandle.USER_NULL, false);

        Slogf.i(LOG_TAG, "Cleaning up device-wide policies done.");
    }

    private void clearManagedSubscriptionsPolicy() {
        unregisterOnSubscriptionsChangedListener();

        SubscriptionManager subscriptionManager = mContext.getSystemService(
                SubscriptionManager.class);
        //Iterate over all the subscriptions and remove association with any user.
        int[] subscriptionIds = subscriptionManager.getActiveSubscriptionIdList(false);
        for (int subId : subscriptionIds) {
            subscriptionManager.setSubscriptionUserHandle(subId, null);
        }
    }

    private void clearLauncherShortcutOverrides() {
        mPolicyCache.setLauncherShortcutOverrides(new ArrayMap<>());
    }

    private void updateTelephonyCrossProfileIntentFilters(int parentUserId, int profileUserId,
            boolean enableWorkTelephony) {
        try {
            // This should only occur when managed profile is being removed.
            if (!enableWorkTelephony && profileUserId == UserHandle.USER_NULL) {
                mIPackageManager.clearCrossProfileIntentFilters(parentUserId,
                        mContext.getPackageName());
                return;
            }
            for (DefaultCrossProfileIntentFilter filter :
                    DefaultCrossProfileIntentFiltersUtils
                            .getDefaultCrossProfileTelephonyIntentFilters(!enableWorkTelephony)) {
                if (removeCrossProfileIntentFilter(filter, parentUserId, profileUserId)) {
                    Slogf.w(LOG_TAG,
                            "Failed to remove cross-profile intent filter: "
                                    + filter.filter.getIntentFilter() + ", enableWorkTelephony: "
                                    + enableWorkTelephony);
                }
            }
            for (DefaultCrossProfileIntentFilter filter :
                    DefaultCrossProfileIntentFiltersUtils
                            .getDefaultCrossProfileTelephonyIntentFilters(enableWorkTelephony)) {
                addCrossProfileIntentFilter(filter, parentUserId, profileUserId);
            }
        } catch (RemoteException re) {
            Slogf.wtf(LOG_TAG, "Error updating telephony cross profile intent filters", re);
        }
    }

    void addCrossProfileIntentFilter(DefaultCrossProfileIntentFilter filter, int parentUserId,
            int profileUserId)
            throws RemoteException {
        if (filter.direction == DefaultCrossProfileIntentFilter.Direction.TO_PROFILE) {
            mIPackageManager.addCrossProfileIntentFilter(
                    filter.filter.getIntentFilter(),
                    mContext.getOpPackageName(),
                    parentUserId,
                    profileUserId,
                    filter.flags);
        } else {
            mIPackageManager.addCrossProfileIntentFilter(
                    filter.filter.getIntentFilter(),
                    mContext.getOpPackageName(),
                    profileUserId,
                    parentUserId,
                    filter.flags);
        }
    }

    boolean removeCrossProfileIntentFilter(DefaultCrossProfileIntentFilter filter, int parentUserId,
            int profileUserId)
            throws RemoteException {
        if (filter.direction == DefaultCrossProfileIntentFilter.Direction.TO_PROFILE) {
            return mIPackageManager.removeCrossProfileIntentFilter(
                    filter.filter.getIntentFilter(),
                    mContext.getOpPackageName(),
                    parentUserId,
                    profileUserId,
                    filter.flags);
        } else {
            return mIPackageManager.removeCrossProfileIntentFilter(
                    filter.filter.getIntentFilter(),
                    mContext.getOpPackageName(),
                    profileUserId,
                    parentUserId,
                    filter.flags);
        }
    }

    /**
     * @param factoryReset null: legacy behaviour, false: attempt to remove user, true: attempt to
     *                     factory reset
     */
    private void wipeDataNoLock(@Nullable ComponentName admin, int flags, String internalReason,
            String wipeReasonForUser, int userId, boolean calledOnParentInstance,
            @Nullable Boolean factoryReset) {
        wtfIfInLock();
        final String adminPackage;
        if (admin != null) {
            adminPackage = admin.getPackageName();
        } else {
            int callerId = mInjector.binderGetCallingUid();
            String[] adminPackages = mInjector.getPackageManager().getPackagesForUid(callerId);
            Preconditions.checkState(adminPackages.length > 0,
                    "Caller %s does not have any associated packages", callerId);
            adminPackage = adminPackages[0];
        }
        mInjector.binderWithCleanCallingIdentity(() -> {
            // First check whether the admin is allowed to wipe the device/user/profile.
            final String restriction;
            if (userId == UserHandle.USER_SYSTEM) {
                restriction = UserManager.DISALLOW_FACTORY_RESET;
            } else if (isManagedProfile(userId)) {
                restriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
            } else {
                restriction = UserManager.DISALLOW_REMOVE_USER;
            }
            if (isAdminAffectedByRestriction(admin, restriction, userId)) {
                throw new SecurityException("Cannot wipe data. " + restriction
                        + " restriction is set for user " + userId);
            }
        });

        boolean isSystemUser = userId == UserHandle.USER_SYSTEM;
        boolean wipeDevice;
        if (factoryReset == null || !mInjector.isChangeEnabled(EXPLICIT_WIPE_BEHAVIOUR,
                adminPackage,
                userId)) {
            // Legacy mode
            wipeDevice = isSystemUser;
        } else {
            // Explicit behaviour
            if (factoryReset) {
                EnforcingAdmin enforcingAdmin = enforcePermissionsAndGetEnforcingAdmin(
                        /*admin=*/ null,
                        /*permission=*/ new String[]{MANAGE_DEVICE_POLICY_WIPE_DATA,
                                MASTER_CLEAR},
                        USES_POLICY_WIPE_DATA,
                        adminPackage,
                        factoryReset ? UserHandle.USER_ALL :
                                getAffectedUser(calledOnParentInstance));
                wipeDevice = true;
            } else {
                mInjector.binderWithCleanCallingIdentity(() -> {
                    Preconditions.checkCallAuthorization(!isSystemUser,
                            "User %s is a system user and cannot be removed", userId);
                    boolean isLastNonHeadlessUser = getUserInfo(userId).isFull()
                            && mUserManager.getAliveUsers().stream()
                            .filter((it) -> it.getUserHandle().getIdentifier() != userId)
                            .noneMatch(UserInfo::isFull);
                    Preconditions.checkState(!isLastNonHeadlessUser,
                            "Removing user %s would leave the device without any active users. "
                                    + "Consider factory resetting the device instead.",
                            userId);
                });
                wipeDevice = false;
            }
        }
        mInjector.binderWithCleanCallingIdentity(() -> {
            if (wipeDevice) {
                forceWipeDeviceNoLock(
                        (flags & WIPE_EXTERNAL_STORAGE) != 0,
                        internalReason,
                        (flags & WIPE_EUICC) != 0,
                        (flags & WIPE_RESET_PROTECTION_DATA) != 0);
            } else {
                forceWipeUser(userId, wipeReasonForUser, (flags & WIPE_SILENTLY) != 0);
            }
        });
    }

    private void sendWipeProfileNotification(String wipeReasonForUser, UserHandle user) {
        Notification notification =
                new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
                        .setSmallIcon(android.R.drawable.stat_sys_warning)
                        .setContentTitle(getWorkProfileDeletedTitle())
                        .setContentText(wipeReasonForUser)
                        .setColor(mContext.getColor(R.color.system_notification_accent_color))
                        .setStyle(new Notification.BigTextStyle().bigText(wipeReasonForUser))
                        .build();
        mInjector.getNotificationManager().notifyAsUser(
                /* tag= */ null, SystemMessage.NOTE_PROFILE_WIPED, notification, user);
    }

    private String getWorkProfileDeletedTitle() {
        return getUpdatableString(WORK_PROFILE_DELETED_TITLE, R.string.work_profile_deleted);
    }

    private void clearWipeProfileNotification() {
        mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PROFILE_WIPED);
    }

    @Override
    public void setFactoryResetProtectionPolicy(ComponentName who, String callerPackageName,
            @Nullable FactoryResetProtectionPolicy policy) {
        if (!mHasFeature) {
            return;
        }
        if (!isPermissionCheckFlagEnabled()) {
            Preconditions.checkNotNull(who, "ComponentName is null");
        }
        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
        if (!isPermissionCheckFlagEnabled()) {
            Preconditions.checkCallAuthorization(
                    isDefaultDeviceOwner(caller)
                            || isProfileOwnerOfOrganizationOwnedDevice(caller));
        }
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager
                .OPERATION_SET_FACTORY_RESET_PROTECTION_POLICY);

        final int frpManagementAgentUid = getFrpManagementAgentUidOrThrow();
        synchronized (getLockObject()) {
            ActiveAdmin admin;
            if (isPermissionCheckFlagEnabled()) {
                admin = enforcePermissionAndGetEnforcingAdmin(
                        who, MANAGE_DEVICE_POLICY_FACTORY_RESET, caller.getPackageName(),
                        UserHandle.USER_ALL)
                        .getActiveAdmin();
            } else {
                admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
            }
            admin.mFactoryResetProtectionPolicy = policy;
            saveSettingsLocked(caller.getUserId());
        }

        mInjector.binderWithCleanCallingIdentity(
                () -> notifyResetProtectionPolicyChanged(frpManagementAgentUid));

        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_FACTORY_RESET_PROTECTION)
                .setAdmin(caller.getPackageName())
                .write();
    }

    // Shouldn't be called from binder thread without clearing identity.
    private void notifyResetProtectionPolicyChanged(int frpManagementAgentUid) {
        final Intent intent = new Intent(
                DevicePolicyManager.ACTION_RESET_PROTECTION_POLICY_CHANGED).addFlags(
                Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND | Intent.FLAG_RECEIVER_FOREGROUND);
        mContext.sendBroadcastAsUser(intent,
                UserHandle.getUserHandleForUid(frpManagementAgentUid),
                permission.MANAGE_FACTORY_RESET_PROTECTION);
    }

    @Override
    public FactoryResetProtectionPolicy getFactoryResetProtectionPolicy(
            @Nullable ComponentName who) {
        if (!mHasFeature) {
            return null;
        }

        final CallerIdentity caller = getCallerIdentity(who);
        final int frpManagementAgentUid = getFrpManagementAgentUidOrThrow();
        final ActiveAdmin admin;
        synchronized (getLockObject()) {
            if (who == null) {
                Preconditions.checkCallAuthorization(frpManagementAgentUid == caller.getUid()
                                || hasCallingPermission(permission.MASTER_CLEAR)
                                || hasCallingPermission(MANAGE_DEVICE_POLICY_FACTORY_RESET),
                        "Must be called by the FRP management agent on device");
                admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceOrSystemPermissionBasedAdminLocked();
            } else {
                Preconditions.checkCallAuthorization(
                        isDefaultDeviceOwner(caller)
                                || isProfileOwnerOfOrganizationOwnedDevice(caller));
                admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
            }
        }

        return admin != null ? admin.mFactoryResetProtectionPolicy : null;
    }

    private int getFrpManagementAgentUid() {
        PersistentDataBlockManagerInternal pdb = mInjector.getPersistentDataBlockManagerInternal();
        return pdb != null ? pdb.getAllowedUid() : -1;
    }

    private int getFrpManagementAgentUidOrThrow() {
        int uid = getFrpManagementAgentUid();
        if (uid == -1) {
            throw new UnsupportedOperationException(
                    "The persistent data block service is not supported on this device");
        }
        return uid;
    }

    @Override
    public boolean isFactoryResetProtectionPolicySupported() {
        return getFrpManagementAgentUid() != -1;
    }

    @Override
    public void sendLostModeLocationUpdate(AndroidFuture<Boolean> future) {
        if (!mHasFeature) {
            future.complete(false);
            return;
        }
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(permission.TRIGGER_LOST_MODE));

        synchronized (getLockObject()) {
            ActiveAdmin admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();

            Preconditions.checkState(admin != null,
                    "Lost mode location updates can only be sent on an organization-owned device.");
            mInjector.binderWithCleanCallingIdentity(() -> {
                String[] providers = {LocationManager.FUSED_PROVIDER,
                        LocationManager.NETWORK_PROVIDER, LocationManager.GPS_PROVIDER};
                tryRetrieveAndSendLocationUpdate(admin, future, providers, /* index= */ 0);
            });
        }
    }

    /** Send lost mode location updates recursively, in order of the list of location providers. */
    private void tryRetrieveAndSendLocationUpdate(ActiveAdmin admin,
            AndroidFuture<Boolean> future, String[] providers, int index) {
        // None of the providers were able to get location, return false
        if (index == providers.length) {
            future.complete(false);
            return;
        }
        if (mInjector.getLocationManager().isProviderEnabled(providers[index])) {
            mInjector.getLocationManager().getCurrentLocation(providers[index],
                    /* cancellationSignal= */ null, mContext.getMainExecutor(), location -> {
                        if (location != null) {
                            mContext.sendBroadcastAsUser(
                                    newLostModeLocationUpdateIntent(admin, location),
                                    admin.getUserHandle());
                            future.complete(true);
                        } else {
                            tryRetrieveAndSendLocationUpdate(admin, future, providers, index + 1);
                        }
                    }
            );
        } else {
           tryRetrieveAndSendLocationUpdate(admin, future, providers, index + 1);
        }
    }

    private Intent newLostModeLocationUpdateIntent(ActiveAdmin admin, Location location) {
        final Intent intent = new Intent(
                DevicePolicyManager.ACTION_LOST_MODE_LOCATION_UPDATE);
        intent.putExtra(DevicePolicyManager.EXTRA_LOST_MODE_LOCATION, location);
        intent.setPackage(admin.info.getPackageName());
        return intent;
    }

    /**
     * Called by a privileged caller holding {@code BIND_DEVICE_ADMIN} permission to retrieve
     * the remove warning for the given device admin.
     */
    @Override
    public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
        if (!mHasFeature) {
            return;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
        Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));

        synchronized (getLockObject()) {
            ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
            if (admin == null) {
                result.sendResult(null);
                return;
            }
            Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
            intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
            intent.setComponent(admin.info.getComponent());
            mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
                    null, new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    result.sendResult(getResultExtras(false));
                }
            }, null, Activity.RESULT_OK, null, null);
        }
    }

    @Override
    public void reportPasswordChanged(PasswordMetrics metrics, @UserIdInt int userId) {
        if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
            return;
        }

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(isSystemUid(caller));
        // Managed Profile password can only be changed when it has a separate challenge.
        if (!isSeparateProfileChallengeEnabled(userId)) {
            Preconditions.checkCallAuthorization(!isManagedProfile(userId), "You can "
                    + "not set the active password for a managed profile, userId = %d", userId);
        }

        DevicePolicyData policy = getUserData(userId);
        final ArraySet<Integer> affectedUserIds = new ArraySet<>();

        synchronized (getLockObject()) {
            policy.mFailedPasswordAttempts = 0;
            affectedUserIds.add(userId);
            affectedUserIds.addAll(updatePasswordValidityCheckpointLocked(
                    userId, /* parent */ false));
            affectedUserIds.addAll(updatePasswordExpirationsLocked(userId));
            setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false);

            // Send a broadcast to each profile using this password as its primary unlock.
            sendAdminCommandForLockscreenPoliciesLocked(
                    DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
                    DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId);

            affectedUserIds.addAll(removeCaApprovalsIfNeeded(userId));
            saveSettingsForUsersLocked(affectedUserIds);
        }
        if (mInjector.securityLogIsLoggingEnabled()) {
            SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_CHANGED,
                    /* complexity */ metrics.determineComplexity(), /*user*/ userId);
        }
    }

    /**
     * Called any time the device password is updated. Resets all password expiration clocks.
     *
     * @return the set of user IDs that have been affected
     */
    @GuardedBy("getLockObject()")
    private Set<Integer> updatePasswordExpirationsLocked(int userHandle) {
        final ArraySet<Integer> affectedUserIds = new ArraySet<>();
        List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle);
        for (int i = 0; i < admins.size(); i++) {
            ActiveAdmin admin = admins.get(i);
            if (admin.isPermissionBased || admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
                affectedUserIds.add(admin.getUserHandle().getIdentifier());
                long timeout = admin.passwordExpirationTimeout;
                admin.passwordExpirationDate =
                        timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
            }
        }
        return affectedUserIds;
    }

    @Override
    public void reportFailedPasswordAttempt(int userHandle, boolean parent) {
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
        Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));
        if (!isSeparateProfileChallengeEnabled(userHandle)) {
            Preconditions.checkCallAuthorization(!isManagedProfile(userHandle),
                    "You can not report failed password attempt if separate profile challenge is "
                            + "not in place for a managed profile, userId = %d", userHandle);
        }

        boolean wipeData = false;
        ActiveAdmin strictestAdmin = null;
        final long ident = mInjector.binderClearCallingIdentity();
        try {
            synchronized (getLockObject()) {
                DevicePolicyData policy = getUserData(userHandle);
                policy.mFailedPasswordAttempts++;
                saveSettingsLocked(userHandle);
                if (mHasFeature) {
                    strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
                            userHandle, /* parent= */ false);
                    int max = strictestAdmin != null
                            ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
                    if (max > 0 && policy.mFailedPasswordAttempts >= max) {
                        wipeData = true;
                    }

                    sendAdminCommandForLockscreenPoliciesLocked(
                            DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
                            DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
                }
            }
        } finally {
            mInjector.binderRestoreCallingIdentity(ident);
        }

        if (wipeData && strictestAdmin != null) {
            final int userId = getUserIdToWipeForFailedPasswords(strictestAdmin);
            Slogf.i(LOG_TAG, "Max failed password attempts policy reached for admin: "
                    + strictestAdmin.info.getComponent().flattenToShortString()
                    + ". Calling wipeData for user " + userId);

            // Attempt to wipe the device/user/profile associated with the admin, as if the
            // admin had called wipeData(). That way we can check whether the admin is actually
            // allowed to wipe the device (e.g. a regular device admin shouldn't be able to wipe the
            // device if the device owner has set DISALLOW_FACTORY_RESET, but the DO should be
            // able to do so).
            // IMPORTANT: Call without holding the lock to prevent deadlock.
            try {
                wipeDataNoLock(strictestAdmin.info.getComponent(),
                        /* flags= */ 0,
                        /* reason= */ "reportFailedPasswordAttempt()",
                        getFailedPasswordAttemptWipeMessage(),
                        userId,
                        /* calledOnParentInstance= */ parent,
                        // factoryReset=null to enable U- behaviour
                        /* factoryReset= */ null);
            } catch (SecurityException e) {
                Slogf.w(LOG_TAG, "Failed to wipe user " + userId
                        + " after max failed password attempts reached.", e);
            }
        }

        if (mInjector.securityLogIsLoggingEnabled()) {
            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT,
                    /* result= */ 0, /* method strength= */ 1);
        }
    }

    private String getFailedPasswordAttemptWipeMessage() {
        return getUpdatableString(
                WORK_PROFILE_DELETED_FAILED_PASSWORD_ATTEMPTS_MESSAGE,
               R.string.work_profile_deleted_reason_maximum_password_failure);
    }

    /**
     * Returns which user should be wiped if this admin's maximum filed password attempts policy is
     * violated.
     */
    private int getUserIdToWipeForFailedPasswords(ActiveAdmin admin) {
        final int userId = admin.getUserHandle().getIdentifier();
        if (admin.isPermissionBased) {
            return userId;
        }
        final ComponentName component = admin.info.getComponent();
        return isProfileOwnerOfOrganizationOwnedDevice(component, userId)
                ? getProfileParentId(userId) : userId;
    }

    @Override
    public void reportSuccessfulPasswordAttempt(int userHandle) {
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
        Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));

        synchronized (getLockObject()) {
            DevicePolicyData policy = getUserData(userHandle);
            if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
                mInjector.binderWithCleanCallingIdentity(() -> {
                    policy.mFailedPasswordAttempts = 0;
                    policy.mPasswordOwner = -1;
                    saveSettingsLocked(userHandle);
                    if (mHasFeature) {
                        sendAdminCommandForLockscreenPoliciesLocked(
                                DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
                                DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
                    }
                });
            }
        }

        if (mInjector.securityLogIsLoggingEnabled()) {
            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
                    /*method strength*/ 1);
        }
    }

    @Override
    public void reportFailedBiometricAttempt(int userHandle) {
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
        Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));

        if (mInjector.securityLogIsLoggingEnabled()) {
            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
                    /*method strength*/ 0);
        }
    }

    @Override
    public void reportSuccessfulBiometricAttempt(int userHandle) {
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
        Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));

        if (mInjector.securityLogIsLoggingEnabled()) {
            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
                    /*method strength*/ 0);
        }
    }

    @Override
    public void reportKeyguardDismissed(int userHandle) {
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
        Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));

        if (mInjector.securityLogIsLoggingEnabled()) {
            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
        }
    }

    @Override
    public void reportKeyguardSecured(int userHandle) {
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
        Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));

        if (mInjector.securityLogIsLoggingEnabled()) {
            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
        }
    }

    @Override
    public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
            String exclusionList) {
        if (!mHasFeature) {
            return null;
        }
        synchronized (getLockObject()) {
            Objects.requireNonNull(who, "ComponentName is null");

            // Only check if system user has set global proxy. We don't allow other users to set it.
            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
                    DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);

            // Scan through active admins and find if anyone has already
            // set the global proxy.
            Set<ComponentName> compSet = policy.mAdminMap.keySet();
            for (ComponentName component : compSet) {
                ActiveAdmin ap = policy.mAdminMap.get(component);
                if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
                    // Another admin already sets the global proxy
                    // Return it to the caller.
                    return component;
                }
            }

            // If the user is not system, don't set the global proxy. Fail silently.
            if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
                Slogf.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
                        + UserHandle.getCallingUserId() + " is not permitted.");
                return null;
            }
            if (proxySpec == null) {
                admin.specifiesGlobalProxy = false;
                admin.globalProxySpec = null;
                admin.globalProxyExclusionList = null;
            } else {

                admin.specifiesGlobalProxy = true;
                admin.globalProxySpec = proxySpec;
                admin.globalProxyExclusionList = exclusionList;
            }

            // Reset the global proxy accordingly
            // Do this using system permissions, as apps cannot write to secure settings
            mInjector.binderWithCleanCallingIdentity(() -> resetGlobalProxyLocked(policy));
            return null;
        }
    }

    @Override
    public ComponentName getGlobalProxyAdmin(int userHandle) {
        if (!mHasFeature) {
            return null;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(
                hasFullCrossUsersPermission(caller, userHandle) && canQueryAdminPolicy(caller));

        synchronized (getLockObject()) {
            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
            // Scan through active admins and find if anyone has already
            // set the global proxy.
            final int N = policy.mAdminList.size();
            for (int i = 0; i < N; i++) {
                ActiveAdmin ap = policy.mAdminList.get(i);
                if (ap.specifiesGlobalProxy) {
                    // Device admin sets the global proxy
                    // Return it to the caller.
                    return ap.info.getComponent();
                }
            }
        }
        // No device admin sets the global proxy.
        return null;
    }

    @Override
    public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
        checkAllUsersAreAffiliatedWithDevice();
        mInjector.binderWithCleanCallingIdentity(
                () -> mInjector.getConnectivityManager().setGlobalProxy(proxyInfo));
    }

    private void resetGlobalProxyLocked(DevicePolicyData policy) {
        final int N = policy.mAdminList.size();
        for (int i = 0; i < N; i++) {
            ActiveAdmin ap = policy.mAdminList.get(i);
            if (ap.specifiesGlobalProxy) {
                saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
                return;
            }
        }
        // No device admins defining global proxies - reset global proxy settings to none
        saveGlobalProxyLocked(null, null);
    }

    private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
        if (exclusionList == null) {
            exclusionList = "";
        }
        if (proxySpec == null) {
            proxySpec = "";
        }
        // Remove white spaces
        proxySpec = proxySpec.trim();
        String data[] = proxySpec.split(":");
        int proxyPort = 8080;
        if (data.length > 1) {
            try {
                proxyPort = Integer.parseInt(data[1]);
            } catch (NumberFormatException e) {}
        }
        exclusionList = exclusionList.trim();

        ProxyInfo proxyProperties = ProxyInfo.buildDirectProxy(data[0], proxyPort,
                ProxyUtils.exclusionStringAsList(exclusionList));
        if (!proxyProperties.isValid()) {
            Slogf.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
            return;
        }
        mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
        mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
        mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
                exclusionList);
    }

    /**
     * Called by an application that is administering the device to request that the storage system
     * be encrypted. Does nothing if the caller is on a secondary user or a managed profile.
     *
     * @return the new total request status (for all admins), or {@link
     *         DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user
     */
    @Override
    public int setStorageEncryption(ComponentName who, boolean encrypt) {
        if (!mHasFeature) {
            return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final int userHandle = UserHandle.getCallingUserId();
        synchronized (getLockObject()) {
            // Check for permissions
            // Only system user can set storage encryption
            if (userHandle != UserHandle.USER_SYSTEM) {
                Slogf.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. "
                        + "User " + UserHandle.getCallingUserId() + " is not permitted.");
                return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
            }

            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
                    DeviceAdminInfo.USES_ENCRYPTED_STORAGE);

            // Quick exit:  If the filesystem does not support encryption, we can exit early.
            if (!isEncryptionSupported()) {
                return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
            }

            // (1) Record the value for the admin so it's sticky
            if (ap.encryptionRequested != encrypt) {
                ap.encryptionRequested = encrypt;
                saveSettingsLocked(userHandle);
            }

            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
            // (2) Compute "max" for all admins
            boolean newRequested = false;
            final int N = policy.mAdminList.size();
            for (int i = 0; i < N; i++) {
                newRequested |= policy.mAdminList.get(i).encryptionRequested;
            }

            // Notify OS of new request
            setEncryptionRequested(newRequested);

            // Return the new global request status
            return newRequested
                    ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
                    : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
        }
    }

    /**
     * Get the current storage encryption request status for a given admin, or aggregate of all
     * active admins.
     */
    @Override
    public boolean getStorageEncryption(@Nullable ComponentName who, int userHandle) {
        if (!mHasFeature) {
            return false;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));

        synchronized (getLockObject()) {
            // Check for permissions if a particular caller is specified
            if (caller.hasAdminComponent()) {
                // When checking for a single caller, status is based on caller's request
                ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
                return ap != null ? ap.encryptionRequested : false;
            }

            // If no particular caller is specified, return the aggregate set of requests.
            // This is short circuited by returning true on the first hit.
            DevicePolicyData policy = getUserData(userHandle);
            final int N = policy.mAdminList.size();
            for (int i = 0; i < N; i++) {
                if (policy.mAdminList.get(i).encryptionRequested) {
                    return true;
                }
            }
            return false;
        }
    }

    /**
     * Get the current encryption status of the device.
     */
    @Override
    public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
        if (!mHasFeature) {
            // Ok to return current status.
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity(callerPackage);
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));


        final ApplicationInfo ai;
        try {
            ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
        } catch (RemoteException e) {
            throw new SecurityException(e);
        }

        boolean legacyApp = false;
        if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
            legacyApp = true;
        }

        final int rawStatus = getEncryptionStatus();
        if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
            return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
        }
        return rawStatus;
    }

    /**
     * Hook to low-levels:  This should report if the filesystem supports encrypted storage.
     */
    private boolean isEncryptionSupported() {
        // Note, this can be implemented as
        //   return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
        // But is provided as a separate internal method if there's a faster way to do a
        // simple check for supported-or-not.
        return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
    }

    /**
     * Hook to low-levels:  Reporting the current status of encryption.
     * @return Either {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED}
     * or {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}.
     */
    private int getEncryptionStatus() {
        if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
            return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
        } else {
            return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
        }
    }

    /**
     * Hook to low-levels:  If needed, record the new admin setting for encryption.
     */
    private void setEncryptionRequested(boolean encrypt) {
    }

    /**
     * Set whether the screen capture is disabled for the user managed by the specified admin.
     */
    @Override
    public void setScreenCaptureDisabled(
            ComponentName who, String callerPackage, boolean disabled, boolean parent) {
        if (!mHasFeature) {
            return;
        }

        CallerIdentity caller = getCallerIdentity(who, callerPackage);
        int callerUserId = Binder.getCallingUserHandle().getIdentifier();
        int targetUserId = parent ? getProfileParentId(callerUserId) : callerUserId;
        EnforcingAdmin admin = enforcePermissionAndGetEnforcingAdmin(
                who, MANAGE_DEVICE_POLICY_SCREEN_CAPTURE, caller.getPackageName(),
                targetUserId);
        if ((parent && isProfileOwnerOfOrganizationOwnedDevice(caller))
                || isDefaultDeviceOwner(caller)) {
            if (disabled) {
                mDevicePolicyEngine.setGlobalPolicy(
                        PolicyDefinition.SCREEN_CAPTURE_DISABLED,
                        admin,
                        new BooleanPolicyValue(disabled));
            } else {
                mDevicePolicyEngine.removeGlobalPolicy(
                        PolicyDefinition.SCREEN_CAPTURE_DISABLED,
                        admin);
            }
        } else {
            if (disabled) {
                mDevicePolicyEngine.setLocalPolicy(
                        PolicyDefinition.SCREEN_CAPTURE_DISABLED,
                        admin,
                        new BooleanPolicyValue(disabled),
                        callerUserId);
            } else {
                mDevicePolicyEngine.removeLocalPolicy(
                        PolicyDefinition.SCREEN_CAPTURE_DISABLED,
                        admin,
                        callerUserId);
            }
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_SCREEN_CAPTURE_DISABLED)
                .setAdmin(caller.getPackageName())
                .setBoolean(disabled)
                .write();
    }

    // Set the latest screen capture policy, overriding any existing ones.
    // userHandle can be one of USER_ALL, USER_NULL or a concrete userId.
    private void setScreenCaptureDisabled(int userHandle) {
        int current = mPolicyCache.getScreenCaptureDisallowedUser();
        if (userHandle == current) {
            return;
        }
        mPolicyCache.setScreenCaptureDisallowedUser(userHandle);
        updateScreenCaptureDisabled();
    }

    /**
     * Returns whether or not screen capture is disabled for  any active admin.
     */
    @Override
    public boolean getScreenCaptureDisabled(ComponentName who, int userHandle, boolean parent) {
        if (!mHasFeature) {
            return false;
        }
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));

        if (parent) {
            Preconditions.checkCallAuthorization(
                    isProfileOwnerOfOrganizationOwnedDevice(getCallerIdentity().getUserId()));
        }
        Boolean disallowed = mDevicePolicyEngine.getResolvedPolicy(
                PolicyDefinition.SCREEN_CAPTURE_DISABLED,
                userHandle);
        return disallowed != null && disallowed;
    }

    private void updateScreenCaptureDisabled() {
        mHandler.post(() -> {
            try {
                mInjector.getIWindowManager().refreshScreenCaptureDisabled();
            } catch (RemoteException e) {
                Slogf.w(LOG_TAG, "Unable to notify WindowManager.", e);
            }
        });
    }

    @Override
    public void setNearbyNotificationStreamingPolicy(int policy) {
        if (!mHasFeature) {
            return;
        }

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || isProfileOwner(caller));

        synchronized (getLockObject()) {
            final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
            if (admin.mNearbyNotificationStreamingPolicy != policy) {
                admin.mNearbyNotificationStreamingPolicy = policy;
                saveSettingsLocked(caller.getUserId());
            }
        }
    }

    @Override
    public int getNearbyNotificationStreamingPolicy(final int userId) {
        if (!mHasFeature) {
            return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
        }

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(
                isProfileOwner(caller) || isDefaultDeviceOwner(caller)
                        || hasCallingOrSelfPermission(permission.READ_NEARBY_STREAMING_POLICY));
        Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));

        synchronized (getLockObject()) {
            final ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userId);
            return admin != null
                    ? admin.mNearbyNotificationStreamingPolicy
                    : NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
        }
    }

    @Override
    public void setNearbyAppStreamingPolicy(int policy) {
        if (!mHasFeature) {
            return;
        }

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || isProfileOwner(caller));

        synchronized (getLockObject()) {
            final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
            if (admin.mNearbyAppStreamingPolicy != policy) {
                admin.mNearbyAppStreamingPolicy = policy;
                saveSettingsLocked(caller.getUserId());
            }
        }
    }

    @Override
    public int getNearbyAppStreamingPolicy(final int userId) {
        if (!mHasFeature) {
            return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
        }

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(
                isProfileOwner(caller) || isDefaultDeviceOwner(caller)
                        || hasCallingOrSelfPermission(permission.READ_NEARBY_STREAMING_POLICY));
        Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));

        synchronized (getLockObject()) {
            final ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userId);
            return admin != null
                    ? admin.mNearbyAppStreamingPolicy
                    : NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
        }
    }

    /**
     * Set whether auto time is required by the specified admin (must be device or profile owner).
     */
    @Override
    public void setAutoTimeRequired(ComponentName who, boolean required) {
        if (!mHasFeature) {
            return;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isDeviceOwner(caller) || isProfileOwner(caller));

        boolean requireAutoTimeChanged = false;
        synchronized (getLockObject()) {
            Preconditions.checkCallAuthorization(!isManagedProfile(caller.getUserId()),
                    "Managed profile cannot set auto time required");

            EnforcingAdmin admin = getEnforcingAdminForCaller(who, who.getPackageName());
            setGlobalUserRestrictionInternal(
                    admin, UserManager.DISALLOW_CONFIG_DATE_TIME, required);
        }
        // Turn AUTO_TIME on in settings if it is required
        if (required) {
            mInjector.binderWithCleanCallingIdentity(
                    () -> mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME,
                            1 /* AUTO_TIME on */));
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_AUTO_TIME_REQUIRED)
                .setAdmin(who)
                .setBoolean(required)
                .write();
    }

    /**
     * Returns whether or not auto time is required by the device owner or any profile owner.
     */
    @Override
    public boolean getAutoTimeRequired() {
        if (!mHasFeature) {
            return false;
        }
        Boolean required = mDevicePolicyEngine.getResolvedPolicy(
                PolicyDefinition.getPolicyDefinitionForUserRestriction(
                        UserManager.DISALLOW_CONFIG_DATE_TIME),
                mInjector.binderGetCallingUserHandle().getIdentifier());
        return required != null && required;
    }

    /**
     * Set whether auto time is enabled on the device.
     */
    @Override
    public void setAutoTimeEnabled(@Nullable ComponentName who, String callerPackageName,
            boolean enabled) {
        if (!mHasFeature) {
            return;
        }

        CallerIdentity caller;
        if (isUnicornFlagEnabled()) {
            caller = getCallerIdentity(who, callerPackageName);
        } else {
            caller = getCallerIdentity(who);
        }

        if (isUnicornFlagEnabled()) {
            // The effect of this policy is device-wide.
            enforcePermission(SET_TIME, caller.getPackageName(), UserHandle.USER_ALL);
        } else {
            Objects.requireNonNull(who, "ComponentName is null");
            Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller)
                    || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDefaultDeviceOwner(
                    caller));
        }
        mInjector.binderWithCleanCallingIdentity(() ->
                mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, enabled ? 1 : 0));

        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_AUTO_TIME)
                .setAdmin(caller.getPackageName())
                .setBoolean(enabled)
                .write();
    }

    /**
     * Returns whether auto time is used on the device or not.
     */
    @Override
    public boolean getAutoTimeEnabled(@Nullable ComponentName who, String callerPackageName) {
        if (!mHasFeature) {
            return false;
        }
        CallerIdentity caller;
        if (isUnicornFlagEnabled()) {
            caller = getCallerIdentity(who, callerPackageName);
        } else {
            caller = getCallerIdentity(who);
        }

        if (isUnicornFlagEnabled()) {
            enforceCanQuery(SET_TIME, caller.getPackageName(), UserHandle.USER_ALL);
        } else {
            Objects.requireNonNull(who, "ComponentName is null");
            Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller)
                    || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDefaultDeviceOwner(
                    caller));
        }

        return mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) > 0;
    }

    /**
     * Set whether auto time zone is enabled on the device.
     */
    @Override
    public void setAutoTimeZoneEnabled(@Nullable ComponentName who, String callerPackageName,
            boolean enabled) {
        if (!mHasFeature) {
            return;
        }

        CallerIdentity caller;
        if (isUnicornFlagEnabled()) {
            caller = getCallerIdentity(who, callerPackageName);
        } else {
            caller = getCallerIdentity(who);
        }

        if (isUnicornFlagEnabled()) {
            // The effect of this policy is device-wide.
            EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                    who,
                    SET_TIME_ZONE,
                    caller.getPackageName(),
                    UserHandle.USER_ALL
            );
            mDevicePolicyEngine.setGlobalPolicy(
                    PolicyDefinition.AUTO_TIMEZONE,
                    // TODO(b/260573124): add correct enforcing admin when permission changes are
                    //  merged.
                    enforcingAdmin,
                    new BooleanPolicyValue(enabled));
        } else {
            Objects.requireNonNull(who, "ComponentName is null");
            Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller)
                    || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDefaultDeviceOwner(
                    caller));
            mInjector.binderWithCleanCallingIdentity(() ->
                    mInjector.settingsGlobalPutInt(Global.AUTO_TIME_ZONE, enabled ? 1 : 0));
        }

        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_AUTO_TIME_ZONE)
                .setAdmin(caller.getPackageName())
                .setBoolean(enabled)
                .write();
    }

    /**
     * Returns whether auto time zone is used on the device or not.
     */
    @Override
    public boolean getAutoTimeZoneEnabled(@Nullable ComponentName who, String callerPackageName) {
        if (!mHasFeature) {
            return false;
        }

        CallerIdentity caller;
        if (isUnicornFlagEnabled()) {
            caller = getCallerIdentity(who, callerPackageName);
        } else {
            caller = getCallerIdentity(who);
        }

        if (isUnicornFlagEnabled()) {
            // The effect of this policy is device-wide.
            enforceCanQuery(SET_TIME_ZONE, caller.getPackageName(), UserHandle.USER_ALL);
        } else {
            Objects.requireNonNull(who, "ComponentName is null");
            Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller)
                    || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDefaultDeviceOwner(
                    caller));
        }

        return mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) > 0;
    }

    // TODO (b/137101239): remove this method in follow-up CL
    // since it's only used for split system user.
    @Override
    public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
        throw new UnsupportedOperationException("This method was used by split system user only.");
    }

    // TODO (b/137101239): remove this method in follow-up CL
    // since it's only used for split system user.
    @Override
    public boolean getForceEphemeralUsers(ComponentName who) {
        throw new UnsupportedOperationException("This method was used by split system user only.");
    }

    @Override
    public boolean requestBugreport(ComponentName who) {
        if (!mHasFeature) {
            return false;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        // TODO: If an unaffiliated user is removed, the admin will be able to request a bugreport
        // which could still contain data related to that user. Should we disallow that, e.g. until
        // next boot? Might not be needed given that this still requires user consent.
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
        checkAllUsersAreAffiliatedWithDevice();
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REQUEST_BUGREPORT);

        if (mBugreportCollectionManager.requestBugreport()) {
            DevicePolicyEventLogger
                    .createEvent(DevicePolicyEnums.REQUEST_BUGREPORT)
                    .setAdmin(who)
                    .write();

            final long currentTime = System.currentTimeMillis();
            synchronized (getLockObject()) {
                DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
                if (currentTime > policyData.mLastBugReportRequestTime) {
                    policyData.mLastBugReportRequestTime = currentTime;
                    saveSettingsLocked(UserHandle.USER_SYSTEM);
                }
            }

            return true;
        } else {
            return false;
        }
    }

    void sendDeviceOwnerCommand(String action, Bundle extras) {
        final int deviceOwnerUserId;
        final ComponentName receiverComponent;
        synchronized (getLockObject()) {
            deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
            receiverComponent = mOwners.getDeviceOwnerComponent();
        }
        sendActiveAdminCommand(action, extras, deviceOwnerUserId, receiverComponent,
                /* inForeground */ false);
    }

    void sendDeviceOwnerOrProfileOwnerCommand(String action, Bundle extras, int userId) {
        if (userId == UserHandle.USER_ALL) {
            userId = UserHandle.USER_SYSTEM;
        }
        boolean inForeground = false;
        ComponentName receiverComponent = null;
        if (action.equals(DeviceAdminReceiver.ACTION_NETWORK_LOGS_AVAILABLE)) {
            inForeground = true;
            receiverComponent = resolveDelegateReceiver(DELEGATION_NETWORK_LOGGING, action, userId);
        }
        if (action.equals(DeviceAdminReceiver.ACTION_SECURITY_LOGS_AVAILABLE)) {
            inForeground = true;
            receiverComponent = resolveDelegateReceiver(
                DELEGATION_SECURITY_LOGGING, action, userId);
        }
        if (receiverComponent == null) {
            receiverComponent = getOwnerComponent(userId);
        }
        sendActiveAdminCommand(action, extras, userId, receiverComponent, inForeground);
    }

    private void sendProfileOwnerCommand(String action, Bundle extras, @UserIdInt int userId) {
        sendActiveAdminCommand(action, extras, userId, mOwners.getProfileOwnerComponent(userId),
                /* inForeground */ false);
    }

    private void sendActiveAdminCommand(String action, Bundle extras,
            @UserIdInt int userId, ComponentName receiverComponent, boolean inForeground) {
        final Intent intent = new Intent(action);
        intent.setComponent(receiverComponent);
        if (extras != null) {
            intent.putExtras(extras);
        }
        if (inForeground) {
            intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        }

        if (VERBOSE_LOG) {
            Slogf.v(LOG_TAG, "sendActiveAdminCommand(): broadcasting " + action + " to "
                    + receiverComponent.flattenToShortString() + " on user " + userId);
        }
        mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
    }

    private void sendOwnerChangedBroadcast(String broadcast, int userId) {
        final Intent intent = new Intent(broadcast)
                .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
        mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
    }

    void sendBugreportToDeviceOwner(Uri bugreportUri, String bugreportHash) {
        synchronized (getLockObject()) {
            final Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
            intent.setComponent(mOwners.getDeviceOwnerComponent());
            intent.setDataAndType(bugreportUri, RemoteBugreportManager.BUGREPORT_MIMETYPE);
            intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            final UriGrantsManagerInternal ugm = LocalServices
                    .getService(UriGrantsManagerInternal.class);
            final NeededUriGrants needed = ugm.checkGrantUriPermissionFromIntent(intent,
                    Process.SHELL_UID, mOwners.getDeviceOwnerComponent().getPackageName(),
                    mOwners.getDeviceOwnerUserId());
            ugm.grantUriPermissionUncheckedFromIntent(needed, null);

            mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
        }
    }

    void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri, String bugreportHash) {
        synchronized (getLockObject()) {
            mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
        }
    }

    Pair<String, String> getDeviceOwnerRemoteBugreportUriAndHash() {
        synchronized (getLockObject()) {
            final String uri = mOwners.getDeviceOwnerRemoteBugreportUri();
            return uri == null ? null
                    : new Pair<>(uri, mOwners.getDeviceOwnerRemoteBugreportHash());
        }
    }

    /**
     * Disables all device cameras according to the specified admin.
     */
    @Override
    public void setCameraDisabled(ComponentName who, String callerPackageName, boolean disabled,
            boolean parent) {
        if (!mHasFeature) {
            return;
        }

        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
        final int userId = caller.getUserId();

        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_CAMERA_DISABLED);
        EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                who,
                MANAGE_DEVICE_POLICY_CAMERA,
                caller.getPackageName(),
                getProfileParentUserIfRequested(userId, parent));
        try {
            setBackwardCompatibleUserRestriction(
                    caller, enforcingAdmin, UserManager.DISALLOW_CAMERA, disabled, parent);
        } catch (IllegalStateException e) {
            throw new IllegalStateException(
                    "Please use addUserRestriction or addUserRestrictionGlobally using the key"
                            + " UserManager.DISALLOW_CAMERA to disable the camera locally or"
                            + " globally, respectively");
        }

        final int affectedUserId = parent ? getProfileParentId(userId) : userId;
        if (SecurityLog.isLoggingEnabled() && who != null) {
            SecurityLog.writeEvent(SecurityLog.TAG_CAMERA_POLICY_SET,
                    who.getPackageName(), userId, affectedUserId, disabled ? 1 : 0);
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_CAMERA_DISABLED)
                .setAdmin(caller.getPackageName())
                .setBoolean(disabled)
                .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT)
                .write();
    }

    /**
     * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
     * active admins.
     */
    @Override
    public boolean getCameraDisabled(ComponentName who, String callerPackageName, int userHandle,
            boolean parent) {
        if (!mHasFeature) {
            return false;
        }
        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
        Preconditions.checkCallAuthorization(
                hasFullCrossUsersPermission(caller, userHandle)
                        || isCameraServerUid(caller)
                        || hasPermission(MANAGE_DEVICE_POLICY_CAMERA,
                            caller.getPackageName(), userHandle)
                        || hasPermission(QUERY_ADMIN_POLICY, caller.getPackageName()));

        int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
        PolicyDefinition<Boolean> policy =
                PolicyDefinition.getPolicyDefinitionForUserRestriction(
                        UserManager.DISALLOW_CAMERA);
        if (who != null) {
            EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackageName);
            Boolean value = null;
            if (isDeviceOwner(caller)) {
                value = mDevicePolicyEngine.getGlobalPolicySetByAdmin(policy, admin);
            } else {
                value = mDevicePolicyEngine.getLocalPolicySetByAdmin(
                        policy, admin, affectedUserId);
            }
            return Boolean.TRUE.equals(value);

        } else {
            return Boolean.TRUE.equals(
                    mDevicePolicyEngine.getResolvedPolicy(policy, affectedUserId));
        }
    }

    @Override
    public void setKeyguardDisabledFeatures(
            ComponentName who, String callerPackageName, int which, boolean parent) {
        if (!mHasFeature) {
            return;
        }

        CallerIdentity caller;
        if (isUnicornFlagEnabled()) {
            caller = getCallerIdentity(who, callerPackageName);
        } else {
            caller = getCallerIdentity(who);
            Objects.requireNonNull(who, "ComponentName is null");
        }

        final int userHandle = caller.getUserId();
        int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
        synchronized (getLockObject()) {
            if (isUnicornFlagEnabled()) {
                // SUPPORT USES_POLICY_DISABLE_KEYGUARD_FEATURES
                EnforcingAdmin admin = enforcePermissionAndGetEnforcingAdmin(
                        who, MANAGE_DEVICE_POLICY_KEYGUARD, caller.getPackageName(),
                        affectedUserId);
                if (which == 0) {
                    mDevicePolicyEngine.removeLocalPolicy(
                            PolicyDefinition.KEYGUARD_DISABLED_FEATURES, admin, affectedUserId);
                } else {
                    // TODO(b/273723433): revisit silent masking of features
                    if (isManagedProfile(userHandle)) {
                        if (parent) {
                            if (isProfileOwnerOfOrganizationOwnedDevice(caller)) {
                                which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
                            } else {
                                which = which
                                        & NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
                            }
                        } else {
                            which = which & PROFILE_KEYGUARD_FEATURES;
                        }
                    }
                    mDevicePolicyEngine.setLocalPolicy(PolicyDefinition.KEYGUARD_DISABLED_FEATURES,
                            admin, new IntegerPolicyValue(which), affectedUserId);
                }
                invalidateBinderCaches();
            } else {
                ActiveAdmin ap = getActiveAdminForCallerLocked(
                        who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
                if (isManagedProfile(userHandle)) {
                    if (parent) {
                        if (isProfileOwnerOfOrganizationOwnedDevice(caller)) {
                            which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
                        } else {
                            which = which & NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
                        }
                    } else {
                        which = which & PROFILE_KEYGUARD_FEATURES;
                    }
                }
                if (ap.disabledKeyguardFeatures != which) {
                    ap.disabledKeyguardFeatures = which;
                    saveSettingsLocked(userHandle);
                }
            }
        }
        if (SecurityLog.isLoggingEnabled()) {
            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISABLED_FEATURES_SET,
                    caller.getPackageName(), userHandle, affectedUserId, which);
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_KEYGUARD_DISABLED_FEATURES)
                .setAdmin(caller.getPackageName())
                .setInt(which)
                .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT)
                .write();
    }

    /**
     * Gets the disabled state for features in keyguard for the given admin,
     * or the aggregate of all active admins if who is null.
     * This API is cached: invalidate with invalidateBinderCaches().
     */
    @Override
    public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
        if (!mHasFeature) {
            return 0;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
        Preconditions.checkCallAuthorization(
                who == null || isCallingFromPackage(who.getPackageName(), caller.getUid())
                        || isSystemUid(caller));
        int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;

        synchronized (getLockObject()) {
            if (who != null) {
                if (isUnicornFlagEnabled()) {
                    EnforcingAdmin admin = getEnforcingAdminForPackage(
                            who, who.getPackageName(), userHandle);
                    Integer features = mDevicePolicyEngine.getLocalPolicySetByAdmin(
                            PolicyDefinition.KEYGUARD_DISABLED_FEATURES,
                            admin,
                            affectedUserId);

                    return features == null ? 0 : features;
                } else {
                    ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
                    return (admin != null) ? admin.disabledKeyguardFeatures : 0;
                }
            }

            if (isUnicornFlagEnabled()) {
                Integer features = mDevicePolicyEngine.getResolvedPolicy(
                        PolicyDefinition.KEYGUARD_DISABLED_FEATURES,
                        affectedUserId);

                return Binder.withCleanCallingIdentity(() -> {
                    int combinedFeatures = features == null ? 0 : features;
                    List<UserInfo> profiles = mUserManager.getProfiles(affectedUserId);
                    for (UserInfo profile : profiles) {
                        int profileId = profile.id;
                        if (profileId == affectedUserId) {
                            continue;
                        }
                        Integer profileFeatures = mDevicePolicyEngine.getResolvedPolicy(
                                PolicyDefinition.KEYGUARD_DISABLED_FEATURES,
                                profileId);
                        if (profileFeatures != null) {
                            combinedFeatures |= (profileFeatures
                                    & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
                        }
                    }
                    return combinedFeatures;
                });
            }

            final long ident = mInjector.binderClearCallingIdentity();
            try {
                final List<ActiveAdmin> admins;
                if (!parent && isManagedProfile(userHandle)) {
                    // If we are being asked about a managed profile, just return keyguard features
                    // disabled by admins in the profile.
                    admins = getUserDataUnchecked(userHandle).mAdminList;
                } else {
                    // Otherwise return those set by admins in the user and its profiles.
                    admins = getActiveAdminsForLockscreenPoliciesLocked(
                            getProfileParentUserIfRequested(userHandle, parent));
                }

                int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
                final int N = admins.size();
                for (int i = 0; i < N; i++) {
                    ActiveAdmin admin = admins.get(i);
                    int userId = admin.getUserHandle().getIdentifier();
                    boolean isRequestedUser = !parent && (userId == userHandle);
                    if (isRequestedUser || !isManagedProfile(userId)) {
                        // If we are being asked explicitly about this user
                        // return all disabled features even if its a managed profile.
                        which |= admin.disabledKeyguardFeatures;
                    } else {
                        // Otherwise a managed profile is only allowed to disable
                        // some features on the parent user.
                        which |= (admin.disabledKeyguardFeatures
                                & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
                    }
                }
                return which;
            } finally {
                mInjector.binderRestoreCallingIdentity(ident);
            }
        }
    }

    @Override
    public void setKeepUninstalledPackages(ComponentName who, String callerPackage,
            List<String> packageList) {
        if (!mHasFeature) {
            return;
        }
        Objects.requireNonNull(packageList, "packageList is null");
        final CallerIdentity caller = getCallerIdentity(who, callerPackage);
        Preconditions.checkCallAuthorization((caller.hasAdminComponent()
                &&  isDefaultDeviceOwner(caller))
                || (caller.hasPackage()
                && isCallerDelegate(caller, DELEGATION_KEEP_UNINSTALLED_PACKAGES)));
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_KEEP_UNINSTALLED_PACKAGES);

        synchronized (getLockObject()) {
            // Get the device owner
            ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
            // Set list of packages to be kept even if uninstalled.
            deviceOwner.keepUninstalledPackages = packageList;
            // Save settings.
            saveSettingsLocked(caller.getUserId());
            // Notify package manager.
            mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_KEEP_UNINSTALLED_PACKAGES)
                .setAdmin(caller.getPackageName())
                .setBoolean(/* isDelegate */ who == null)
                .setStrings(packageList.toArray(new String[0]))
                .write();
    }

    @Override
    public List<String> getKeepUninstalledPackages(ComponentName who, String callerPackage) {
        if (!mHasFeature) {
            return null;
        }
        final CallerIdentity caller = getCallerIdentity(who, callerPackage);
        Preconditions.checkCallAuthorization((caller.hasAdminComponent()
                &&  isDefaultDeviceOwner(caller))
                || (caller.hasPackage()
                && isCallerDelegate(caller, DELEGATION_KEEP_UNINSTALLED_PACKAGES)));

        synchronized (getLockObject()) {
            return getKeepUninstalledPackagesLocked();
        }
    }

    private List<String> getKeepUninstalledPackagesLocked() {
        ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
        return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
    }

    /**
     * Logs a warning when the device doesn't have {@code PackageManager.FEATURE_DEVICE_ADMIN}.
     *
     * @param message action that was not executed; should not end with a period because the missing
     * feature will be appended to it.
     */
    private void logMissingFeatureAction(String message) {
        Slogf.w(LOG_TAG, message + " because device does not have the "
                + PackageManager.FEATURE_DEVICE_ADMIN + " feature.");
    }

    @Override
    public boolean setDeviceOwner(ComponentName admin, int userId,
            boolean setProfileOwnerOnCurrentUserIfNecessary) {
        if (!mHasFeature) {
            logMissingFeatureAction("Cannot set " + ComponentName.flattenToShortString(admin)
                    + " as device owner for user " + userId);
            return false;
        }
        Preconditions.checkArgument(admin != null);

        final CallerIdentity caller = getCallerIdentity();

        boolean hasIncompatibleAccountsOrNonAdb =
                !isAdb(caller) || hasIncompatibleAccountsOnAnyUser();

        if (!hasIncompatibleAccountsOrNonAdb) {
            synchronized (getLockObject()) {
                if (!isAdminTestOnlyLocked(admin, userId) && hasAccountsOnAnyUser()) {
                    Slogf.w(LOG_TAG,
                            "Non test-only owner can't be installed with existing accounts.");
                    return false;
                }
            }
        }

        synchronized (getLockObject()) {
            enforceCanSetDeviceOwnerLocked(caller, admin, userId, hasIncompatibleAccountsOrNonAdb);

            Preconditions.checkArgument(isPackageInstalledForUser(admin.getPackageName(), userId),
                    "Invalid component " + admin + " for device owner");
            final ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(admin, userId);
            Preconditions.checkArgument(activeAdmin != null && !getUserData(
                    userId).mRemovingAdmins.contains(admin), "Not active admin: " + admin);

            // Shutting down backup manager service permanently.
            toggleBackupServiceActive(UserHandle.USER_SYSTEM, /* makeActive= */ false);
            if (isAdb(caller)) {
                // Log device owner provisioning was started using adb.
                MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_DEVICE_OWNER);
                DevicePolicyEventLogger
                        .createEvent(DevicePolicyEnums.PROVISIONING_ENTRY_POINT_ADB)
                        .setAdmin(admin)
                        .setStrings(LOG_TAG_DEVICE_OWNER)
                        .write();
            }

            mOwners.setDeviceOwner(admin, userId);
            mOwners.writeDeviceOwner();
            setDeviceOwnershipSystemPropertyLocked();

            //TODO(b/180371154): when provisionFullyManagedDevice is used in tests, remove this
            // hard-coded default value setting.
            if (isAdb(caller)) {
                activeAdmin.mAdminCanGrantSensorsPermissions = true;
                mPolicyCache.setAdminCanGrantSensorsPermissions(true);
                saveSettingsLocked(userId);
            }

            mInjector.binderWithCleanCallingIdentity(() -> {
                // Restrict adding a managed profile when a device owner is set on the device.
                // That is to prevent the co-existence of a managed profile and a device owner
                // on the same device.
                // Instead, the device may be provisioned with an organization-owned managed
                // profile, such that the admin on that managed profile has extended management
                // capabilities that can affect the entire device (but not access private data
                // on the primary profile).
                for (int u : mUserManagerInternal.getUserIds()) {
                    mUserManager.setUserRestriction(
                            UserManager.DISALLOW_ADD_MANAGED_PROFILE, true,
                            UserHandle.of(u));
                    // Restrict adding a clone profile when a device owner is set on the device.
                    // That is to prevent the co-existence of a clone profile and a device owner
                    // on the same device.
                    // CDD for reference : https://source.android.com/compatibility/12/android-12-cdd#95_multi-user_support
                    mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_CLONE_PROFILE,
                            true,
                            UserHandle.of(u));

                    // Restrict adding a private profile when a device owner is set.
                    mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_PRIVATE_PROFILE,
                            true,
                            UserHandle.of(u));
                }

                // TODO Send to system too?
                sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, userId);
            });
            mDeviceAdminServiceController.startServiceForAdmin(
                    admin.getPackageName(), userId, "set-device-owner");

            Slogf.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId);
        }

        if (setProfileOwnerOnCurrentUserIfNecessary
                && mInjector.userManagerIsHeadlessSystemUserMode()) {
            int currentForegroundUser;
            synchronized (getLockObject()) {
                currentForegroundUser = getCurrentForegroundUserId();
            }
            Slogf.i(LOG_TAG, "setDeviceOwner(): setting " + admin
                    + " as profile owner on user " + currentForegroundUser);
            // Sets profile owner on current foreground user since
            // the human user will complete the DO setup workflow from there.
            manageUserUnchecked(/* deviceOwner= */ admin, /* profileOwner= */ admin,
                    /* managedUser= */ currentForegroundUser, /* adminExtras= */ null,
                    /* showDisclaimer= */ false);
        }
        return true;
    }

    /**
     * This API is cached: invalidate with invalidateBinderCaches().
     */
    @Override
    public boolean hasDeviceOwner() {
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || canManageUsers(caller) || isFinancedDeviceOwner(
                        caller) || hasCallingOrSelfPermission(
                        MANAGE_PROFILE_AND_DEVICE_OWNERS));
        return mOwners.hasDeviceOwner();
    }

    boolean isDeviceOwner(ActiveAdmin admin) {
        return isDeviceOwner(admin.info.getComponent(), admin.getUserHandle().getIdentifier());
    }

    /**
     * Check if the user is a Device Owner
     *
     * @param who    component to check against
     * @param userId user to check
     * @return if the user is a Device Owner
     */
    public boolean isDeviceOwner(@Nullable ComponentName who, int userId) {
        synchronized (getLockObject()) {
            return mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userId
                    && mOwners.getDeviceOwnerComponent().equals(who);
        }
    }

    /**
     * Returns {@code true} <b>only if</b> the caller is the device owner and the device owner type
     * is {@link DevicePolicyManager#DEVICE_OWNER_TYPE_DEFAULT}. {@code false} is returned for the
     * case where the caller is not the device owner, there is no device owner, or the device owner
     * type is not {@link DevicePolicyManager#DEVICE_OWNER_TYPE_DEFAULT}.
     *
     */
    private boolean isDefaultDeviceOwner(CallerIdentity caller) {
        synchronized (getLockObject()) {
            return isDeviceOwnerLocked(caller) && getDeviceOwnerTypeLocked(
                    mOwners.getDeviceOwnerPackageName()) == DEVICE_OWNER_TYPE_DEFAULT;
        }
    }

    /**
     * Returns {@code true} if the provided caller identity is of a device owner.
     * @param caller identity of caller.
     * @return true if {@code identity} is a device owner, false otherwise.
     */
    public boolean isDeviceOwner(CallerIdentity caller) {
        synchronized (getLockObject()) {
            return isDeviceOwnerLocked(caller);
        }
    }

    private boolean isDeviceOwnerLocked(CallerIdentity caller) {
        if (!mOwners.hasDeviceOwner() || mOwners.getDeviceOwnerUserId() != caller.getUserId()) {
            return false;
        }

        if (caller.hasAdminComponent()) {
            return mOwners.getDeviceOwnerComponent().equals(caller.getComponentName());
        } else {
            return isUidDeviceOwnerLocked(caller.getUid());
        }
    }

    private boolean isDeviceOwnerUserId(int userId) {
        synchronized (getLockObject()) {
            return mOwners.getDeviceOwnerComponent() != null
                    && mOwners.getDeviceOwnerUserId() == userId;
        }
    }

    /**
     * Check if {@link userId} is a Profile Owner
     *
     * @param who    component to check against
     * @param userId user to check
     * @return if the user is a Profile Owner
     */
    public boolean isProfileOwner(@Nullable ComponentName who, int userId) {
        final ComponentName profileOwner = mInjector.binderWithCleanCallingIdentity(
                () -> getProfileOwnerAsUser(userId));
        return who != null && who.equals(profileOwner);
    }

    /**
     * Returns {@code true} if the provided caller identity is of a profile owner.
     * @param caller identity of caller.
     * @return true if {@code identity} is a profile owner, false otherwise.
     */
    public boolean isProfileOwner(CallerIdentity caller) {
        synchronized (getLockObject()) {
            final ComponentName profileOwner = mInjector.binderWithCleanCallingIdentity(() ->
                    getProfileOwnerAsUser(caller.getUserId()));
            // No profile owner.
            if (profileOwner == null) {
                return false;
            }
            // The admin ComponentName was specified, check it directly.
            if (caller.hasAdminComponent()) {
                return profileOwner.equals(caller.getComponentName());
            } else {
                return isUidProfileOwnerLocked(caller.getUid());
            }
        }
    }

    /**
     * Checks if the app uid provided is the profile owner. This method should only be called
     * if no componentName is available.
     *
     * @param appUid UID of the caller.
     * @return true if the caller is the profile owner
     */
    private boolean isUidProfileOwnerLocked(int appUid) {
        ensureLocked();

        final int userId = UserHandle.getUserId(appUid);
        final ComponentName profileOwnerComponent = mOwners.getProfileOwnerComponent(userId);
        if (profileOwnerComponent == null) {
            return false;
        }
        for (ActiveAdmin admin : getUserData(userId).mAdminList) {
            final ComponentName currentAdminComponent = admin.info.getComponent();
            if (admin.getUid() == appUid && profileOwnerComponent.equals(currentAdminComponent)) {
                return true;
            }
        }
        return false;
    }

    private boolean hasProfileOwner(int userId) {
        synchronized (getLockObject()) {
            return mOwners.hasProfileOwner(userId);
        }
    }

    /**
     * Returns {@code true} if the provided caller identity is of a profile owner of an organization
     * owned device.
     *
     * @param caller identity of caller
     * @return true if {@code identity} is a profile owner of an organization owned device, false
     * otherwise.
     */
    private boolean isProfileOwnerOfOrganizationOwnedDevice(CallerIdentity caller) {
        return isProfileOwner(caller) && isProfileOwnerOfOrganizationOwnedDevice(
                caller.getUserId());
    }

    private boolean isProfileOwnerOfOrganizationOwnedDevice(int userId) {
        synchronized (getLockObject()) {
            return mOwners.isProfileOwnerOfOrganizationOwnedDevice(userId);
        }
    }

    private boolean isProfileOwnerOfOrganizationOwnedDevice(ComponentName who, int userId) {
        return isProfileOwner(who, userId) && isProfileOwnerOfOrganizationOwnedDevice(userId);
    }

    private boolean isProfileOwnerOnUser0(CallerIdentity caller) {
        return isProfileOwner(caller) && caller.getUserHandle().isSystem();
    }

    private boolean isPackage(CallerIdentity caller, String packageName) {
        return isCallingFromPackage(packageName, caller.getUid());
    }

    @Override
    public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
        if (!mHasFeature) {
            return null;
        }
        if (!callingUserOnly) {
            Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())
                    || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
        }
        synchronized (getLockObject()) {
            if (!mOwners.hasDeviceOwner()) {
                return null;
            }
            if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
                    mOwners.getDeviceOwnerUserId()) {
                return null;
            }
            return mOwners.getDeviceOwnerComponent();
        }
    }

    @Override
    public ComponentName getDeviceOwnerComponentOnUser(int userId) {
        if (!mHasFeature) {
            return null;
        }
        if (mInjector.userHandleGetCallingUserId() != userId) {
            Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())
                    || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
        }
        synchronized (getLockObject()) {
            // There is only ever one device owner on a device so if the passed userId is the same
            // as the device owner userId we know that the componentName returned by
            // getDeviceOwnerComponent will be the correct one.
            if (mOwners.getDeviceOwnerUserId() == userId || userId == UserHandle.USER_ALL) {
                return mOwners.getDeviceOwnerComponent();
            }
        }
        return null;
    }

    private int getDeviceOwnerUserIdUncheckedLocked() {
        return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
    }

    @Override
    public int getDeviceOwnerUserId() {
        if (!mHasFeature) {
            return UserHandle.USER_NULL;
        }
        Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));

        synchronized (getLockObject()) {
            return getDeviceOwnerUserIdUncheckedLocked();
        }
    }

    private @UserIdInt int getMainUserId() {
        int mainUserId = mUserManagerInternal.getMainUserId();
        if (mainUserId == UserHandle.USER_NULL) {
            Slogf.d(LOG_TAG, "getMainUserId(): no main user, returning USER_SYSTEM");
            return UserHandle.USER_SYSTEM;
        }
        return mainUserId;
    }

    // TODO(b/240562946): Remove api as owner name is not used.
    /**
     * Returns the "name" of the device owner.  It'll work for non-DO users too, but requires
     * MANAGE_USERS.
     */
    @Override
    public String getDeviceOwnerName() {
        if (!mHasFeature) {
            return null;
        }
        Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())
                || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));

        synchronized (getLockObject()) {
            if (!mOwners.hasDeviceOwner()) {
                return null;
            }
            // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
            // Should setDeviceOwner/ProfileOwner still take a name?
            String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
            return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
        }
    }

    /** Returns the active device owner or {@code null} if there is no device owner. */
    @VisibleForTesting
    ActiveAdmin getDeviceOwnerAdminLocked() {
        ensureLocked();
        ComponentName component = mOwners.getDeviceOwnerComponent();
        if (component == null) {
            return null;
        }

        DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
        final int n = policy.mAdminList.size();
        for (int i = 0; i < n; i++) {
            ActiveAdmin admin = policy.mAdminList.get(i);
            if (component.equals(admin.info.getComponent())) {
                return admin;
            }
        }
        Slogf.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
        return null;
    }

    /**
     * @deprecated Use the version which does not take a user id.
     */
    @Deprecated
    ActiveAdmin getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked(int userId) {
        ensureLocked();
        ActiveAdmin admin = getDeviceOwnerAdminLocked();
        if (admin == null) {
            admin = getProfileOwnerOfOrganizationOwnedDeviceLocked(userId);
        }
        return admin;
    }

    ActiveAdmin getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked() {
        ensureLocked();
        ActiveAdmin admin = getDeviceOwnerAdminLocked();
        if (admin == null) {
            admin = getProfileOwnerOfOrganizationOwnedDeviceLocked();
        }
        return admin;
    }

    ActiveAdmin getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceOrSystemPermissionBasedAdminLocked() {
        ensureLocked();
        ActiveAdmin doOrPo = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
        if (isPermissionCheckFlagEnabled() && doOrPo == null) {
            return getUserData(0).mPermissionBasedAdmin;
        }
        return doOrPo;
    }

    ActiveAdmin getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceParentLocked(int userId) {
        ensureLocked();
        ActiveAdmin admin = getDeviceOwnerAdminLocked();
        if (admin != null) {
            return admin;
        }
        admin = getProfileOwnerOfOrganizationOwnedDeviceLocked(userId);
        return admin != null ? admin.getParentActiveAdmin() : null;
    }

    @Override
    public void clearDeviceOwner(String packageName) {
        Objects.requireNonNull(packageName, "packageName is null");

        final CallerIdentity caller = getCallerIdentity(packageName);
        synchronized (getLockObject()) {
            final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
            final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
            if (!mOwners.hasDeviceOwner()
                    || !deviceOwnerComponent.getPackageName().equals(packageName)
                    || (deviceOwnerUserId != caller.getUserId())) {
                throw new SecurityException(
                        "clearDeviceOwner can only be called by the device owner");
            }
            enforceUserUnlocked(deviceOwnerUserId);

            final ActiveAdmin admin = getDeviceOwnerAdminLocked();
            mInjector.binderWithCleanCallingIdentity(() -> {
                clearDeviceOwnerLocked(admin, deviceOwnerUserId);
                removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
                sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED,
                        deviceOwnerUserId);
            });
            Slogf.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent);
        }
    }

    private void clearOverrideApnUnchecked() {
        if (!mHasTelephonyFeature) {
            return;
        }
        // Disable Override APNs and remove them from database.
        setOverrideApnsEnabledUnchecked(false);
        final List<ApnSetting> apns = getOverrideApnsUnchecked();
        for (int i = 0; i < apns.size(); i ++) {
            removeOverrideApnUnchecked(apns.get(i).getId());
        }
    }

    private void clearManagedProfileApnUnchecked() {
        if (!mHasTelephonyFeature) {
            return;
        }
        if (!LocalServices.getService(SystemServiceManager.class).isBootCompleted()) {
            Slogf.i(LOG_TAG, "Skip clearing managed profile Apn before boot completed");
            // Cannot talk to APN content provider before system boots
            // Ideally we should delay the cleanup post boot_completed, not just
            // skipping  it altogether.
            return;
        }
        final List<ApnSetting> apns = getOverrideApnsUnchecked();
        for (ApnSetting apn : apns) {
            if (apn.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) {
                removeOverrideApnUnchecked(apn.getId());
            }
        }
    }

    private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
        String ownersPackage = mOwners.getDeviceOwnerPackageName();
        if (ownersPackage != null) {
            mDeviceAdminServiceController.stopServiceForAdmin(
                    ownersPackage, userId, "clear-device-owner");
        }

        if (admin != null) {
            admin.disableCamera = false;
            admin.userRestrictions = null;
            admin.defaultEnabledRestrictionsAlreadySet.clear();
            admin.forceEphemeralUsers = false;
            admin.isNetworkLoggingEnabled = false;
            admin.requireAutoTime = false;
            mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
        }
        final DevicePolicyData policyData = getUserData(userId);
        policyData.mCurrentInputMethodSet = false;
        if (policyData.mPasswordTokenHandle != 0) {
            mLockPatternUtils.removeEscrowToken(policyData.mPasswordTokenHandle, userId);
            policyData.mPasswordTokenHandle = 0;
        }
        saveSettingsLocked(userId);
        mPolicyCache.onUserRemoved(userId);
        final DevicePolicyData systemPolicyData = getUserData(UserHandle.USER_SYSTEM);
        systemPolicyData.mLastSecurityLogRetrievalTime = -1;
        systemPolicyData.mLastBugReportRequestTime = -1;
        systemPolicyData.mLastNetworkLogsRetrievalTime = -1;
        saveSettingsLocked(UserHandle.USER_SYSTEM);
        clearUserPoliciesLocked(userId);
        clearOverrideApnUnchecked();
        clearApplicationRestrictions(userId);

        mOwners.clearDeviceOwner();
        mOwners.writeDeviceOwner();

        updateAdminCanGrantSensorsPermissionCache(userId);
        clearDeviceOwnerUserRestriction(UserHandle.of(userId));
        mInjector.securityLogSetLoggingEnabledProperty(false);
        mSecurityLogMonitor.stop();
        setNetworkLoggingActiveInternal(false);
        deleteTransferOwnershipBundleLocked(userId);
        toggleBackupServiceActive(UserHandle.USER_SYSTEM, true);
        setGlobalSettingDeviceOwnerType(DEVICE_OWNER_TYPE_DEFAULT);

        mDevicePolicyEngine.removePoliciesForAdmin(
                EnforcingAdmin.createEnterpriseEnforcingAdmin(
                        admin.info.getComponent(), userId, admin));
    }

    private void clearApplicationRestrictions(int userId) {
        // Changing app restrictions involves disk IO, offload it to the background thread.
        mBackgroundHandler.post(() -> {
            final List<PackageInfo> installedPackageInfos = mInjector.getPackageManager(userId)
                    .getInstalledPackages(MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE);
            final UserHandle userHandle = UserHandle.of(userId);
            for (final PackageInfo packageInfo : installedPackageInfos) {
                mInjector.getUserManager().setApplicationRestrictions(
                        packageInfo.packageName, null /* restrictions */, userHandle);
            }
        });
    }

    @Override
    public boolean setProfileOwner(ComponentName who, int userHandle) {
        if (!mHasFeature) {
            logMissingFeatureAction("Cannot set " + ComponentName.flattenToShortString(who)
                    + " as profile owner for user " + userHandle);
            return false;
        }
        Preconditions.checkArgument(who != null);

        final CallerIdentity caller = getCallerIdentity();
        // Cannot be called while holding the lock:
        final boolean hasIncompatibleAccountsOrNonAdb =
                hasIncompatibleAccountsOrNonAdbNoLock(caller, userHandle, who);
        synchronized (getLockObject()) {
            enforceCanSetProfileOwnerLocked(
                    caller, who, userHandle, hasIncompatibleAccountsOrNonAdb);
            final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
            Preconditions.checkArgument(
                    isPackageInstalledForUser(who.getPackageName(), userHandle)
                            && admin != null
                            && !getUserData(userHandle).mRemovingAdmins.contains(who),
                    "Not active admin: " + who);

            final int parentUserId = getProfileParentId(userHandle);
            // When trying to set a profile owner on a new user, it may be that this user is
            // a profile - but it may not be a managed profile if there's a restriction on the
            // parent to add managed profiles (e.g. if the device has a device owner).
            if (parentUserId != userHandle && mUserManager.hasUserRestriction(
                    UserManager.DISALLOW_ADD_MANAGED_PROFILE,
                    UserHandle.of(parentUserId))) {
                Slogf.i(LOG_TAG, "Cannot set profile owner because of restriction.");
                return false;
            }

            if (isAdb(caller)) {
                // Log profile owner provisioning was started using adb.
                MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER);
                DevicePolicyEventLogger
                        .createEvent(DevicePolicyEnums.PROVISIONING_ENTRY_POINT_ADB)
                        .setAdmin(who)
                        .setStrings(LOG_TAG_PROFILE_OWNER)
                        .write();
            }

            // Shutting down backup manager service permanently.
            toggleBackupServiceActive(userHandle, /* makeActive= */ false);

            mOwners.setProfileOwner(who, userHandle);
            mOwners.writeProfileOwner(userHandle);
            Slogf.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);

            mInjector.binderWithCleanCallingIdentity(() -> {
                if (mUserManager.isManagedProfile(userHandle)) {
                    maybeSetDefaultRestrictionsForAdminLocked(userHandle, admin);
                    ensureUnknownSourcesRestrictionForProfileOwnerLocked(userHandle, admin,
                            true /* newOwner */);
                }
                sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED,
                        userHandle);
            });
            mDeviceAdminServiceController.startServiceForAdmin(
                    who.getPackageName(), userHandle, "set-profile-owner");
            return true;
        }
    }

    private void toggleBackupServiceActive(int userId, boolean makeActive) {
        long ident = mInjector.binderClearCallingIdentity();
        try {
            if (mInjector.getIBackupManager() != null) {
                mInjector.getIBackupManager()
                        .setBackupServiceActive(userId, makeActive);
            }
        } catch (RemoteException e) {
            throw new IllegalStateException(String.format("Failed %s backup service.",
                    makeActive ? "activating" : "deactivating"), e);
        } finally {
            mInjector.binderRestoreCallingIdentity(ident);
        }

    }

    @Override
    public void clearProfileOwner(ComponentName who) {
        if (!mHasFeature) {
            return;
        }
        Objects.requireNonNull(who, "ComponentName is null");

        final CallerIdentity caller = getCallerIdentity(who);
        final int userId = caller.getUserId();
        Preconditions.checkCallingUser(!isManagedProfile(userId));
        Preconditions.checkCallAuthorization(isProfileOwner(caller));

        enforceUserUnlocked(userId);
        synchronized (getLockObject()) {
            final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());

            mInjector.binderWithCleanCallingIdentity(() -> {
                clearProfileOwnerLocked(admin, userId);
                removeActiveAdminLocked(who, userId);
                sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED,
                        userId);
            });
            Slogf.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
        }
    }

    public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
        String ownersPackage = mOwners.getProfileOwnerPackage(userId);
        if (ownersPackage != null) {
            mDeviceAdminServiceController.stopServiceForAdmin(
                    ownersPackage, userId, "clear-profile-owner");
        }

        if (admin != null) {
            admin.disableCamera = false;
            admin.userRestrictions = null;
            admin.defaultEnabledRestrictionsAlreadySet.clear();
        }
        final DevicePolicyData policyData = getUserData(userId);
        policyData.mCurrentInputMethodSet = false;
        policyData.mOwnerInstalledCaCerts.clear();
        saveSettingsLocked(userId);
        clearUserPoliciesLocked(userId);
        clearApplicationRestrictions(userId);
        mOwners.removeProfileOwner(userId);
        mOwners.writeProfileOwner(userId);
        deleteTransferOwnershipBundleLocked(userId);
        toggleBackupServiceActive(userId, true);
        applyProfileRestrictionsIfDeviceOwnerLocked();
        setNetworkLoggingActiveInternal(false);

        mDevicePolicyEngine.removePoliciesForAdmin(
                EnforcingAdmin.createEnterpriseEnforcingAdmin(
                        admin.info.getComponent(), userId, admin));
    }

    @Override
    public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
        if (!mHasFeature) {
            return;
        }
        Objects.requireNonNull(who, "ComponentName is null");

        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller));

        mInjector.binderWithCleanCallingIdentity(() ->
                mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null));

        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_DEVICE_OWNER_LOCK_SCREEN_INFO)
                .setAdmin(caller.getComponentName())
                .write();
    }

    @Override
    public CharSequence getDeviceOwnerLockScreenInfo() {
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller));
        return mInjector.binderWithCleanCallingIdentity(() ->
            mLockPatternUtils.getDeviceOwnerInfo());
    }

    private void clearUserPoliciesLocked(int userId) {
        // Reset some of the user-specific policies.
        final DevicePolicyData policy = getUserData(userId);
        policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
        // Clear delegations.
        policy.mDelegationMap.clear();
        policy.mStatusBarDisabled = false;
        policy.mSecondaryLockscreenEnabled = false;
        policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
        policy.mAffiliationIds.clear();
        resetAffiliationCacheLocked();
        policy.mLockTaskPackages.clear();
        policy.mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_NONE;
        saveSettingsLocked(userId);

        try {
            mIPermissionManager.updatePermissionFlagsForAllApps(
                    PackageManager.FLAG_PERMISSION_POLICY_FIXED,
                    0  /* flagValues */, userId);
        } catch (RemoteException re) {
            // Shouldn't happen.
            Slogf.wtf(LOG_TAG, "Failing in updatePermissionFlagsForAllApps", re);
        }
    }

    @Override
    public boolean hasUserSetupCompleted() {
        return hasUserSetupCompleted(mInjector.userHandleGetCallingUserId());
    }

    // This checks only if the Setup Wizard has run.  Since Wear devices pair before
    // completing Setup Wizard, and pairing involves transferring user data, calling
    // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted().
    private boolean hasUserSetupCompleted(int userHandle) {
        if (!mHasFeature) {
            return true;
        }
        return mInjector.hasUserSetupCompleted(getUserData(userHandle));
    }

    private boolean hasPaired(int userHandle) {
        if (!mHasFeature) {
            return true;
        }
        return getUserData(userHandle).mPaired;
    }

    @Override
    public int getUserProvisioningState(int userHandle) {
        if (!mHasFeature) {
            return DevicePolicyManager.STATE_USER_UNMANAGED;
        }
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(canManageUsers(caller)
                || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));

        if (userHandle != caller.getUserId()) {
            Preconditions.checkCallAuthorization(canManageUsers(caller)
                    || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS));
        }

        return getUserData(userHandle).mUserProvisioningState;
    }

    @Override
    public void setUserProvisioningState(int newState, int userId) {
        if (!mHasFeature) {
            logMissingFeatureAction("Cannot set provisioning state " + newState + " for user "
                    + userId);
            return;
        }
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));

        final CallerIdentity caller = getCallerIdentity();
        final long id = mInjector.binderClearCallingIdentity();
        try {
            int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
            // NOTE: multiple if statements are nested below so it can log more info on error
            if (userId != deviceOwnerUserId) {
                boolean hasProfileOwner = mOwners.hasProfileOwner(userId);
                if (!hasProfileOwner) {
                    int managedUserId = getManagedUserId(userId);
                    if (managedUserId < 0 && newState != STATE_USER_UNMANAGED) {
                        // No managed device, user or profile, so setting provisioning state makes
                        // no sense.
                        String error = "Not allowed to change provisioning state unless a "
                                + "device or profile owner is set.";
                        Slogf.w(LOG_TAG, "setUserProvisioningState(newState=%d, userId=%d) failed: "
                                + "deviceOwnerId=%d, hasProfileOwner=%b, managedUserId=%d, err=%s",
                                newState, userId, deviceOwnerUserId, hasProfileOwner,
                                managedUserId, error);
                        throw new IllegalStateException(error);
                    }
                }
            }

            synchronized (getLockObject()) {
                boolean transitionCheckNeeded = true;

                // Calling identity/permission checks.
                if (isAdb(caller)) {
                    // ADB shell can only move directly from un-managed to finalized as part of
                    // directly setting profile-owner or device-owner.
                    if (getUserProvisioningState(userId)
                            != DevicePolicyManager.STATE_USER_UNMANAGED
                            || newState != STATE_USER_SETUP_FINALIZED) {
                        throw new IllegalStateException("Not allowed to change provisioning state "
                                + "unless current provisioning state is unmanaged, and new state"
                                + "is finalized.");
                    }
                    transitionCheckNeeded = false;
                }

                final DevicePolicyData policyData = getUserData(userId);
                if (transitionCheckNeeded) {
                    // Optional state transition check for non-ADB case.
                    checkUserProvisioningStateTransition(policyData.mUserProvisioningState,
                            newState);
                }
                policyData.mUserProvisioningState = newState;
                saveSettingsLocked(userId);
            }
        } finally {
            mInjector.binderRestoreCallingIdentity(id);
        }
    }

    private void checkUserProvisioningStateTransition(int currentState, int newState) {
        // Valid transitions for normal use-cases.
        switch (currentState) {
            case DevicePolicyManager.STATE_USER_UNMANAGED:
                // Can move to any state from unmanaged (except itself as an edge case)..
                if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
                    return;
                }
                break;
            case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
            case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
                // Can only move to finalized from these states.
                if (newState == STATE_USER_SETUP_FINALIZED) {
                    return;
                }
                break;
            case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
                // Current user has a managed-profile, but current user is not managed, so
                // rather than moving to finalized state, go back to unmanaged once
                // profile provisioning is complete.
                if (newState == DevicePolicyManager.STATE_USER_PROFILE_FINALIZED) {
                    return;
                }
                break;
            case STATE_USER_SETUP_FINALIZED:
                // Cannot transition out of finalized.
                break;
            case DevicePolicyManager.STATE_USER_PROFILE_FINALIZED:
                // Should only move to an unmanaged state after removing the work profile.
                if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
                    return;
                }
                break;
        }

        // Didn't meet any of the accepted state transition checks above, throw appropriate error.
        throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
                + "from state [" + currentState + "]");
    }

    @Override
    public void setProfileEnabled(ComponentName who) {
        if (!mHasFeature) {
            logMissingFeatureAction("Cannot enable profile for "
                    + ComponentName.flattenToShortString(who));
            return;
        }
        Objects.requireNonNull(who, "ComponentName is null");

        final CallerIdentity caller = getCallerIdentity(who);
        final int userId = caller.getUserId();
        Preconditions.checkCallAuthorization(
                isProfileOwner(caller) || isDefaultDeviceOwner(caller));
        Preconditions.checkCallingUser(isManagedProfile(userId));

        synchronized (getLockObject()) {
            // Check if the profile is already enabled.
            UserInfo managedProfile = getUserInfo(userId);
            if (managedProfile.isEnabled()) {
                Slogf.e(LOG_TAG,
                        "setProfileEnabled is called when the profile is already enabled");
                return;
            }
            mInjector.binderWithCleanCallingIdentity(() -> {
                mUserManager.setUserEnabled(userId);
                UserInfo parent = mUserManager.getProfileParent(userId);
                Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
                intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
                UserHandle parentHandle = new UserHandle(parent.id);
                mLocalService.broadcastIntentToManifestReceivers(intent,
                        parentHandle, /* requiresPermission= */ true);
                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
                        Intent.FLAG_RECEIVER_FOREGROUND);
                mContext.sendBroadcastAsUser(intent, parentHandle);
            });
        }
    }

    @Override
    public void setProfileName(ComponentName who, String profileName) {
        Objects.requireNonNull(who, "ComponentName is null");

        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || isProfileOwner(caller));

        final String truncatedProfileName =
                profileName.substring(0, Math.min(profileName.length(), MAX_PROFILE_NAME_LENGTH));
        mInjector.binderWithCleanCallingIdentity(() -> {
            mUserManager.setUserName(caller.getUserId(), truncatedProfileName);
            DevicePolicyEventLogger
                    .createEvent(DevicePolicyEnums.SET_PROFILE_NAME)
                    .setAdmin(caller.getComponentName())
                    .write();
        });
    }

    @Override
    public ComponentName getProfileOwnerAsUser(int userId) {
        if (!mHasFeature) {
            return null;
        }
        Preconditions.checkArgumentNonnegative(userId, "Invalid userId");

        CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId)
                || hasFullCrossUsersPermission(caller, userId));

        synchronized (getLockObject()) {
            return mOwners.getProfileOwnerComponent(userId);
        }
    }

    // Returns the active profile owner for this user or null if the current user has no
    // profile owner.
    @VisibleForTesting
    ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
        ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
        if (profileOwner == null) {
            return null;
        }
        DevicePolicyData policy = getUserData(userHandle);
        final int n = policy.mAdminList.size();
        for (int i = 0; i < n; i++) {
            ActiveAdmin admin = policy.mAdminList.get(i);
            if (profileOwner.equals(admin.info.getComponent())) {
                return admin;
            }
        }
        return null;
    }

    /**
     * Returns the ActiveAdmin associated with the PO or DO on the given user.
     */
    private @Nullable ActiveAdmin getDeviceOrProfileOwnerAdminLocked(int userHandle) {
        ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
        if (admin == null && getDeviceOwnerUserIdUncheckedLocked() == userHandle) {
            admin = getDeviceOwnerAdminLocked();
        }
        return admin;
    }

    @GuardedBy("getLockObject()")
    ActiveAdmin getProfileOwnerOfOrganizationOwnedDeviceLocked(int userHandle) {
        return mInjector.binderWithCleanCallingIdentity(() -> {
            for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
                if (userInfo.isManagedProfile()) {
                    if (getProfileOwnerAsUser(userInfo.id) != null
                            && isProfileOwnerOfOrganizationOwnedDevice(userInfo.id)) {
                        ComponentName who = getProfileOwnerAsUser(userInfo.id);
                        return getActiveAdminUncheckedLocked(who, userInfo.id);
                    }
                }
            }
            return null;
        });
    }

    @GuardedBy("getLockObject()")
    ActiveAdmin getProfileOwnerOfOrganizationOwnedDeviceLocked() {
        return mInjector.binderWithCleanCallingIdentity(() -> {
            for (UserInfo userInfo : mUserManager.getUsers()) {
                if (userInfo.isManagedProfile()) {
                    if (getProfileOwnerAsUser(userInfo.id) != null
                            && isProfileOwnerOfOrganizationOwnedDevice(userInfo.id)) {
                        ComponentName who = getProfileOwnerAsUser(userInfo.id);
                        return getActiveAdminUncheckedLocked(who, userInfo.id);
                    }
                }
            }
            return null;
        });
    }

    /**
     * This API is cached: invalidate with invalidateBinderCaches().
     */
    @Override
    public @Nullable ComponentName getProfileOwnerOrDeviceOwnerSupervisionComponent(
            @NonNull UserHandle userHandle) {
        if (!mHasFeature) {
            return null;
        }
        synchronized (getLockObject()) {
            final ComponentName doComponent = mOwners.getDeviceOwnerComponent();
            final ComponentName poComponent =
                    mOwners.getProfileOwnerComponent(userHandle.getIdentifier());
            // Return test only admin if configured to do so.
            // TODO(b/182994391): Replace with more generic solution to override the supervision
            // component.
            if (mConstants.USE_TEST_ADMIN_AS_SUPERVISION_COMPONENT) {
                if (isAdminTestOnlyLocked(doComponent, userHandle.getIdentifier())) {
                    return doComponent;
                } else if (isAdminTestOnlyLocked(poComponent, userHandle.getIdentifier())) {
                    return poComponent;
                }
            }

            // Check profile owner first as that is what most likely is set.
            if (isSupervisionComponentLocked(poComponent)) {
                return poComponent;
            }

            if (isSupervisionComponentLocked(doComponent)) {
                return doComponent;
            }

            return null;
        }
    }

    /**
     * Returns if the specified component is the supervision component.
     */
    @Override
    public boolean isSupervisionComponent(@NonNull ComponentName who) {
        if (!mHasFeature) {
            return false;
        }
        synchronized (getLockObject()) {
            if (mConstants.USE_TEST_ADMIN_AS_SUPERVISION_COMPONENT) {
                final CallerIdentity caller = getCallerIdentity();
                if (isAdminTestOnlyLocked(who, caller.getUserId())) {
                    return true;
                }
            }
            return isSupervisionComponentLocked(who);
        }
    }

    private boolean isSupervisionComponentLocked(@Nullable ComponentName who) {
        if (who == null) {
            return false;
        }

        final String configComponent = mContext.getResources().getString(
                com.android.internal.R.string.config_defaultSupervisionProfileOwnerComponent);
        if (configComponent != null) {
            final ComponentName componentName = ComponentName.unflattenFromString(configComponent);
            if (who.equals(componentName)) {
                return true;
            }
        }

        // Check the system supervision role.
        final String configPackage = mContext.getResources().getString(
                com.android.internal.R.string.config_systemSupervision);

        return who.getPackageName().equals(configPackage);
    }

    // TODO(b/240562946): Remove api as owner name is not used.
    @Override
    public String getProfileOwnerName(int userHandle) {
        if (!mHasFeature) {
            return null;
        }
        Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())
                || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
        return getProfileOwnerNameUnchecked(userHandle);
    }

    private String getProfileOwnerNameUnchecked(int userHandle) {
        ComponentName profileOwner = getProfileOwnerAsUser(userHandle);
        if (profileOwner == null) {
            return null;
        }
        return getApplicationLabel(profileOwner.getPackageName(), userHandle);
    }

    private @UserIdInt int getOrganizationOwnedProfileUserId() {
        for (UserInfo ui : mUserManagerInternal.getUserInfos()) {
            if (ui.isManagedProfile() && isProfileOwnerOfOrganizationOwnedDevice(ui.id)) {
                return ui.id;
            }
        }
        return UserHandle.USER_NULL;
    }

    /**
     * This API is cached: invalidate with invalidateBinderCaches().
     */
    @Override
    public boolean isOrganizationOwnedDeviceWithManagedProfile() {
        if (!mHasFeature) {
            return false;
        }
        return getOrganizationOwnedProfileUserId() != UserHandle.USER_NULL;
    }

    @Override
    public boolean checkDeviceIdentifierAccess(String packageName, int pid, int uid) {
        final CallerIdentity caller = getCallerIdentity();
        ensureCallerIdentityMatchesIfNotSystem(packageName, pid, uid, caller);

        // Verify that the specified packages matches the provided uid.
        if (!doesPackageMatchUid(packageName, uid)) {
            return false;
        }
        // A device or profile owner must also have the READ_PHONE_STATE permission to access device
        // identifiers. If the package being checked does not have this permission then deny access.
        if (!hasPermission(permission.READ_PHONE_STATE, pid, uid)) {
            return false;
        }
        return hasDeviceIdAccessUnchecked(packageName, uid);
    }

    /**
     * Check if one the following conditions hold:
     * (1) The device has a Device Owner, and one of the following holds:
     *   (1.1) The caller is the Device Owner
     *   (1.2) The caller is another app in the same user as the device owner, AND
     *         The caller is the delegated certificate installer.
     *   (1.3) The caller is a Profile Owner and the calling user is affiliated.
     * (2) The user has a profile owner, AND:
     *   (2.1) The profile owner has been granted access to Device IDs and one of the following
     *         holds:
     *     (2.1.1) The caller is the profile owner.
     *     (2.1.2) The caller is from another app in the same user as the profile owner, AND
     *             the caller is the delegated cert installer.
     * (3) The caller holds the
     * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission.
     *
     *  For the device owner case, simply check that the caller is the device owner or the
     *  delegated certificate installer.
     *
     *  For the profile owner case, first check that the caller is the profile owner or can
     *  manage the DELEGATION_CERT_INSTALL scope.
     *  If that check succeeds, ensure the profile owner was granted access to device
     *  identifiers. The grant is transitive: The delegated cert installer is implicitly allowed
     *  access to device identifiers in this case as part of the delegation.
     */
    @VisibleForTesting
    boolean hasDeviceIdAccessUnchecked(String packageName, int uid) {
        final int userId = UserHandle.getUserId(uid);
        // TODO(b/280048070): Introduce a permission to handle device ID access
        if (isPermissionCheckFlagEnabled()
                && !(isUidProfileOwnerLocked(uid) || isUidDeviceOwnerLocked(uid))) {
            return hasPermission(MANAGE_DEVICE_POLICY_CERTIFICATES, packageName, userId);
        } else {
            ComponentName deviceOwner = getDeviceOwnerComponent(true);
            if (deviceOwner != null && (deviceOwner.getPackageName().equals(packageName)
                    || isCallerDelegate(packageName, uid, DELEGATION_CERT_INSTALL))) {
                return true;
            }
            ComponentName profileOwner = getProfileOwnerAsUser(userId);
            final boolean isCallerProfileOwnerOrDelegate = profileOwner != null
                    && (profileOwner.getPackageName().equals(packageName)
                    || isCallerDelegate(packageName, uid, DELEGATION_CERT_INSTALL));
            if (isCallerProfileOwnerOrDelegate && (isProfileOwnerOfOrganizationOwnedDevice(userId)
                    || isUserAffiliatedWithDevice(userId))) {
                return true;
            }
        }
        return false;
    }

    private boolean doesPackageMatchUid(String packageName, int uid) {
        final int userId = UserHandle.getUserId(uid);
        try {
            ApplicationInfo appInfo = mIPackageManager.getApplicationInfo(packageName, 0, userId);
            // Since this call goes directly to PackageManagerService a NameNotFoundException is not
            // thrown but null data can be returned; if the appInfo for the specified package cannot
            // be found then return false to prevent crashing the app.
            if (appInfo == null) {
                Slogf.w(LOG_TAG, "appInfo could not be found for package %s", packageName);
                return false;
            } else if (uid != appInfo.uid) {
                String message = String.format("Package %s (uid=%d) does not match provided uid %d",
                        packageName, appInfo.uid, uid);
                Slogf.w(LOG_TAG, message);
                throw new SecurityException(message);
            }
        } catch (RemoteException e) {
            // If an exception is caught obtaining the appInfo just return false to prevent crashing
            // apps due to an internal error.
            Slogf.e(LOG_TAG, e, "Exception caught obtaining appInfo for package %s", packageName);
            return false;
        }
        return true;
    }

    private void ensureCallerIdentityMatchesIfNotSystem(String packageName, int pid, int uid,
            CallerIdentity caller) {
        // If the caller is not a system app then it should only be able to check its own device
        // identifier access.
        int callingUid = caller.getUid();
        int callingPid = mInjector.binderGetCallingPid();
        if (UserHandle.getAppId(callingUid) >= Process.FIRST_APPLICATION_UID
                && (callingUid != uid || callingPid != pid)) {
            String message = String.format(
                    "Calling uid %d, pid %d cannot check device identifier access for package %s "
                            + "(uid=%d, pid=%d)", callingUid, callingPid, packageName, uid, pid);
            Slogf.w(LOG_TAG, message);
            throw new SecurityException(message);
        }
    }

    /**
     * Canonical name for a given package.
     */
    private String getApplicationLabel(String packageName, @UserIdInt int userId) {
        return mInjector.binderWithCleanCallingIdentity(() -> {
            final Context userContext;
            try {
                UserHandle userHandle = UserHandle.of(userId);
                userContext = mContext.createPackageContextAsUser(packageName, /* flags= */ 0,
                        userHandle);
            } catch (PackageManager.NameNotFoundException nnfe) {
                Slogf.w(LOG_TAG, nnfe, "%s is not installed for user %d", packageName, userId);
                return null;
            }
            ApplicationInfo appInfo = userContext.getApplicationInfo();
            CharSequence result = null;
            if (appInfo != null) {
                result = appInfo.loadUnsafeLabel(userContext.getPackageManager());
            }
            return result != null ? result.toString() : null;
        });
    }

    /**
     * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
     * permission.
     * The profile owner can only be set before the user setup phase has completed,
     * except for:
     * - SYSTEM_UID
     * - adb unless hasIncompatibleAccountsOrNonAdb is true.
     */
    @GuardedBy("getLockObject()")
    private void enforceCanSetProfileOwnerLocked(
            CallerIdentity caller, @Nullable ComponentName owner, @UserIdInt int userId,
            boolean hasIncompatibleAccountsOrNonAdb) {
        UserInfo info = getUserInfo(userId);
        if (info == null) {
            // User doesn't exist.
            throw new IllegalArgumentException(
                    "Attempted to set profile owner for invalid userId: " + userId);
        }
        if (info.isGuest()) {
            throw new IllegalStateException("Cannot set a profile owner on a guest");
        }
        if (mOwners.hasProfileOwner(userId)) {
            StringBuilder errorMessage = new StringBuilder("Trying to set the profile owner");
            if (!hasIncompatibleAccountsOrNonAdb) {
                append(errorMessage, owner).append(" on user ").append(userId);
            }
            errorMessage.append(", but profile owner");
            if (!hasIncompatibleAccountsOrNonAdb) {
                appendProfileOwnerLocked(errorMessage, userId);
            }

            throw new IllegalStateException(errorMessage.append(" is already set.").toString());
        }
        if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userId) {
            StringBuilder errorMessage = new StringBuilder("Trying to set the profile owner");
            if (!hasIncompatibleAccountsOrNonAdb) {
                append(errorMessage, owner).append(" on user ").append(userId);
            }
            errorMessage.append(", but the user already has a device owner");
            if (!hasIncompatibleAccountsOrNonAdb) {
                appendDeviceOwnerLocked(errorMessage);
            }
            throw new IllegalStateException(errorMessage.append('.').toString());
        }
        if (isAdb(caller)) {
            if ((mIsWatch || hasUserSetupCompleted(userId))
                    && hasIncompatibleAccountsOrNonAdb) {
                StringBuilder errorMessage = new StringBuilder("Not allowed to set the profile "
                        + "owner");
                if (!hasIncompatibleAccountsOrNonAdb) {
                    append(errorMessage, owner).append(" on user ").append(userId).append(' ');
                }
                throw new IllegalStateException(errorMessage.append(" because there are already "
                        + "some accounts on the profile.").toString());
            }
            return;
        }
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));

        if ((mIsWatch || hasUserSetupCompleted(userId))) {
            Preconditions.checkState(isSystemUid(caller),
                    "Cannot set the profile owner on a user which is already set-up");

            if (!mIsWatch) {
                if (!isSupervisionComponentLocked(owner)) {
                    throw new IllegalStateException("Unable to set non-default profile owner"
                            + " post-setup " + owner);
                }
            }
        }
    }

    /**
     * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
     * permission.
     */
    @GuardedBy("getLockObject()")
    private void enforceCanSetDeviceOwnerLocked(
            CallerIdentity caller, @Nullable ComponentName owner, @UserIdInt int deviceOwnerUserId,
            boolean hasIncompatibleAccountsOrNonAdb) {
        boolean showComponentOnError = false;
        if (!isAdb(caller)) {
            Preconditions.checkCallAuthorization(
                    hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
        } else {
            showComponentOnError = true;
        }

        final int code = checkDeviceOwnerProvisioningPreConditionLocked(owner,
                /* deviceOwnerUserId= */ deviceOwnerUserId, /* callingUserId*/ caller.getUserId(),
                isAdb(caller), hasIncompatibleAccountsOrNonAdb);
        if (code != STATUS_OK) {
            final String provisioningErrorStringLocked = computeProvisioningErrorStringLocked(code,
                    deviceOwnerUserId, owner, showComponentOnError);
            if (code == STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED) {
                throw new ServiceSpecificException(code, provisioningErrorStringLocked);
            } else {
                throw new IllegalStateException(provisioningErrorStringLocked);
            }
        }
    }

    private String computeProvisioningErrorString(int code, @UserIdInt int userId) {
        synchronized (getLockObject()) {
            return computeProvisioningErrorStringLocked(code, userId, /* newOwner= */ null,
                    /* showComponentOnError= */ false);
        }
    }

    @GuardedBy("getLockObject()")
    private String computeProvisioningErrorStringLocked(int code, @UserIdInt int userId,
            @Nullable ComponentName newOwner, boolean showComponentOnError) {
        switch (code) {
            case STATUS_OK:
                return "OK";
            case STATUS_HAS_DEVICE_OWNER: {
                StringBuilder error = new StringBuilder("Trying to set the device owner");
                if (showComponentOnError && newOwner != null) {
                    append(error, newOwner);
                }
                error.append(", but device owner");
                if (showComponentOnError) {
                    appendDeviceOwnerLocked(error);
                }
                return error.append(" is already set.").toString();
            }
            case STATUS_USER_HAS_PROFILE_OWNER: {
                StringBuilder error = new StringBuilder("Trying to set the device owner");
                if (showComponentOnError && newOwner != null) {
                    append(error, newOwner);
                }
                error.append(", but the user already has a profile owner");
                if (showComponentOnError) {
                    appendProfileOwnerLocked(error, userId);
                }
                return error.append(".").toString();
            }
            case STATUS_USER_NOT_RUNNING:
                return "User " + userId + " not running.";
            case STATUS_NOT_SYSTEM_USER:
                return "User " + userId + " is not system user.";
            case STATUS_USER_SETUP_COMPLETED:
                return  "Cannot set the device owner if the device is already set-up.";
            case STATUS_NONSYSTEM_USER_EXISTS:
                return "Not allowed to set the device owner because there are already several"
                        + " users on the device.";
            case STATUS_ACCOUNTS_NOT_EMPTY:
                return "Not allowed to set the device owner because there are already some accounts"
                        + " on the device.";
            case STATUS_HAS_PAIRED:
                return "Not allowed to set the device owner because this device has already "
                        + "paired.";
            case STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED:
                return "Cannot provision an unsupported DPC into DO on a"
                        + " headless device";
            default:
                return "Unexpected @ProvisioningPreCondition: " + code;
        }
    }

    @GuardedBy("getLockObject()")
    private void appendDeviceOwnerLocked(StringBuilder string) {
        ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
        if (deviceOwner == null) {
            // Shouldn't happen, but it doesn't hurt to check...
            Slogf.wtf(LOG_TAG, "appendDeviceOwnerLocked(): device has no DO set");
            return;
        }
        append(string, deviceOwner);
    }

    @GuardedBy("getLockObject()")
    private void appendProfileOwnerLocked(StringBuilder string, @UserIdInt int userId) {
        ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
        if (profileOwner == null) {
            // Shouldn't happen, but it doesn't hurt to check...
            Slogf.wtf(LOG_TAG, "profileOwner(%d): PO not set", userId);
            return;
        }
        append(string, profileOwner);
    }

    private static StringBuilder append(StringBuilder string, ComponentName component) {
        return string.append(" (").append(component.flattenToShortString()).append(')');
    }

    private void enforceUserUnlocked(int userId) {
        // Since we're doing this operation on behalf of an app, we only
        // want to use the actual "unlocked" state.
        Preconditions.checkState(mUserManager.isUserUnlocked(userId),
                "User must be running and unlocked");
    }

    private void enforceUserUnlocked(@UserIdInt int userId, boolean parent) {
        if (parent) {
            enforceUserUnlocked(getProfileParentId(userId));
        } else {
            enforceUserUnlocked(userId);
        }
    }

    private boolean canManageUsers(CallerIdentity caller) {
        return hasCallingOrSelfPermission(permission.MANAGE_USERS);
    }

    private boolean canQueryAdminPolicy(CallerIdentity caller) {
        return hasCallingOrSelfPermission(permission.QUERY_ADMIN_POLICY);
    }

    private boolean hasPermission(String permission, int pid, int uid) {
        return mContext.checkPermission(permission, pid, uid) == PackageManager.PERMISSION_GRANTED;
    }

    private boolean hasCallingPermission(String permission) {
        return mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED;
    }

    private boolean hasCallingOrSelfPermission(String permission) {
        return mContext.checkCallingOrSelfPermission(permission)
                == PackageManager.PERMISSION_GRANTED;
    }

    private boolean hasPermissionForPreflight(CallerIdentity caller, String permission) {
        final int callingPid = mInjector.binderGetCallingPid();
        final String packageName = mContext.getPackageName();

        return PermissionChecker.checkPermissionForPreflight(mContext, permission, callingPid,
                caller.getUid(), packageName) == PermissionChecker.PERMISSION_GRANTED;
    }

    private boolean hasFullCrossUsersPermission(CallerIdentity caller, int userHandle) {
        return (userHandle == caller.getUserId()) || isSystemUid(caller) || isRootUid(caller)
                || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS_FULL);
    }

    private boolean hasCrossUsersPermission(CallerIdentity caller, int userHandle) {
        return (userHandle == caller.getUserId()) || isSystemUid(caller) || isRootUid(caller)
                || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS);
    }

    private boolean canDPCManagedUserUseLockTaskLocked(int userId) {
        if (isUserAffiliatedWithDeviceLocked(userId)) {
            return true;
        }

        // Unaffiliated profile owners are not allowed to use lock when there is a device owner.
        if (mOwners.hasDeviceOwner()) {
            return false;
        }
        
        final ComponentName profileOwner = getProfileOwnerAsUser(userId);
        if (profileOwner == null) {
            return false;
        }
        // Managed profiles are not allowed to use lock task
        if (isManagedProfile(userId)) {
            return false;
        }
        
        return true;
    }
    private void enforceCanQueryLockTaskLocked(ComponentName who, String callerPackageName) {
        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
        final int userId = caller.getUserId();

        enforceCanQuery(MANAGE_DEVICE_POLICY_LOCK_TASK, caller.getPackageName(), userId);
        if ((isDeviceOwner(caller) || isProfileOwner(caller))
                && !canDPCManagedUserUseLockTaskLocked(userId)) {
            throw new SecurityException("User " + userId + " is not allowed to use lock task");
        }
    }

    private EnforcingAdmin enforceCanCallLockTaskLocked(ComponentName who,
            String callerPackageName) {
        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
        final int userId =  caller.getUserId();

        EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                who,
                MANAGE_DEVICE_POLICY_LOCK_TASK,
                caller.getPackageName(),
                userId
        );
        if ((isDeviceOwner(caller) || isProfileOwner(caller))
                && !canDPCManagedUserUseLockTaskLocked(userId)) {
            throw new SecurityException("User " + userId + " is not allowed to use lock task");
        }
        return enforcingAdmin;
    }

    private void enforceCanCallLockTaskLocked(CallerIdentity caller) {
        Preconditions.checkCallAuthorization(isProfileOwner(caller)
                || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller));

        final int userId =  caller.getUserId();
        if (!canDPCManagedUserUseLockTaskLocked(userId)) {
            throw new SecurityException("User " + userId + " is not allowed to use lock task");
        }
    }

    private boolean isSystemUid(CallerIdentity caller) {
        return UserHandle.isSameApp(caller.getUid(), Process.SYSTEM_UID);
    }

    private boolean isRootUid(CallerIdentity caller) {
        return UserHandle.isSameApp(caller.getUid(), Process.ROOT_UID);
    }

    private boolean isShellUid(CallerIdentity caller) {
        return UserHandle.isSameApp(caller.getUid(), Process.SHELL_UID);
    }

    private boolean isCameraServerUid(CallerIdentity caller) {
        return UserHandle.isSameApp(caller.getUid(), Process.CAMERASERVER_UID);
    }

    private @UserIdInt int getCurrentForegroundUserId() {
        try {
            UserInfo currentUser = mInjector.getIActivityManager().getCurrentUser();
            if (currentUser == null) {
                // TODO(b/206107460): should not happen on production, but it's happening on unit
                // tests that are not properly setting the expectation (because they don't need it)
                Slogf.wtf(LOG_TAG, "getCurrentForegroundUserId(): mInjector.getIActivityManager()"
                        + ".getCurrentUser() returned null, please ignore when running unit tests");
                return ActivityManager.getCurrentUser();
            }
            return currentUser.id;
        } catch (RemoteException e) {
            Slogf.wtf(LOG_TAG, "cannot get current user", e);
        }
        return UserHandle.USER_NULL;
    }

    @Override
    public List<UserHandle> listForegroundAffiliatedUsers() {
        checkIsDeviceOwner(getCallerIdentity());

        return mInjector.binderWithCleanCallingIdentity(() -> {
            int userId = getCurrentForegroundUserId();
            boolean isAffiliated;
            synchronized (getLockObject()) {
                isAffiliated = isUserAffiliatedWithDeviceLocked(userId);
            }

            if (!isAffiliated) return Collections.emptyList();

            List<UserHandle> users = new ArrayList<>(1);
            users.add(UserHandle.of(userId));

            return users;
        });
    }

    protected int getProfileParentId(int userHandle) {
        return mInjector.binderWithCleanCallingIdentity(() -> {
            UserInfo parentUser = mUserManager.getProfileParent(userHandle);
            return parentUser != null ? parentUser.id : userHandle;
        });
    }

    private int getProfileParentUserIfRequested(int userHandle, boolean parent) {
        if (parent) {
            return getProfileParentId(userHandle);
        }

        return userHandle;
    }

    private int getCredentialOwner(final int userHandle, final boolean parent) {
        return mInjector.binderWithCleanCallingIdentity(() -> {
            int effectiveUserHandle = userHandle;
            if (parent) {
                UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
                if (parentProfile != null) {
                    effectiveUserHandle = parentProfile.id;
                }
            }
            return mUserManager.getCredentialOwnerProfile(effectiveUserHandle);
        });
    }

    private boolean isManagedProfile(int userHandle) {
        final UserInfo user = getUserInfo(userHandle);
        return user != null && user.isManagedProfile();
    }

    private void enableIfNecessary(String packageName, int userId) {
        try {
            final ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
                    PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS, userId);
            if (ai.enabledSetting
                    == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                mIPackageManager.setApplicationEnabledSetting(packageName,
                        PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
                        PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
            }
        } catch (RemoteException e) {
        }
    }

    private void dumpPersonalAppInfoForSystemUserNoLock(IndentingPrintWriter pw) {
        wtfIfInLock();
        PersonalAppsSuspensionHelper.forUser(mContext, UserHandle.USER_SYSTEM).dump(pw);
    }

    private void dumpPerUserPolicyData(IndentingPrintWriter pw) {
        int userCount = mUserData.size();
        for (int i = 0; i < userCount; i++) {
            int userId = mUserData.keyAt(i);
            DevicePolicyData policy = getUserData(userId);
            policy.dump(pw);
            pw.println();
        }
    }

    @Override
    protected void dump(FileDescriptor fd, PrintWriter printWriter, String[] args) {
        if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, printWriter)) return;

        try (IndentingPrintWriter pw = new IndentingPrintWriter(printWriter, "  ")) {
            pw.println("Current Device Policy Manager state:");
            pw.increaseIndent();

            dumpImmutableState(pw);
            synchronized (getLockObject()) {
                mOwners.dump(pw);
                pw.println();
                mDeviceAdminServiceController.dump(pw);
                pw.println();
                dumpPerUserPolicyData(pw);
                pw.println();
                mConstants.dump(pw);
                pw.println();
                mStatLogger.dump(pw);
                pw.println();
                if (dumpsysPolicyEngineMigrationEnabled()) {
                    mDevicePolicyEngine.dump(pw);
                    pw.println();
                }
                pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
                pw.println("Logout user: " + getLogoutUserIdUnchecked());
                pw.println();

                if (mPendingUserCreatedCallbackTokens.isEmpty()) {
                    pw.println("no pending user created callback tokens");
                } else {
                    int size = mPendingUserCreatedCallbackTokens.size();
                    pw.printf("%d pending user created callback token%s\n", size,
                            (size == 1 ? "" : "s"));
                }
                pw.println();

                mPolicyCache.dump(pw);
                pw.println();
                mStateCache.dump(pw);
                pw.println();
            }
            dumpPersonalAppInfoForSystemUserNoLock(pw);

            synchronized (mSubscriptionsChangedListenerLock) {
                pw.println("Subscription changed listener : " + mSubscriptionsChangedListener);
            }

            pw.println("DPM global setting ALLOW_WORK_PROFILE_TELEPHONY_FOR_NON_DPM_ROLE_HOLDERS : "
                    + mInjector.settingsGlobalGetString(
                    Global.ALLOW_WORK_PROFILE_TELEPHONY_FOR_NON_DPM_ROLE_HOLDERS));
            mHandler.post(() -> handleDump(pw));
            dumpResources(pw);
        }
    }

    // Dump state that is guarded by the handler
    private void handleDump(IndentingPrintWriter pw) {
        if (mNetworkLoggingNotificationUserId != UserHandle.USER_NULL) {
            pw.println("mNetworkLoggingNotificationUserId:  " + mNetworkLoggingNotificationUserId);
        }
    }

    private void dumpImmutableState(IndentingPrintWriter pw) {
        pw.println("Immutable state:");
        pw.increaseIndent();
        pw.printf("mHasFeature=%b\n", mHasFeature);
        pw.printf("mIsWatch=%b\n", mIsWatch);
        pw.printf("mIsAutomotive=%b\n", mIsAutomotive);
        pw.printf("mHasTelephonyFeature=%b\n", mHasTelephonyFeature);
        pw.printf("mSafetyChecker=%s\n", mSafetyChecker);
        pw.decreaseIndent();
    }

    private void dumpResources(IndentingPrintWriter pw) {
        mOverlayPackagesProvider.dump(pw);
        pw.println();

        pw.println("Other overlayable app resources");
        pw.increaseIndent();
        dumpResources(pw, mContext, "cross_profile_apps", R.array.cross_profile_apps);
        dumpResources(pw, mContext, "vendor_cross_profile_apps", R.array.vendor_cross_profile_apps);
        dumpResources(pw, mContext, "config_packagesExemptFromSuspension",
                R.array.config_packagesExemptFromSuspension);
        dumpResources(pw, mContext, "policy_exempt_apps", R.array.policy_exempt_apps);
        dumpResources(pw, mContext, "vendor_policy_exempt_apps", R.array.vendor_policy_exempt_apps);
        pw.decreaseIndent();
        pw.println();
    }

    static void dumpResources(IndentingPrintWriter pw, Context context, String resName, int resId) {
        dumpApps(pw, resName, context.getResources().getStringArray(resId));
    }

    static void dumpApps(IndentingPrintWriter pw, String name, String[] apps) {
        dumpApps(pw, name, Arrays.asList(apps));
    }

    static void dumpApps(IndentingPrintWriter pw, String name, List apps) {
        if (apps == null || apps.isEmpty()) {
            pw.printf("%s: empty\n", name);
            return;
        }
        int size = apps.size();
        pw.printf("%s: %d app%s\n", name, size, size == 1 ? "" : "s");
        pw.increaseIndent();
        for (int i = 0; i < size; i++) {
            pw.printf("%d: %s\n", i, apps.get(i));
        }
        pw.decreaseIndent();
    }

    @Override
    public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
            String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
        new DevicePolicyManagerServiceShellCommand(DevicePolicyManagerService.this).exec(
                this, in, out, err, args, callback, resultReceiver);

    }

    private String getEncryptionStatusName(int encryptionStatus) {
        switch (encryptionStatus) {
            case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
                return "per-user";
            case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
                return "unsupported";
            default:
                return "unknown";
        }
    }

    @Override
    public void addPersistentPreferredActivity(ComponentName who, String callerPackageName,
            IntentFilter filter, ComponentName activity) {
        CallerIdentity caller = getCallerIdentity(who, callerPackageName);

        final int userId = caller.getUserId();
        EnforcingAdmin enforcingAdmin;
        if (who == null) {
            enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                    who,
                    MANAGE_DEVICE_POLICY_LOCK_TASK,
                    caller.getPackageName(),
                    userId);
        } else {
            Preconditions.checkCallAuthorization(isProfileOwner(caller)
                    || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller));
            enforcingAdmin = getEnforcingAdminForCaller(who, callerPackageName);
        }
        if (!isPackageInstalledForUser(activity.getPackageName(), userId)) {
            // Fail early as packageManager doesn't persist the activity if its not installed.
            return;
        }
        mDevicePolicyEngine.setLocalPolicy(
                PolicyDefinition.PERSISTENT_PREFERRED_ACTIVITY(filter),
                enforcingAdmin,
                new ComponentNamePolicyValue(activity),
                userId);
        final String activityPackage =
                (activity != null ? activity.getPackageName() : null);
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.ADD_PERSISTENT_PREFERRED_ACTIVITY)
                .setAdmin(caller.getPackageName())
                .setStrings(activityPackage, getIntentFilterActions(filter))
                .write();
    }

    @Override
    public void clearPackagePersistentPreferredActivities(ComponentName who,
            String callerPackageName, String packageName) {
        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
        final int userId = caller.getUserId();

        EnforcingAdmin enforcingAdmin;
        if (who == null) {
            enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                    who,
                    MANAGE_DEVICE_POLICY_LOCK_TASK,
                    caller.getPackageName(),
                    userId);
        } else {
            Preconditions.checkCallAuthorization(isProfileOwner(caller)
                    || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller));
            enforcingAdmin = getEnforcingAdminForCaller(who, callerPackageName);
        }
        clearPackagePersistentPreferredActivitiesFromPolicyEngine(
                enforcingAdmin,
                packageName,
                userId);
    }

    /**
     * Remove all persistent intent handler preferences associated with the given package that were
     * set by this admin, note that is doesn't remove preferences set by other admins for the same
     * package.
     */
    private void clearPackagePersistentPreferredActivitiesFromPolicyEngine(
            EnforcingAdmin admin, String packageName, int userId) {
        Set<PolicyKey> keys = mDevicePolicyEngine.getLocalPolicyKeysSetByAdmin(
                PolicyDefinition.GENERIC_PERSISTENT_PREFERRED_ACTIVITY,
                admin,
                userId);
        for (PolicyKey key : keys) {
            if (!(key instanceof IntentFilterPolicyKey)) {
                throw new IllegalStateException("PolicyKey for PERSISTENT_PREFERRED_ACTIVITY is not"
                        + "of type IntentFilterPolicyKey");
            }
            IntentFilterPolicyKey parsedKey =
                    (IntentFilterPolicyKey) key;
            IntentFilter filter = Objects.requireNonNull(parsedKey.getIntentFilter());

            ComponentName preferredActivity = mDevicePolicyEngine.getLocalPolicySetByAdmin(
                    PolicyDefinition.PERSISTENT_PREFERRED_ACTIVITY(filter),
                    admin,
                    userId);
            if (preferredActivity != null
                    && preferredActivity.getPackageName().equals(packageName)) {
                mDevicePolicyEngine.removeLocalPolicy(
                        PolicyDefinition.PERSISTENT_PREFERRED_ACTIVITY(filter),
                        admin,
                        userId);
            }
        }
    }

    @Override
    public void setDefaultSmsApplication(ComponentName admin, String callerPackageName,
            String packageName, boolean parent) {
        CallerIdentity caller;
        if (isPermissionCheckFlagEnabled()) {
            caller = getCallerIdentity(admin, callerPackageName);
        } else {
            caller = getCallerIdentity(admin);
        }

        final int userId;

        if (isPermissionCheckFlagEnabled()) {
            enforcePermission(
                    MANAGE_DEVICE_POLICY_DEFAULT_SMS,
                    caller.getPackageName(),
                    getAffectedUser(parent));
        } else {
            Objects.requireNonNull(admin, "ComponentName is null");
            Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
                    || isProfileOwnerOfOrganizationOwnedDevice(caller));
        }

        if (!parent && isManagedProfile(caller.getUserId())
                && getManagedSubscriptionsPolicy().getPolicyType()
                != ManagedSubscriptionsPolicy.TYPE_ALL_MANAGED_SUBSCRIPTIONS) {
            throw new IllegalStateException(
                    "Default sms application can only be set on the profile, when "
                            + "ManagedSubscriptions policy is set");
        }

        if (parent) {
            userId = getProfileParentId(mInjector.userHandleGetCallingUserId());
            mInjector.binderWithCleanCallingIdentity(() -> enforcePackageIsSystemPackage(
                    packageName, userId));
        } else {
            userId = mInjector.userHandleGetCallingUserId();
        }

        mInjector.binderWithCleanCallingIdentity(() ->
                SmsApplication.setDefaultApplicationAsUser(packageName, mContext, userId));

        synchronized (getLockObject()) {
            final ActiveAdmin activeAdmin = getParentOfAdminIfRequired(
                    getProfileOwnerOrDeviceOwnerLocked(caller.getUserId()), parent);

            if (isManagedProfile(userId)) {
                mInjector.binderWithCleanCallingIdentity(
                        () -> updateDialerAndSmsManagedShortcutsOverrideCache());
            }

            if (!Objects.equals(activeAdmin.mSmsPackage, packageName)) {
                activeAdmin.mSmsPackage = packageName;
                saveSettingsLocked(caller.getUserId());
            }
        }
    }

    @Override
    public void setDefaultDialerApplication(String packageName) {
        if (!mHasFeature || !mHasTelephonyFeature) {
            return;
        }

        final CallerIdentity caller = getCallerIdentity();
        final int callerUserId = caller.getUserId();
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
                || isProfileOwnerOfOrganizationOwnedDevice(caller));
        mInjector.binderWithCleanCallingIdentity(() -> {
            CompletableFuture<Void> future = new CompletableFuture<>();
            Consumer<Boolean> callback = successful -> {
                if (successful) {
                    future.complete(null);
                } else {
                    future.completeExceptionally(new IllegalArgumentException(
                            packageName +  " cannot be set as the dialer"));
                }
            };
            mRoleManager.addRoleHolderAsUser(
                    RoleManager.ROLE_DIALER, packageName, 0, UserHandle.of(callerUserId),
                    AsyncTask.THREAD_POOL_EXECUTOR, callback);
            try {
                future.get(20, TimeUnit.SECONDS);
            } catch (TimeoutException e) {
                throw new IllegalArgumentException("Timeout when setting the app as the dialer", e);
            } catch (ExecutionException e) {
                Throwable cause = e.getCause();
                if (cause instanceof IllegalArgumentException) {
                    throw (IllegalArgumentException) cause;
                } else {
                    throw new IllegalStateException(cause);
                }
            }
        });
        // Only save the package when the setting the role succeeded without exception.
        synchronized (getLockObject()) {
            if (isManagedProfile(callerUserId)) {
                mInjector.binderWithCleanCallingIdentity(
                        () -> updateDialerAndSmsManagedShortcutsOverrideCache());
            }

            final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(callerUserId);
            if (!Objects.equals(admin.mDialerPackage, packageName)) {
                admin.mDialerPackage = packageName;
                saveSettingsLocked(callerUserId);
            }
        }
    }

    @Override
    public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
            String packageName) {
        try {
            setDelegatedScopePreO(admin, packageName, DELEGATION_APP_RESTRICTIONS);
        } catch (IllegalArgumentException e) {
            return false;
        }
        return true;
    }

    @Override
    public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
        final List<String> delegatePackages = getDelegatePackages(admin,
                DELEGATION_APP_RESTRICTIONS);
        return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
    }

    @Override
    public boolean isCallerApplicationRestrictionsManagingPackage(String callerPackage) {
        return isCallerDelegate(callerPackage, getCallerIdentity().getUid(),
                DELEGATION_APP_RESTRICTIONS);
    }

    @Override
    public void setApplicationRestrictions(ComponentName who, String callerPackage,
            String packageName, Bundle restrictions) {
        final CallerIdentity caller = getCallerIdentity(who, callerPackage);
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_APPLICATION_RESTRICTIONS);

        if (isUnicornFlagEnabled()) {
            EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                    who,
                    MANAGE_DEVICE_POLICY_APP_RESTRICTIONS,
                    caller.getPackageName(),
                    caller.getUserId()
            );
            // This check is eventually made in UMS, checking here to fail early.
            String validationResult =
                    FrameworkParsingPackageUtils.validateName(packageName, false, false);
            if (validationResult != null) {
                throw new IllegalArgumentException("Invalid package name: " + validationResult);
            }

            if (restrictions == null || restrictions.isEmpty()) {
                mDevicePolicyEngine.removeLocalPolicy(
                        PolicyDefinition.APPLICATION_RESTRICTIONS(packageName),
                        enforcingAdmin,
                        caller.getUserId());
            } else {
                mDevicePolicyEngine.setLocalPolicy(
                        PolicyDefinition.APPLICATION_RESTRICTIONS(packageName),
                        enforcingAdmin,
                        new BundlePolicyValue(restrictions),
                        caller.getUserId());
            }
            setBackwardsCompatibleAppRestrictions(
                    caller, packageName, restrictions, caller.getUserHandle());
        } else {
            Preconditions.checkCallAuthorization((caller.hasAdminComponent()
                    && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
                    || (caller.hasPackage() && isCallerDelegate(caller,
                    DELEGATION_APP_RESTRICTIONS)));
            mInjector.binderWithCleanCallingIdentity(() -> {
                mUserManager.setApplicationRestrictions(packageName, restrictions,
                        caller.getUserHandle());
            });
        }

        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_APPLICATION_RESTRICTIONS)
                .setAdmin(caller.getPackageName())
                .setBoolean(/* isDelegate */ isCallerDelegate(caller))
                .setStrings(packageName)
                .write();
    }

    /**
     * Set app restrictions in user manager for DPC callers only to keep backwards compatibility
     * for the old getApplicationRestrictions API.
     */
    private void setBackwardsCompatibleAppRestrictions(
            CallerIdentity caller, String packageName, Bundle restrictions, UserHandle userHandle) {
        if ((caller.hasAdminComponent() && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
                || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_APP_RESTRICTIONS))) {
            Bundle restrictionsToApply = restrictions == null || restrictions.isEmpty()
                    ? getAppRestrictionsSetByAnyAdmin(packageName, userHandle)
                    : restrictions;
            mInjector.binderWithCleanCallingIdentity(() -> {
                mUserManager.setApplicationRestrictions(packageName, restrictionsToApply,
                        userHandle);
            });
        } else {
            // Notify package of changes via an intent - only sent to explicitly registered
            // receivers. Sending here because For DPCs, this is being sent in UMS.
            final Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
            changeIntent.setPackage(packageName);
            changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
            mContext.sendBroadcastAsUser(changeIntent, userHandle);
        }
    }

    private Bundle getAppRestrictionsSetByAnyAdmin(String packageName, UserHandle userHandle) {
        LinkedHashMap<EnforcingAdmin, PolicyValue<Bundle>> policies =
                mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
                        PolicyDefinition.APPLICATION_RESTRICTIONS(packageName),
                        userHandle.getIdentifier());
        return policies.isEmpty()
                ? null : policies.entrySet().stream().findAny().get().getValue().getValue();
    }

    private int getUidForPackage(String packageName, int userId) {
        return mInjector.binderWithCleanCallingIdentity(() -> {
            try {
                return mContext.getPackageManager().getApplicationInfoAsUser(
                        packageName, /* flags= */ 0, userId).uid;
            } catch (NameNotFoundException exception) {
                return -1;
            }
        });
    }

    @Override
    public void setTrustAgentConfiguration(
            ComponentName admin, String callerPackageName, ComponentName agent,
            PersistableBundle args, boolean parent) {
        if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
            return;
        }

        if (!isPermissionCheckFlagEnabled()) {
            Objects.requireNonNull(admin, "admin is null");
        }

        Objects.requireNonNull(agent, "agent is null");

        enforceMaxPackageNameLength(agent.getPackageName());
        final String agentAsString = agent.flattenToString();
        enforceMaxStringLength(agentAsString, "agent name");
        if (args != null) {
            enforceMaxStringLength(args, "args");
        }

        int userHandle = mInjector.userHandleGetCallingUserId();
        synchronized (getLockObject()) {
            ActiveAdmin ap;
            if (isPermissionCheckFlagEnabled()) {
                CallerIdentity caller = getCallerIdentity(admin, callerPackageName);
                int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
                ap = enforcePermissionAndGetEnforcingAdmin(
                        admin,
                        /*permission=*/MANAGE_DEVICE_POLICY_KEYGUARD,
                        /*adminPolicy=*/DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES,
                        caller.getPackageName(), affectedUserId).getActiveAdmin();
            } else {
                ap = getActiveAdminForCallerLocked(admin,
                        DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
            }
            checkCanExecuteOrThrowUnsafe(
                    DevicePolicyManager.OPERATION_SET_TRUST_AGENT_CONFIGURATION);

            ap.trustAgentInfos.put(agentAsString, new TrustAgentInfo(args));
            saveSettingsLocked(userHandle);
        }
    }

    @Override
    public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
            ComponentName agent, int userHandle, boolean parent) {
        if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
            return null;
        }
        Objects.requireNonNull(agent, "agent null");
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity(admin);
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));

        synchronized (getLockObject()) {
            final String componentName = agent.flattenToString();
            if (admin != null) {
                final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
                if (ap == null) return null;
                TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
                if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
                List<PersistableBundle> result = new ArrayList<>();
                result.add(trustAgentInfo.options);
                return result;
            }

            // Return strictest policy for this user and profiles that are visible from this user.
            List<PersistableBundle> result = null;
            // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
            // of the options. If any admin doesn't have options, discard options for the rest
            // and return null.
            List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
                    getProfileParentUserIfRequested(userHandle, parent));
            boolean allAdminsHaveOptions = true;
            final int N = admins.size();
            for (int i = 0; i < N; i++) {
                final ActiveAdmin active = admins.get(i);

                final boolean disablesTrust = (active.disabledKeyguardFeatures
                        & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
                final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
                if (info != null && info.options != null && !info.options.isEmpty()) {
                    if (disablesTrust) {
                        if (result == null) {
                            result = new ArrayList<>();
                        }
                        result.add(info.options);
                    } else {
                        Slogf.w(LOG_TAG, "Ignoring admin %s because it has trust options but "
                                + "doesn't declare KEYGUARD_DISABLE_TRUST_AGENTS", active.info);
                    }
                } else if (disablesTrust) {
                    allAdminsHaveOptions = false;
                    break;
                }
            }
            return allAdminsHaveOptions ? result : null;
        }
    }

    @Override
    public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isProfileOwner(caller) || isDefaultDeviceOwner(caller));
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_RESTRICTIONS_PROVIDER);

        synchronized (getLockObject()) {
            int userHandle = caller.getUserId();
            DevicePolicyData userData = getUserData(userHandle);
            userData.mRestrictionsProvider = permissionProvider;
            saveSettingsLocked(userHandle);
        }
    }

    @Override
    public ComponentName getRestrictionsProvider(int userHandle) {
        Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
                String.format(NOT_SYSTEM_CALLER_MSG, "query the permission provider"));
        synchronized (getLockObject()) {
            DevicePolicyData userData = getUserData(userHandle);
            return userData != null ? userData.mRestrictionsProvider : null;
        }
    }

    @Override
    public void addCrossProfileIntentFilter(ComponentName who, String callerPackageName,
            IntentFilter filter, int flags) {
        CallerIdentity caller;
        if (isPermissionCheckFlagEnabled()) {
            caller = getCallerIdentity(who, callerPackageName);
        } else {
            caller = getCallerIdentity(who);
        }
        int callingUserId = caller.getUserId();

        if (isPermissionCheckFlagEnabled()) {
            enforcePermission(
                    MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
                    caller.getPackageName(),
                    callingUserId);
        } else {
            Objects.requireNonNull(who, "ComponentName is null");
            Preconditions.checkCallAuthorization(
                    isProfileOwner(caller) || isDefaultDeviceOwner(caller));
        }
        synchronized (getLockObject()) {
            long id = mInjector.binderClearCallingIdentity();
            try {
                UserInfo parent = mUserManager.getProfileParent(callingUserId);
                if (parent == null) {
                    Slogf.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
                            + "parent");
                    return;
                }
                if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
                    mIPackageManager.addCrossProfileIntentFilter(
                            filter, who.getPackageName(), callingUserId, parent.id, 0);
                }
                if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
                    mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
                            parent.id, callingUserId, 0);
                }
            } catch (RemoteException re) {
                // Shouldn't happen
                Slogf.wtf(LOG_TAG, "Error adding cross profile intent filter", re);
            } finally {
                mInjector.binderRestoreCallingIdentity(id);
            }
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.ADD_CROSS_PROFILE_INTENT_FILTER)
                .setAdmin(caller.getPackageName())
                .setStrings(getIntentFilterActions(filter))
                .setInt(flags)
                .write();
    }

    private static String[] getIntentFilterActions(IntentFilter filter) {
        if (filter == null) {
            return null;
        }
        final int actionsCount = filter.countActions();
        final String[] actions = new String[actionsCount];
        for (int i = 0; i < actionsCount; i++) {
            actions[i] = filter.getAction(i);
        }
        return actions;
    }

    @Override
    public void clearCrossProfileIntentFilters(ComponentName who, String callerPackageName) {
        CallerIdentity caller;
        if (isPermissionCheckFlagEnabled()) {
            caller = getCallerIdentity(who, callerPackageName);
        } else {
            caller = getCallerIdentity(who);
        }
        int callingUserId = caller.getUserId();

        if (isPermissionCheckFlagEnabled()) {
            enforcePermission(
                    MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
                    caller.getPackageName(),
                    callingUserId);
        } else {
            Objects.requireNonNull(who, "ComponentName is null");
            Preconditions.checkCallAuthorization(
                    isProfileOwner(caller) || isDefaultDeviceOwner(caller));
        }

        synchronized (getLockObject()) {
            long id = mInjector.binderClearCallingIdentity();
            try {
                UserInfo parent = mUserManager.getProfileParent(callingUserId);
                if (parent == null) {
                    Slogf.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
                            + "parent");
                    return;
                }
                // Removing those that go from the managed profile to the parent.
                mIPackageManager.clearCrossProfileIntentFilters(
                        callingUserId, who.getPackageName());
                // And those that go from the parent to the managed profile.
                // If we want to support multiple managed profiles, we will have to only remove
                // those that have callingUserId as their target.
                mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
            } catch (RemoteException re) {
                // Shouldn't happen
                Slogf.wtf(LOG_TAG, "Error clearing cross profile intent filters", re);
            } finally {
                mInjector.binderRestoreCallingIdentity(id);
            }
        }
    }

    /**
     * @return true if all packages in enabledPackages are either in the list
     * permittedList or are a system app.
     */
    private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
            List<String> permittedList, int userIdToCheck) {
        long id = mInjector.binderClearCallingIdentity();
        try {
            // If we have an enabled packages list for a managed profile the packages
            // we should check are installed for the parent user.
            UserInfo user = getUserInfo(userIdToCheck);
            if (user.isManagedProfile()) {
                userIdToCheck = user.profileGroupId;
            }

            for (String enabledPackage : enabledPackages) {
                boolean systemService = false;
                try {
                    ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
                            enabledPackage, PackageManager.MATCH_UNINSTALLED_PACKAGES,
                            userIdToCheck);

                    if (applicationInfo == null) {
                        return false;
                    }

                    systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
                } catch (RemoteException e) {
                    Slogf.i(LOG_TAG, "Can't talk to package managed", e);
                }
                if (!systemService && !permittedList.contains(enabledPackage)) {
                    return false;
                }
            }
        } finally {
            mInjector.binderRestoreCallingIdentity(id);
        }
        return true;
    }

    /**
     * Invoke a method in AccessibilityManager ensuring the client is removed.
     */
    private <T> T withAccessibilityManager(
            int userId, Function<AccessibilityManager, T> function) {
        // Not using AccessibilityManager.getInstance because that guesses
        // at the user you require based on callingUid and caches for a given
        // process.
        final IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
        final IAccessibilityManager service = iBinder == null
                ? null : IAccessibilityManager.Stub.asInterface(iBinder);
        final AccessibilityManager am = new AccessibilityManager(mContext, service, userId);
        try {
            return function.apply(am);
        } finally {
            am.removeClient();
        }
    }

    @Override
    public boolean setPermittedAccessibilityServices(ComponentName who, List<String> packageList) {
        if (!mHasFeature) {
            return false;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || isProfileOwner(caller));

        if (packageList != null) {
            for (String pkg : packageList) {
                enforceMaxPackageNameLength(pkg);
            }

            int userId = caller.getUserId();
            final List<AccessibilityServiceInfo> enabledServices;
            long id = mInjector.binderClearCallingIdentity();
            try {
                UserInfo user = getUserInfo(userId);
                if (user.isManagedProfile()) {
                    userId = user.profileGroupId;
                }
                enabledServices = withAccessibilityManager(userId,
                        am -> am.getEnabledAccessibilityServiceList(FEEDBACK_ALL_MASK));
            } finally {
                mInjector.binderRestoreCallingIdentity(id);
            }

            if (enabledServices != null) {
                List<String> enabledPackages = new ArrayList<>();
                for (AccessibilityServiceInfo service : enabledServices) {
                    enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
                }
                if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
                        userId)) {
                    Slogf.e(LOG_TAG, "Cannot set permitted accessibility services, "
                            + "because it contains already enabled accesibility services.");
                    return false;
                }
            }
        }

        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
            admin.permittedAccessiblityServices = packageList;
            saveSettingsLocked(UserHandle.getCallingUserId());
        }
        final String[] packageArray =
                packageList != null ? ((List<String>) packageList).toArray(new String[0]) : null;
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_PERMITTED_ACCESSIBILITY_SERVICES)
                .setAdmin(who)
                .setStrings(packageArray)
                .write();
        return true;
    }

    @Override
    public List<String> getPermittedAccessibilityServices(ComponentName who) {
        if (!mHasFeature) {
            return null;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || isProfileOwner(caller));

        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
            return admin.permittedAccessiblityServices;
        }
    }

    @Override
    public List<String> getPermittedAccessibilityServicesForUser(int userId) {
        if (!mHasFeature) {
            return null;
        }
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(canManageUsers(caller) || canQueryAdminPolicy(caller));

        List<String> result = null;

        synchronized (getLockObject()) {
            // If we have multiple profiles we return the intersection of the
            // permitted lists. This can happen in cases where we have a device
            // and profile owner.
            int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
            for (int profileId : profileIds) {
                // Just loop though all admins, only device or profiles
                // owners can have permitted lists set.
                DevicePolicyData policy = getUserDataUnchecked(profileId);
                final int N = policy.mAdminList.size();
                for (int j = 0; j < N; j++) {
                    ActiveAdmin admin = policy.mAdminList.get(j);
                    List<String> fromAdmin = admin.permittedAccessiblityServices;
                    if (fromAdmin != null) {
                        if (result == null) {
                            result = new ArrayList<>(fromAdmin);
                        } else {
                            result.retainAll(fromAdmin);
                        }
                    }
                }
            }
        }

        // If we have a permitted list add all system accessibility services.
        if (result != null) {
            long id = mInjector.binderClearCallingIdentity();
            try {
                UserInfo user = getUserInfo(userId);
                if (user.isManagedProfile()) {
                    userId = user.profileGroupId;
                }
                // Move AccessibilityManager out of {@link getLockObject} to prevent potential
                // deadlock.
                final List<AccessibilityServiceInfo> installedServices =
                        withAccessibilityManager(userId,
                                AccessibilityManager::getInstalledAccessibilityServiceList);

                if (installedServices != null) {
                    for (AccessibilityServiceInfo service : installedServices) {
                        ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
                        ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
                        if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                            result.add(serviceInfo.packageName);
                        }
                    }
                }
            } finally {
                mInjector.binderRestoreCallingIdentity(id);
            }
        }

        return result;
    }

    @Override
    public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
            int userHandle) {
        if (!mHasFeature) {
            return true;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        Preconditions.checkStringNotEmpty(packageName, "packageName is null");
        Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
                String.format(NOT_SYSTEM_CALLER_MSG,
                        "query if an accessibility service is disabled by admin"));

        synchronized (getLockObject()) {
            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
            if (admin == null) {
                return false;
            }
            if (admin.permittedAccessiblityServices == null) {
                return true;
            }
            return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
                    admin.permittedAccessiblityServices, userHandle);
        }
    }

    @Override
    public boolean setPermittedInputMethods(ComponentName who, String callerPackageName,
            List<String> packageList, boolean calledOnParentInstance) {
        if (!mHasFeature) {
            return false;
        }

        CallerIdentity caller = getCallerIdentity(who, callerPackageName);

        int userId = getProfileParentUserIfRequested(
                caller.getUserId(), calledOnParentInstance);
        if (calledOnParentInstance) {
            Preconditions.checkArgument(packageList == null || packageList.isEmpty(),
                    "Permitted input methods must allow all input methods or only "
                            + "system input methods when called on the parent instance of an "
                            + "organization-owned device");
        }

        if (packageList != null) {
            for (String pkg : packageList) {
                enforceMaxPackageNameLength(pkg);
            }

            List<InputMethodInfo> enabledImes = mInjector.binderWithCleanCallingIdentity(() ->
                    InputMethodManagerInternal.get().getEnabledInputMethodListAsUser(userId));
            if (enabledImes != null) {
                List<String> enabledPackages = new ArrayList<String>();
                for (InputMethodInfo ime : enabledImes) {
                    enabledPackages.add(ime.getPackageName());
                }
                if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
                        userId)) {
                    Slogf.e(LOG_TAG, "Cannot set permitted input methods, because the list of "
                            + "permitted input methods excludes an already-enabled input method.");
                    return false;
                }
            }
        }

        synchronized (getLockObject()) {
            EnforcingAdmin admin = enforcePermissionAndGetEnforcingAdmin(
                    who, MANAGE_DEVICE_POLICY_INPUT_METHODS,
                    caller.getPackageName(), userId);
            if (packageList == null) {
                mDevicePolicyEngine.removeLocalPolicy(
                        PolicyDefinition.PERMITTED_INPUT_METHODS,
                        admin,
                        userId);
            } else {
                mDevicePolicyEngine.setLocalPolicy(
                        PolicyDefinition.PERMITTED_INPUT_METHODS,
                        admin,
                        new StringSetPolicyValue(new HashSet<>(packageList)),
                        userId);
            }
        }

        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_PERMITTED_INPUT_METHODS)
                .setAdmin(caller.getPackageName())
                .setStrings(getStringArrayForLogging(packageList, calledOnParentInstance))
                .write();
        return true;
    }

    private String[] getStringArrayForLogging(List list, boolean calledOnParentInstance) {
        List<String> stringList = new ArrayList<String>();
        stringList.add(calledOnParentInstance ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT);
        if (list == null) {
            stringList.add(NULL_STRING_ARRAY);
        } else {
            stringList.addAll((List<String>) list);
        }
        return stringList.toArray(new String[0]);
    }

    @Override
    public List<String> getPermittedInputMethods(ComponentName who, String callerPackageName,
            boolean calledOnParentInstance) {
        if (!mHasFeature) {
            return null;
        }

        CallerIdentity caller = getCallerIdentity(who, callerPackageName);

        synchronized (getLockObject()) {
            int affectedUser = calledOnParentInstance ? getProfileParentId(
                    caller.getUserId()) : caller.getUserId();
            Set<String> policy = mDevicePolicyEngine.getResolvedPolicy(
                    PolicyDefinition.PERMITTED_INPUT_METHODS, affectedUser);
            return policy == null ? null : new ArrayList<>(policy);
        }
    }

    @Override
    public @Nullable List<String> getPermittedInputMethodsAsUser(@UserIdInt int userId) {
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId));
        Preconditions.checkCallAuthorization(canManageUsers(caller) || canQueryAdminPolicy(caller));
        final long callingIdentity = Binder.clearCallingIdentity();
        try {
            return getPermittedInputMethodsUnchecked(userId);
        } finally {
            Binder.restoreCallingIdentity(callingIdentity);
        }
    }

    private @Nullable List<String> getPermittedInputMethodsUnchecked(@UserIdInt int userId) {
        Set<String> policy = mDevicePolicyEngine.getResolvedPolicy(
                PolicyDefinition.PERMITTED_INPUT_METHODS, userId);
        List<String> result = policy == null ? null : new ArrayList<>(policy);

        // If we have a permitted list add all system input methods.
        if (result != null) {
            List<InputMethodInfo> imes = InputMethodManagerInternal
                    .get().getInputMethodListAsUser(userId);
            if (imes != null) {
                for (InputMethodInfo ime : imes) {
                    ServiceInfo serviceInfo = ime.getServiceInfo();
                    ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
                    if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                        result.add(serviceInfo.packageName);
                    }
                }
            }
        }
        return result;
    }

    @Override
    public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
            int userHandle, boolean calledOnParentInstance) {
        if (!mHasFeature) {
            return true;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        Preconditions.checkStringNotEmpty(packageName, "packageName is null");
        Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
                String.format(NOT_SYSTEM_CALLER_MSG,
                        "query if an input method is disabled by admin"));

        int affectedUser = calledOnParentInstance ? getProfileParentId(userHandle) : userHandle;
        Map<EnforcingAdmin, PolicyValue<Set<String>>> policies =
                mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
                        PolicyDefinition.PERMITTED_INPUT_METHODS, affectedUser);
        for (EnforcingAdmin a : policies.keySet()) {
            if (a.getPackageName().equals(who.getPackageName())) {
                if (policies.get(a).getValue() == null) {
                    return true;
                } else {
                    return checkPackagesInPermittedListOrSystem(
                            Collections.singletonList(packageName),
                            new ArrayList<>(policies.get(a).getValue()), affectedUser);
                }
            }
        }
        // Admin didn't set a policy
        return false;
    }

    @Override
    public boolean setPermittedCrossProfileNotificationListeners(
            ComponentName who, List<String> packageList) {
        if (!mHasFeature) {
            return false;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);

        if (!isManagedProfile(caller.getUserId())) {
            return false;
        }
        Preconditions.checkCallAuthorization(isProfileOwner(caller));
        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
            admin.permittedNotificationListeners = packageList;
            saveSettingsLocked(caller.getUserId());
        }
        return true;
    }

    @Override
    public List<String> getPermittedCrossProfileNotificationListeners(ComponentName who) {
        if (!mHasFeature) {
            return null;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isDeviceOwner(caller) || isProfileOwner(caller));

        synchronized (getLockObject()) {
            // API contract is to return null if there are no permitted cross-profile notification
            // listeners, including in Device Owner mode.
            ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
            return admin.permittedNotificationListeners;
        }
    }

    @Override
    public boolean isNotificationListenerServicePermitted(String packageName, int userId) {
        if (!mHasFeature) {
            return true;
        }

        Preconditions.checkStringNotEmpty(packageName, "packageName is null or empty");
        Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
                String.format(NOT_SYSTEM_CALLER_MSG,
                        "query if a notification listener service is permitted"));

        synchronized (getLockObject()) {
            ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
            if (profileOwner == null || profileOwner.permittedNotificationListeners == null) {
                return true;
            }
            return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
                    profileOwner.permittedNotificationListeners, userId);

        }
    }

    private void maybeSendAdminEnabledBroadcastLocked(int userHandle) {
        DevicePolicyData policyData = getUserData(userHandle);
        if (policyData.mAdminBroadcastPending) {
            // Send the initialization data to profile owner and delete the data
            ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
            boolean clearInitBundle = true;
            if (admin != null) {
                PersistableBundle initBundle = policyData.mInitBundle;
                clearInitBundle = sendAdminCommandLocked(admin,
                        DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
                        initBundle == null ? null : new Bundle(initBundle),
                        /* result= */ null ,
                        /* inForeground= */ true);
            }
            if (clearInitBundle) {
                // If there's no admin or we've successfully called the admin, clear the init bundle
                // otherwise, keep it around
                policyData.mInitBundle = null;
                policyData.mAdminBroadcastPending = false;
                saveSettingsLocked(userHandle);
            }
        }
    }

    @Override
    public UserHandle createAndManageUser(ComponentName admin, String name,
            ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
        Objects.requireNonNull(admin, "admin is null");
        Objects.requireNonNull(profileOwner, "profileOwner is null");
        if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
            throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
                    + admin + " are not in the same package");
        }
        final CallerIdentity caller = getCallerIdentity(admin);
        // Only allow the system user to use this method
        Preconditions.checkCallAuthorization(caller.getUserHandle().isSystem(),
                "createAndManageUser was called from non-system user");
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_CREATE_AND_MANAGE_USER);

        final boolean ephemeral = (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0;
        final boolean demo = (flags & DevicePolicyManager.MAKE_USER_DEMO) != 0
                && UserManager.isDeviceInDemoMode(mContext);
        final boolean leaveAllSystemAppsEnabled = (flags & LEAVE_ALL_SYSTEM_APPS_ENABLED) != 0;
        final int targetSdkVersion;

        // Create user.
        UserHandle user = null;
        synchronized (getLockObject()) {
            final long id = mInjector.binderClearCallingIdentity();
            try {
                targetSdkVersion = mInjector.getPackageManagerInternal().getUidTargetSdkVersion(
                        caller.getUid());

                // Return detail error code for checks inside
                // UserManagerService.createUserInternalUnchecked.
                DeviceStorageMonitorInternal deviceStorageMonitorInternal =
                        LocalServices.getService(DeviceStorageMonitorInternal.class);
                if (deviceStorageMonitorInternal.isMemoryLow()) {
                    if (targetSdkVersion >= Build.VERSION_CODES.P) {
                        throw new ServiceSpecificException(
                                UserManager.USER_OPERATION_ERROR_LOW_STORAGE, "low device storage");
                    } else {
                        return null;
                    }
                }

                String userType = demo ? UserManager.USER_TYPE_FULL_DEMO
                        : UserManager.USER_TYPE_FULL_SECONDARY;
                int userInfoFlags = ephemeral ? UserInfo.FLAG_EPHEMERAL : 0;

                if (!mUserManager.canAddMoreUsers(userType)) {
                    if (targetSdkVersion >= Build.VERSION_CODES.P) {
                        throw new ServiceSpecificException(
                                UserManager.USER_OPERATION_ERROR_MAX_USERS, "user limit reached");
                    } else {
                        return null;
                    }
                }

                String[] disallowedPackages = null;
                if (!leaveAllSystemAppsEnabled) {
                    disallowedPackages = mOverlayPackagesProvider.getNonRequiredApps(admin,
                            UserHandle.myUserId(), ACTION_PROVISION_MANAGED_USER).toArray(
                            new String[0]);
                }

                Object token = new Object();
                Slogf.d(LOG_TAG, "Adding new pending token: " + token);
                mPendingUserCreatedCallbackTokens.add(token);
                try {
                    UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
                            userType, userInfoFlags, disallowedPackages, token);
                    if (userInfo != null) {
                        user = userInfo.getUserHandle();
                    }
                } catch (UserManager.CheckedUserOperationException e) {
                    Slogf.e(LOG_TAG, "Couldn't createUserEvenWhenDisallowed", e);
                }
            } finally {
                mInjector.binderRestoreCallingIdentity(id);
            }
        } // synchronized

        if (user == null) {
            if (targetSdkVersion >= Build.VERSION_CODES.P) {
                throw new ServiceSpecificException(UserManager.USER_OPERATION_ERROR_UNKNOWN,
                        "failed to create user");
            } else {
                return null;
            }
        }

        final int userHandle = user.getIdentifier();
        final long id = mInjector.binderClearCallingIdentity();
        try {
            maybeInstallDevicePolicyManagementRoleHolderInUser(userHandle);

            manageUserUnchecked(admin, profileOwner, userHandle, adminExtras,
                    /* showDisclaimer= */ true);

            if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
                Settings.Secure.putIntForUser(mContext.getContentResolver(),
                        Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
            }

            sendProvisioningCompletedBroadcast(
                    userHandle, ACTION_PROVISION_MANAGED_USER, leaveAllSystemAppsEnabled);

            return user;
        } catch (Throwable re) {
            mUserManager.removeUser(userHandle);
            if (targetSdkVersion >= Build.VERSION_CODES.P) {
                throw new ServiceSpecificException(UserManager.USER_OPERATION_ERROR_UNKNOWN,
                        re.getMessage());
            } else {
                return null;
            }
        } finally {
            mInjector.binderRestoreCallingIdentity(id);
        }
    }

    private void sendProvisioningCompletedBroadcast(
            int user, String action, boolean leaveAllSystemAppsEnabled) {
        final Intent intent = new Intent(DevicePolicyManager.ACTION_PROVISIONING_COMPLETED)
                .putExtra(Intent.EXTRA_USER_HANDLE, user)
                .putExtra(Intent.EXTRA_USER, UserHandle.of(user))
                .putExtra(
                        DevicePolicyManager.EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED,
                        leaveAllSystemAppsEnabled)
                .putExtra(DevicePolicyManager.EXTRA_PROVISIONING_ACTION,
                        action)
                .setPackage(getManagedProvisioningPackage(mContext))
                .addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        mContext.sendBroadcastAsUser(intent, UserHandle.SYSTEM);
    }

    private void manageUserUnchecked(ComponentName admin, ComponentName profileOwner,
            @UserIdInt int userId, @Nullable PersistableBundle adminExtras,
            boolean showDisclaimer) {
        synchronized (getLockObject()) {
            if (VERBOSE_LOG) {
                Slogf.v(LOG_TAG, "manageUserUnchecked(): admin=" + admin + ", po=" + profileOwner
                        + ", userId=" + userId + ", hasAdminExtras=" + (adminExtras != null)
                        + ", showDisclaimer=" + showDisclaimer);
            }
        }
        final String adminPkg = admin.getPackageName();
        mInjector.binderWithCleanCallingIdentity(() -> {
            try {
                // Install the profile owner if not present.
                if (!mIPackageManager.isPackageAvailable(adminPkg, userId)) {
                    mIPackageManager.installExistingPackageAsUser(adminPkg, userId,
                            PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
                            PackageManager.INSTALL_REASON_POLICY,
                            /* allowlistedRestrictedPermissions= */ null);
                }
            } catch (RemoteException e) {
                // Does not happen, same process
                Slogf.wtf(LOG_TAG, e, "Failed to install admin package %s for user %d",
                        adminPkg, userId);
            }
        });

        // Set admin.
        setActiveAdmin(profileOwner, /* refreshing= */ true, userId);
        setProfileOwner(profileOwner, userId);

        synchronized (getLockObject()) {
            DevicePolicyData policyData = getUserData(userId);
            policyData.mInitBundle = adminExtras;
            policyData.mAdminBroadcastPending = true;
            policyData.mNewUserDisclaimer = showDisclaimer
                    ? DevicePolicyData.NEW_USER_DISCLAIMER_NEEDED
                    : DevicePolicyData.NEW_USER_DISCLAIMER_NOT_NEEDED;
            saveSettingsLocked(userId);

        }
    }

    private void handleNewUserCreated(UserInfo user, @Nullable Object token) {
        if (VERBOSE_LOG) {
            Slogf.v(LOG_TAG, "handleNewUserCreated(): user=" + user.toFullString()
                    + ", token=" + token);
        }

        mDevicePolicyEngine.handleUserCreated(user);

        final int userId = user.id;
        if (token != null) {
            synchronized (getLockObject()) {
                if (mPendingUserCreatedCallbackTokens.contains(token)) {
                    // Ignore because it was triggered by createAndManageUser()
                    Slogf.d(LOG_TAG, "handleNewUserCreated(): ignoring for user " + userId
                            + " due to token " + token);
                    mPendingUserCreatedCallbackTokens.remove(token);
                    return;
                }
            }
        }

        if (!mOwners.hasDeviceOwner() || !user.isFull() || user.isManagedProfile()
                || user.isGuest()) {
            return;
        }

        if (mInjector.userManagerIsHeadlessSystemUserMode()) {
            ComponentName admin = mOwners.getDeviceOwnerComponent();
            Slogf.i(LOG_TAG, "Automatically setting profile owner (" + admin + ") on new user "
                    + userId);
            manageUserUnchecked(/* deviceOwner= */ admin, /* profileOwner= */ admin,
                    /* managedUser= */ userId, /* adminExtras= */ null, /* showDisclaimer= */ true);
        } else {
            Slogf.i(LOG_TAG, "User %d added on DO mode; setting ShowNewUserDisclaimer", userId);
            setShowNewUserDisclaimer(userId, DevicePolicyData.NEW_USER_DISCLAIMER_NEEDED);
        }
    }

    @Override
    public void acknowledgeNewUserDisclaimer(@UserIdInt int userId) {
        CallerIdentity callerIdentity = getCallerIdentity();
        Preconditions.checkCallAuthorization(canManageUsers(callerIdentity)
                || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS));

        setShowNewUserDisclaimer(userId, DevicePolicyData.NEW_USER_DISCLAIMER_ACKNOWLEDGED);
    }

    private void setShowNewUserDisclaimer(@UserIdInt int userId, String value) {
        Slogf.i(LOG_TAG, "Setting new user disclaimer for user " + userId + " as " + value);
        synchronized (getLockObject()) {
            DevicePolicyData policyData = getUserData(userId);
            policyData.mNewUserDisclaimer = value;
            saveSettingsLocked(userId);
        }
    }

    private void showNewUserDisclaimerIfNecessary(@UserIdInt int userId) {
        boolean mustShow;
        synchronized (getLockObject()) {
            DevicePolicyData policyData = getUserData(userId);
            if (VERBOSE_LOG) {
                Slogf.v(LOG_TAG, "showNewUserDisclaimerIfNecessary(" + userId + "): "
                        + policyData.mNewUserDisclaimer + ")");
            }
            mustShow = DevicePolicyData.NEW_USER_DISCLAIMER_NEEDED
                    .equals(policyData.mNewUserDisclaimer);
        }
        if (!mustShow) return;

        Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_NEW_USER_DISCLAIMER);

        // TODO(b/172691310): add CTS tests to make sure disclaimer is shown
        Slogf.i(LOG_TAG, "Dispatching ACTION_SHOW_NEW_USER_DISCLAIMER intent");
        mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
    }

    @Override
    public boolean isNewUserDisclaimerAcknowledged(@UserIdInt int userId) {
        CallerIdentity callerIdentity = getCallerIdentity();
        Preconditions.checkCallAuthorization(canManageUsers(callerIdentity)
                || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS));
        synchronized (getLockObject()) {
            DevicePolicyData policyData = getUserData(userId);
            return policyData.isNewUserDisclaimerAcknowledged();
        }
    }

    @Override
    public boolean removeUser(ComponentName who, UserHandle userHandle) {
        Objects.requireNonNull(who, "ComponentName is null");
        Objects.requireNonNull(userHandle, "UserHandle is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REMOVE_USER);

        return mInjector.binderWithCleanCallingIdentity(() -> {
            String restriction = isManagedProfile(userHandle.getIdentifier())
                    ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE
                    : UserManager.DISALLOW_REMOVE_USER;
            if (isAdminAffectedByRestriction(who, restriction, caller.getUserId())) {
                Slogf.w(LOG_TAG, "The device owner cannot remove a user because %s is enabled, and "
                        + "was not set by the device owner", restriction);
                return false;
            }
            return mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle.getIdentifier());
        });
    }

    private boolean isAdminAffectedByRestriction(
            @Nullable ComponentName admin, String userRestriction, int userId) {
        switch (mUserManager.getUserRestrictionSource(userRestriction, UserHandle.of(userId))) {
            case UserManager.RESTRICTION_NOT_SET:
                return false;
            case UserManager.RESTRICTION_SOURCE_DEVICE_OWNER:
            case UserManager.RESTRICTION_SOURCE_PROFILE_OWNER:
                return !(isDeviceOwner(admin, userId) || isProfileOwner(admin, userId));
            default:
                return true;
        }
    }

    @Override
    public boolean switchUser(ComponentName who, UserHandle userHandle) {
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SWITCH_USER);

        boolean switched = false;
        // Save previous logout user id in case of failure
        int logoutUserId = getLogoutUserIdUnchecked();
        synchronized (getLockObject()) {
            long id = mInjector.binderClearCallingIdentity();
            try {
                int userId = UserHandle.USER_SYSTEM;
                if (userHandle != null) {
                    userId = userHandle.getIdentifier();
                }
                Slogf.i(LOG_TAG, "Switching to user %d (logout user is %d)", userId, logoutUserId);
                setLogoutUserIdLocked(UserHandle.USER_CURRENT);
                switched = mInjector.getIActivityManager().switchUser(userId);
                if (!switched) {
                    Slogf.w(LOG_TAG, "Failed to switch to user %d", userId);
                } else {
                    Slogf.d(LOG_TAG, "Switched");
                }
                return switched;
            } catch (RemoteException e) {
                Slogf.e(LOG_TAG, "Couldn't switch user", e);
                return false;
            } finally {
                mInjector.binderRestoreCallingIdentity(id);
                if (!switched) {
                    setLogoutUserIdLocked(logoutUserId);
                }
            }
        }
    }

    @Override
    public int getLogoutUserId() {
        Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())
                || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS));

        return getLogoutUserIdUnchecked();
    }

    private @UserIdInt int getLogoutUserIdUnchecked() {
        synchronized (getLockObject()) {
            return mLogoutUserId;
        }
    }

    private void clearLogoutUser() {
        synchronized (getLockObject()) {
            setLogoutUserIdLocked(UserHandle.USER_NULL);
        }
    }

    @GuardedBy("getLockObject()")
    private void setLogoutUserIdLocked(@UserIdInt int userId) {
        if (userId == UserHandle.USER_CURRENT) {
            userId = getCurrentForegroundUserId();
        }

        Slogf.d(LOG_TAG, "setLogoutUserId(): %d -> %d", mLogoutUserId, userId);
        mLogoutUserId = userId;
    }

    @Override
    public int startUserInBackground(ComponentName who, UserHandle userHandle) {
        Objects.requireNonNull(who, "ComponentName is null");
        Objects.requireNonNull(userHandle, "UserHandle is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_START_USER_IN_BACKGROUND);

        final int userId = userHandle.getIdentifier();
        if (isManagedProfile(userId)) {
            Slogf.w(LOG_TAG, "Managed profile cannot be started in background");
            return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE;
        }

        final long id = mInjector.binderClearCallingIdentity();
        try {
            if (!mInjector.getActivityManagerInternal().canStartMoreUsers()) {
                Slogf.w(LOG_TAG, "Cannot start user %d, too many users in background", userId);
                return UserManager.USER_OPERATION_ERROR_MAX_RUNNING_USERS;
            }

            Slogf.i(LOG_TAG, "Starting user %d in background", userId);
            if (mInjector.getIActivityManager().startUserInBackground(userId)) {
                return UserManager.USER_OPERATION_SUCCESS;
            } else {
                Slogf.w(LOG_TAG, "failed to start user %d in background", userId);
                return UserManager.USER_OPERATION_ERROR_UNKNOWN;
            }
        } catch (RemoteException e) {
            // Same process, should not happen.
            return UserManager.USER_OPERATION_ERROR_UNKNOWN;
        } finally {
            mInjector.binderRestoreCallingIdentity(id);
        }
    }

    @Override
    public int stopUser(ComponentName who, UserHandle userHandle) {
        Objects.requireNonNull(who, "ComponentName is null");
        Objects.requireNonNull(userHandle, "UserHandle is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_STOP_USER);

        final int userId = userHandle.getIdentifier();
        if (isManagedProfile(userId)) {
            Slogf.w(LOG_TAG, "Managed profile cannot be stopped");
            return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE;
        }

        return stopUserUnchecked(userId);
    }

    @Override
    public int logoutUser(ComponentName who) {
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isProfileOwner(caller) || isDefaultDeviceOwner(caller));
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_LOGOUT_USER);

        final int callingUserId = caller.getUserId();
        synchronized (getLockObject()) {
            if (!isUserAffiliatedWithDeviceLocked(callingUserId)) {
                throw new SecurityException("Admin " + who +
                        " is neither the device owner or affiliated user's profile owner.");
            }
        }

        if (isManagedProfile(callingUserId)) {
            Slogf.w(LOG_TAG, "Managed profile cannot be logout");
            return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE;
        }

        if (callingUserId != mInjector
                .binderWithCleanCallingIdentity(() -> getCurrentForegroundUserId())) {
            Slogf.d(LOG_TAG, "logoutUser(): user %d is in background, just stopping, not switching",
                    callingUserId);
            return stopUserUnchecked(callingUserId);
        }

        return logoutUserUnchecked(/* userIdToStop= */ callingUserId);
    }

    @Override
    public int logoutUserInternal() {
        CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(canManageUsers(caller)
                || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS));

        int currentUserId = getCurrentForegroundUserId();
        if (VERBOSE_LOG) {
            Slogf.v(LOG_TAG, "logout() called by uid %d; current user is %d", caller.getUid(),
                    currentUserId);
        }
        int result = logoutUserUnchecked(currentUserId);
        if (VERBOSE_LOG) {
            Slogf.v(LOG_TAG, "Result of logout(): %d", result);
        }
        return result;
    }

    private int logoutUserUnchecked(@UserIdInt int userIdToStop) {
        int logoutUserId = getLogoutUserIdUnchecked();
        if (logoutUserId == UserHandle.USER_NULL) {
            // Could happen on devices using headless system user mode when called before calling
            // switchUser() or startUserInBackground() first
            Slogf.w(LOG_TAG, "logoutUser(): could not determine which user to switch to");
            return UserManager.USER_OPERATION_ERROR_UNKNOWN;
        }
        final long id = mInjector.binderClearCallingIdentity();
        try {
            Slogf.i(LOG_TAG, "logoutUser(): switching to user %d", logoutUserId);
            if (!mInjector.getIActivityManager().switchUser(logoutUserId)) {
                Slogf.w(LOG_TAG, "Failed to switch to user %d", logoutUserId);
                // This should never happen as target user is determined by getPreviousUserId()
                return UserManager.USER_OPERATION_ERROR_UNKNOWN;
            }
            clearLogoutUser();
        } catch (RemoteException e) {
            // Same process, should not happen.
            return UserManager.USER_OPERATION_ERROR_UNKNOWN;
        } finally {
            mInjector.binderRestoreCallingIdentity(id);
        }

        return stopUserUnchecked(userIdToStop);
    }

    private int stopUserUnchecked(@UserIdInt int userId) {
        Slogf.i(LOG_TAG, "Stopping user %d", userId);
        final long id = mInjector.binderClearCallingIdentity();
        try {
            switch (mInjector.getIActivityManager().stopUser(userId, true /*force*/, null)) {
                case ActivityManager.USER_OP_SUCCESS:
                    return UserManager.USER_OPERATION_SUCCESS;
                case ActivityManager.USER_OP_IS_CURRENT:
                    return UserManager.USER_OPERATION_ERROR_CURRENT_USER;
                default:
                    return UserManager.USER_OPERATION_ERROR_UNKNOWN;
            }
        } catch (RemoteException e) {
            // Same process, should not happen.
            return UserManager.USER_OPERATION_ERROR_UNKNOWN;
        } finally {
            mInjector.binderRestoreCallingIdentity(id);
        }
    }

    @Override
    public List<UserHandle> getSecondaryUsers(ComponentName who) {
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));

        return mInjector.binderWithCleanCallingIdentity(() -> {
            final List<UserInfo> userInfos = mInjector.getUserManager().getAliveUsers();
            final List<UserHandle> userHandles = new ArrayList<>();
            for (UserInfo userInfo : userInfos) {
                UserHandle userHandle = userInfo.getUserHandle();
                if (!userHandle.isSystem() && !isManagedProfile(userHandle.getIdentifier())) {
                    userHandles.add(userInfo.getUserHandle());
                }
            }
            return userHandles;
        });
    }

    @Override
    public boolean isEphemeralUser(ComponentName who) {
        Objects.requireNonNull(who, "ComponentName is null");

        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || isProfileOwner(caller));

        return mInjector.binderWithCleanCallingIdentity(
                () -> mInjector.getUserManager().isUserEphemeral(caller.getUserId()));
    }

    @Override
    public Bundle getApplicationRestrictions(ComponentName who, String callerPackage,
            String packageName) {
        final CallerIdentity caller = getCallerIdentity(who, callerPackage);

        if (isUnicornFlagEnabled()) {
            EnforcingAdmin enforcingAdmin = enforceCanQueryAndGetEnforcingAdmin(
                    who,
                    MANAGE_DEVICE_POLICY_APP_RESTRICTIONS,
                    caller.getPackageName(),
                    caller.getUserId()
            );

            LinkedHashMap<EnforcingAdmin, PolicyValue<Bundle>> policies =
                    mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
                            PolicyDefinition.APPLICATION_RESTRICTIONS(packageName),
                            caller.getUserId());
            if (policies.isEmpty() || !policies.containsKey(enforcingAdmin)) {
                return Bundle.EMPTY;
            }
            return policies.get(enforcingAdmin).getValue();
        } else {
            Preconditions.checkCallAuthorization((caller.hasAdminComponent()
                    && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
                    || (caller.hasPackage() && isCallerDelegate(caller,
                    DELEGATION_APP_RESTRICTIONS)));
            return mInjector.binderWithCleanCallingIdentity(() -> {
                Bundle bundle = mUserManager.getApplicationRestrictions(packageName,
                        caller.getUserHandle());
                // if no restrictions were saved, mUserManager.getApplicationRestrictions
                // returns null, but DPM method should return an empty Bundle as per JavaDoc
                return bundle != null ? bundle : Bundle.EMPTY;
            });
        }
    }

    /**
     * Returns the apps that are non-exempt from some policies (such as suspension), and populates
     * the given set with the apps that are exempt.
     *
     * @param packageNames apps to check
     * @param outputExemptApps will be populate with subset of {@code packageNames} that is exempt
     * from some policy restrictions
     *
     * @return subset of {@code packageNames} that is affected by some policy restrictions.
     */
    private String[] populateNonExemptAndExemptFromPolicyApps(String[] packageNames,
            Set<String> outputExemptApps) {
        Preconditions.checkArgument(outputExemptApps.isEmpty(), "outputExemptApps is not empty");
        List<String> exemptAppsList = listPolicyExemptAppsUnchecked(mContext);
        if (exemptAppsList.isEmpty()) {
            return packageNames;
        }
        // Using a set so contains() is O(1)
        Set<String> exemptApps = new HashSet<>(exemptAppsList);
        List<String> nonExemptApps = new ArrayList<>(packageNames.length);
        for (int i = 0; i < packageNames.length; i++) {
            String app = packageNames[i];
            if (exemptApps.contains(app)) {
                outputExemptApps.add(app);
            } else {
                nonExemptApps.add(app);
            }
        }
        String[] result = new String[nonExemptApps.size()];
        nonExemptApps.toArray(result);
        return result;
    }

    @Override
    public String[] setPackagesSuspended(ComponentName who, String callerPackage,
            String[] packageNames, boolean suspended) {
        final CallerIdentity caller = getCallerIdentity(who, callerPackage);
        ActiveAdmin admin;

        if (isUnicornFlagEnabled()) {
            EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                    who,
                    MANAGE_DEVICE_POLICY_PACKAGE_STATE,
                    caller.getPackageName(),
                    caller.getUserId());
            admin = enforcingAdmin.getActiveAdmin();
        } else {
            Preconditions.checkCallAuthorization((caller.hasAdminComponent()
                    && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
                    || (caller.hasPackage() && isCallerDelegate(caller,
                    DELEGATION_PACKAGE_ACCESS)));
            synchronized (getLockObject()) {
                admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
            }
        }
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_PACKAGES_SUSPENDED);

        // Must remove the exempt apps from the input before calling PM, then add them back to
        // the array returned to the caller
        Set<String> exemptApps = new HashSet<>();
        packageNames = populateNonExemptAndExemptFromPolicyApps(packageNames, exemptApps);

        String[] nonSuspendedPackages = null;
        synchronized (getLockObject()) {
            long id = mInjector.binderClearCallingIdentity();
            try {
                nonSuspendedPackages = mInjector.getPackageManagerInternal()
                        .setPackagesSuspendedByAdmin(caller.getUserId(), packageNames, suspended);
            } finally {
                mInjector.binderRestoreCallingIdentity(id);
            }
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_PACKAGES_SUSPENDED)
                .setAdmin(caller.getPackageName())
                .setBoolean(/* isDelegate */ who == null)
                .setStrings(packageNames)
                .write();

        if (nonSuspendedPackages == null) {
            Slogf.w(LOG_TAG, "PM failed to suspend packages (%s)", Arrays.toString(packageNames));
            return packageNames;
        }

        ArraySet<String> changed = new ArraySet<>(packageNames);
        if (suspended) {
            // Only save those packages that are actually suspended. If a package is exempt or is
            // unsuspendable, it is skipped.
            changed.removeAll(List.of(nonSuspendedPackages));
        } else {
            // If an admin tries to unsuspend a package that is either exempt or is not
            // suspendable, drop it from the stored list assuming it must be already unsuspended.
            changed.addAll(exemptApps);
        }

        synchronized (getLockObject()) {
            ArraySet<String> current = new ArraySet<>(admin.suspendedPackages);
            if (suspended) {
                current.addAll(changed);
            } else {
                current.removeAll(changed);
            }
            admin.suspendedPackages = current.isEmpty() ? null : new ArrayList<>(current);
            saveSettingsLocked(caller.getUserId());
        }

        if (exemptApps.isEmpty()) {
            return nonSuspendedPackages;
        }

        String[] result = buildNonSuspendedPackagesUnionArray(nonSuspendedPackages, exemptApps);
        if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Returning %s", Arrays.toString(result));
        return result;
    }

    /**
     * Returns an array containing the union of the given non-suspended packages and
     * exempt apps. Assumes both parameters are non-null and non-empty.
     */
    private String[] buildNonSuspendedPackagesUnionArray(String[] nonSuspendedPackages,
            Set<String> exemptApps) {
        String[] result = new String[nonSuspendedPackages.length + exemptApps.size()];
        int index = 0;
        for (String app : nonSuspendedPackages) {
            result[index++] = app;
        }
        for (String app : exemptApps) {
            result[index++] = app;
        }
        return result;
    }

    @Override
    public boolean isPackageSuspended(ComponentName who, String callerPackage, String packageName) {
        final CallerIdentity caller = getCallerIdentity(who, callerPackage);

        if (isUnicornFlagEnabled()) {
            enforcePermission(
                    MANAGE_DEVICE_POLICY_PACKAGE_STATE,
                    caller.getPackageName(),
                    caller.getUserId());
        } else {
            Preconditions.checkCallAuthorization((caller.hasAdminComponent()
                    && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
                    || (caller.hasPackage() && isCallerDelegate(caller,
                    DELEGATION_PACKAGE_ACCESS)));
        }

        synchronized (getLockObject()) {
            long id = mInjector.binderClearCallingIdentity();
            try {
                return mIPackageManager.isPackageSuspendedForUser(packageName, caller.getUserId());
            } catch (RemoteException re) {
                // Shouldn't happen.
                Slogf.e(LOG_TAG, "Failed talking to the package manager", re);
            } finally {
                mInjector.binderRestoreCallingIdentity(id);
            }
            return false;
        }
    }

    @Override
    public List<String> listPolicyExemptApps() {
        CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS)
                        || isDefaultDeviceOwner(caller) || isProfileOwner(caller));

        return listPolicyExemptAppsUnchecked(mContext);
    }

    private static List<String> listPolicyExemptAppsUnchecked(Context context) {
        // TODO(b/181238156): decide whether it should only list the apps set by the resources,
        // or also the "critical" apps defined by PersonalAppsSuspensionHelper (like SMS app).
        // If it's the latter, refactor PersonalAppsSuspensionHelper so it (or a superclass) takes
        // the resources on constructor.
        String[] core = context.getResources().getStringArray(R.array.policy_exempt_apps);
        String[] vendor = context.getResources().getStringArray(R.array.vendor_policy_exempt_apps);

        int size = core.length + vendor.length;
        Set<String> apps = new ArraySet<>(size);
        for (String app : core) {
            apps.add(app);
        }
        for (String app : vendor) {
            apps.add(app);
        }

        return new ArrayList<>(apps);
    }

    @Override
    public void setUserRestriction(
            ComponentName who, String callerPackage, String key, boolean enabledFromThisOwner,
            boolean parent) {

        CallerIdentity caller = getCallerIdentity(who, callerPackage);
        int userId = caller.getUserId();
        int affectedUserId = parent ? getProfileParentId(userId) : userId;

        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_USER_RESTRICTION);

        if (!isDeviceOwner(caller) && !isProfileOwner(caller)) {
            EnforcingAdmin admin = enforcePermissionForUserRestriction(
                    who,
                    key,
                    caller.getPackageName(),
                    affectedUserId);
            if (!mInjector.isChangeEnabled(ENABLE_COEXISTENCE_CHANGE, callerPackage, userId)) {
                throw new IllegalStateException("Calling package is not targeting Android U.");
            }
            if (!UserRestrictionsUtils.isValidRestriction(key)) {
                throw new IllegalArgumentException("Invalid restriction key: " + key);
            }
            PolicyDefinition<Boolean> policyDefinition =
                    PolicyDefinition.getPolicyDefinitionForUserRestriction(key);
            if (enabledFromThisOwner) {
                setLocalUserRestrictionInternal(
                        admin, key, /* enabled= */ true, affectedUserId);
            } else {
                // Remove any local and global policy that was set by the admin
                if (!policyDefinition.isLocalOnlyPolicy()) {
                    setGlobalUserRestrictionInternal(admin, key, /* enabled= */ false);
                }
                if (!policyDefinition.isGlobalOnlyPolicy()) {
                    setLocalUserRestrictionInternal(admin, key, /* enabled= */ false,
                            userId);

                    int parentUserId = getProfileParentId(userId);
                    if (parentUserId != userId) {
                        setLocalUserRestrictionInternal(
                                admin, key, /* enabled= */ false, parentUserId);
                    }
                }
            }
        } else {
            if (!UserRestrictionsUtils.isValidRestriction(key)) {
                return;
            }
            Objects.requireNonNull(who, "ComponentName is null");
            EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackage);
            checkAdminCanSetRestriction(caller, parent, key);
            setBackwardCompatibleUserRestriction(
                    caller, admin, key, enabledFromThisOwner, parent);
        }
        logUserRestrictionCall(key, enabledFromThisOwner, parent, caller);
    }

    private void checkAdminCanSetRestriction(CallerIdentity caller, boolean parent, String key) {
        if (parent) {
            Preconditions.checkCallAuthorization(
                    isProfileOwnerOfOrganizationOwnedDevice(caller));
        } else {
            Preconditions.checkCallAuthorization(
                    isDeviceOwner(caller) || isProfileOwner(caller));
        }
        synchronized (getLockObject()) {
            if (isDefaultDeviceOwner(caller)) {
                if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
                    throw new SecurityException("Device owner cannot set user restriction "
                            + key);
                }
                Preconditions.checkArgument(!parent,
                        "Cannot use the parent instance in Device Owner mode");
            } else if (isFinancedDeviceOwner(caller)) {
                if (!UserRestrictionsUtils.canFinancedDeviceOwnerChange(key)) {
                    throw new SecurityException("Cannot set user restriction " + key
                            + " when managing a financed device");
                }
                Preconditions.checkArgument(!parent,
                        "Cannot use the parent instance in Financed Device Owner"
                                + " mode");
            } else {
                boolean profileOwnerCanChangeOnItself = !parent
                        && UserRestrictionsUtils.canProfileOwnerChange(
                        key, caller.getUserId() == getMainUserId());
                boolean orgOwnedProfileOwnerCanChangeGlobally = parent
                        && isProfileOwnerOfOrganizationOwnedDevice(caller)
                        && UserRestrictionsUtils.canProfileOwnerOfOrganizationOwnedDeviceChange(
                        key);

                if (!profileOwnerCanChangeOnItself && !orgOwnedProfileOwnerCanChangeGlobally) {
                    throw new SecurityException("Profile owner cannot set user restriction "
                            + key);
                }
            }
        }
    }
    private void setBackwardCompatibleUserRestriction(
            CallerIdentity caller, EnforcingAdmin admin, String key, boolean enabled,
            boolean parent) {
        synchronized (getLockObject()) {
            if (isDeviceOwner(caller)) {
                if (UserRestrictionsUtils.isGlobal(OWNER_TYPE_DEVICE_OWNER, key)) {
                    setGlobalUserRestrictionInternal(admin, key, enabled);
                } else {
                    setLocalUserRestrictionInternal(admin, key, enabled, caller.getUserId());
                }
            } else if (isProfileOwner(caller)) {
                if (UserRestrictionsUtils.isGlobal(OWNER_TYPE_PROFILE_OWNER, key)
                        || (parent && isProfileOwnerOfOrganizationOwnedDevice(caller)
                        && UserRestrictionsUtils.isGlobal(
                                OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE, key))) {
                    setGlobalUserRestrictionInternal(admin, key, enabled);
                } else {
                    int affectedUserId = parent
                            ? getProfileParentId(caller.getUserId()) : caller.getUserId();
                    setLocalUserRestrictionInternal(admin, key, enabled, affectedUserId);
                }
            } else {
                throw new IllegalStateException("Non-DO/Non-PO cannot set restriction " + key
                        + " while targetSdkVersion is less than UPSIDE_DOWN_CAKE");
            }
        }
    }

    @Override
    public void setUserRestrictionGlobally(String callerPackage, String key) {
        final CallerIdentity caller = getCallerIdentity(callerPackage);

        EnforcingAdmin admin = enforcePermissionForUserRestriction(
                /* who= */ null,
                key,
                caller.getPackageName(),
                UserHandle.USER_ALL
        );

        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_USER_RESTRICTION);

        if (isDeviceOwner(caller) || isProfileOwner(caller)) {
            throw new SecurityException("Admins are not allowed to call this API.");
        }
        if (!mInjector.isChangeEnabled(
                ENABLE_COEXISTENCE_CHANGE, callerPackage, caller.getUserId())) {
            throw new IllegalStateException("Calling package is not targeting Android U.");
        }
        if (!UserRestrictionsUtils.isValidRestriction(key)) {
            throw new IllegalArgumentException("Invalid restriction key: " + key);
        }

        setGlobalUserRestrictionInternal(admin, key, /* enabled= */ true);

        logUserRestrictionCall(key, /* enabled= */ true, /* parent= */ false, caller);
    }
    private void setLocalUserRestrictionInternal(
            EnforcingAdmin admin, String key, boolean enabled, int userId) {
        PolicyDefinition<Boolean> policyDefinition =
                PolicyDefinition.getPolicyDefinitionForUserRestriction(key);
        if (enabled) {
            mDevicePolicyEngine.setLocalPolicy(
                    policyDefinition,
                    admin,
                    new BooleanPolicyValue(true),
                    userId);
        } else {
            mDevicePolicyEngine.removeLocalPolicy(
                    policyDefinition,
                    admin,
                    userId);
        }
    }
    private void setGlobalUserRestrictionInternal(
            EnforcingAdmin admin, String key, boolean enabled) {
        PolicyDefinition<Boolean> policyDefinition =
                PolicyDefinition.getPolicyDefinitionForUserRestriction(key);
        if (enabled) {
            mDevicePolicyEngine.setGlobalPolicy(
                    PolicyDefinition.getPolicyDefinitionForUserRestriction(key),
                    admin,
                    new BooleanPolicyValue(true));
        } else {
            mDevicePolicyEngine.removeGlobalPolicy(
                    policyDefinition,
                    admin);
        }
    }

    private void logUserRestrictionCall(
            String key, boolean enabled, boolean parent, CallerIdentity caller) {
        final int eventId = enabled
                ? DevicePolicyEnums.ADD_USER_RESTRICTION
                : DevicePolicyEnums.REMOVE_USER_RESTRICTION;
        DevicePolicyEventLogger
                .createEvent(eventId)
                .setAdmin(caller.getComponentName())
                .setStrings(key, parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT)
                .write();
        if (SecurityLog.isLoggingEnabled()) {
            final int eventTag = enabled
                    ? SecurityLog.TAG_USER_RESTRICTION_ADDED
                    : SecurityLog.TAG_USER_RESTRICTION_REMOVED;
            SecurityLog.writeEvent(eventTag, caller.getPackageName(), caller.getUserId(), key);
        }

        Slogf.i(LOG_TAG, "Changing user restriction %s to: %b caller: %s",
                key, enabled, caller.toString());
    }

    @Override
    public Bundle getUserRestrictions(ComponentName who, String callerPackage, boolean parent) {
        if (!mHasFeature) {
            return null;
        }
        CallerIdentity caller = getCallerIdentity(who, callerPackage);
        int targetUserId = parent
                ? getProfileParentId(caller.getUserId()) : caller.getUserId();
        EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackage);
        if (isDeviceOwner(caller) || isProfileOwner(caller)) {
            Objects.requireNonNull(who, "ComponentName is null");
            Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
                    || isFinancedDeviceOwner(caller)
                    || isProfileOwner(caller)
                    || (parent && isProfileOwnerOfOrganizationOwnedDevice(caller)));

            Bundle restrictions = getUserRestrictionsFromPolicyEngine(admin, targetUserId);
            // Add global restrictions set by the admin as well.
            restrictions.putAll(
                    getUserRestrictionsFromPolicyEngine(admin, UserHandle.USER_ALL));
            return restrictions;
        } else {
            if (!mInjector.isChangeEnabled(
                    ENABLE_COEXISTENCE_CHANGE, callerPackage, caller.getUserId())) {
                throw new IllegalStateException("Calling package is not targeting Android U.");
            }
            return getUserRestrictionsFromPolicyEngine(admin, targetUserId);
        }
    }

    // Map of user restriction to permission.
    private static final HashMap<String, String[]> USER_RESTRICTION_PERMISSIONS = new HashMap<>();
    {
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, new String[]{MANAGE_DEVICE_POLICY_PROFILES});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_ADD_CLONE_PROFILE, new String[]{MANAGE_DEVICE_POLICY_PROFILES});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_ADD_PRIVATE_PROFILE, new String[]{MANAGE_DEVICE_POLICY_PROFILES});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_ADD_USER, new String[]{MANAGE_DEVICE_POLICY_MODIFY_USERS});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_ADD_WIFI_CONFIG, new String[]{MANAGE_DEVICE_POLICY_WIFI});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_ADJUST_VOLUME, new String[]{MANAGE_DEVICE_POLICY_AUDIO_OUTPUT});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_AIRPLANE_MODE, new String[]{MANAGE_DEVICE_POLICY_AIRPLANE_MODE});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_AMBIENT_DISPLAY, new String[]{MANAGE_DEVICE_POLICY_DISPLAY});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_APPS_CONTROL, new String[]{MANAGE_DEVICE_POLICY_APPS_CONTROL});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_AUTOFILL, new String[]{MANAGE_DEVICE_POLICY_AUTOFILL});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_BLUETOOTH, new String[]{MANAGE_DEVICE_POLICY_BLUETOOTH});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_BLUETOOTH_SHARING, new String[]{MANAGE_DEVICE_POLICY_BLUETOOTH});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_CAMERA, new String[]{MANAGE_DEVICE_POLICY_CAMERA});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_CAMERA_TOGGLE, new String[]{MANAGE_DEVICE_POLICY_CAMERA_TOGGLE});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_CELLULAR_2G, new String[]{MANAGE_DEVICE_POLICY_MOBILE_NETWORK});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_CHANGE_WIFI_STATE, new String[]{MANAGE_DEVICE_POLICY_WIFI});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_CONFIG_BLUETOOTH, new String[]{MANAGE_DEVICE_POLICY_BLUETOOTH});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_CONFIG_BRIGHTNESS, new String[]{MANAGE_DEVICE_POLICY_DISPLAY});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_CONFIG_CELL_BROADCASTS, new String[]{MANAGE_DEVICE_POLICY_MOBILE_NETWORK});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_CONFIG_CREDENTIALS, new String[]{MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_CONFIG_DATE_TIME, new String[]{MANAGE_DEVICE_POLICY_TIME});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_CONFIG_DEFAULT_APPS, new String[]{MANAGE_DEFAULT_APPLICATIONS});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_CONFIG_LOCALE, new String[]{MANAGE_DEVICE_POLICY_LOCALE});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_CONFIG_LOCATION, new String[]{MANAGE_DEVICE_POLICY_LOCATION});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS, new String[]{MANAGE_DEVICE_POLICY_MOBILE_NETWORK});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_CONFIG_PRIVATE_DNS, new String[]{MANAGE_DEVICE_POLICY_RESTRICT_PRIVATE_DNS});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_CONFIG_SCREEN_TIMEOUT, new String[]{MANAGE_DEVICE_POLICY_DISPLAY});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_CONFIG_TETHERING, new String[]{MANAGE_DEVICE_POLICY_MOBILE_NETWORK});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_CONFIG_VPN, new String[]{MANAGE_DEVICE_POLICY_VPN});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_CONFIG_WIFI, new String[]{MANAGE_DEVICE_POLICY_WIFI});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_CONTENT_CAPTURE, new String[]{MANAGE_DEVICE_POLICY_SCREEN_CONTENT});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_CONTENT_SUGGESTIONS, new String[]{MANAGE_DEVICE_POLICY_SCREEN_CONTENT});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_CREATE_WINDOWS, new String[]{MANAGE_DEVICE_POLICY_WINDOWS});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE, new String[]{MANAGE_DEVICE_POLICY_PROFILE_INTERACTION});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_DATA_ROAMING, new String[]{MANAGE_DEVICE_POLICY_MOBILE_NETWORK});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_DEBUGGING_FEATURES, new String[]{MANAGE_DEVICE_POLICY_DEBUGGING_FEATURES});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_FACTORY_RESET, new String[]{MANAGE_DEVICE_POLICY_FACTORY_RESET});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_FUN, new String[]{MANAGE_DEVICE_POLICY_FUN});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_INSTALL_APPS, new String[]{MANAGE_DEVICE_POLICY_APPS_CONTROL});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, new String[]{MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY, new String[]{MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_MICROPHONE_TOGGLE, new String[]{MANAGE_DEVICE_POLICY_MICROPHONE_TOGGLE});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_MODIFY_ACCOUNTS, new String[]{MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA, new String[]{MANAGE_DEVICE_POLICY_PHYSICAL_MEDIA});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_NETWORK_RESET, new String[]{MANAGE_DEVICE_POLICY_MOBILE_NETWORK});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_OUTGOING_BEAM, new String[]{MANAGE_DEVICE_POLICY_NEARBY_COMMUNICATION});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_OUTGOING_CALLS, new String[]{MANAGE_DEVICE_POLICY_CALLS});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_PRINTING, new String[]{MANAGE_DEVICE_POLICY_PRINTING});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_REMOVE_USER, new String[]{MANAGE_DEVICE_POLICY_MODIFY_USERS});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_RUN_IN_BACKGROUND, new String[]{MANAGE_DEVICE_POLICY_RUN_IN_BACKGROUND});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_SAFE_BOOT, new String[]{MANAGE_DEVICE_POLICY_SAFE_BOOT});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_SET_USER_ICON, new String[]{MANAGE_DEVICE_POLICY_MODIFY_USERS});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_SET_WALLPAPER, new String[]{MANAGE_DEVICE_POLICY_WALLPAPER});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, new String[]{MANAGE_DEVICE_POLICY_PROFILE_INTERACTION});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_SHARE_LOCATION, new String[]{MANAGE_DEVICE_POLICY_LOCATION});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_SHARING_ADMIN_CONFIGURED_WIFI, new String[]{MANAGE_DEVICE_POLICY_WIFI});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_SMS, new String[]{MANAGE_DEVICE_POLICY_SMS});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS, new String[]{MANAGE_DEVICE_POLICY_SYSTEM_DIALOGS});
        if (com.android.net.thread.platform.flags.Flags.threadUserRestrictionEnabled()) {
            USER_RESTRICTION_PERMISSIONS.put(
                    UserManager.DISALLOW_THREAD_NETWORK,
                    new String[]{MANAGE_DEVICE_POLICY_THREAD_NETWORK});
        }
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_ULTRA_WIDEBAND_RADIO, new String[]{MANAGE_DEVICE_POLICY_NEARBY_COMMUNICATION});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_UNIFIED_PASSWORD, new String[]{MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_UNINSTALL_APPS, new String[]{MANAGE_DEVICE_POLICY_APPS_CONTROL});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_UNMUTE_DEVICE, new String[]{MANAGE_DEVICE_POLICY_AUDIO_OUTPUT});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_UNMUTE_MICROPHONE, new String[]{MANAGE_DEVICE_POLICY_MICROPHONE});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_USB_FILE_TRANSFER, new String[]{MANAGE_DEVICE_POLICY_USB_FILE_TRANSFER});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_USER_SWITCH, new String[]{MANAGE_DEVICE_POLICY_MODIFY_USERS});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_WIFI_DIRECT, new String[]{MANAGE_DEVICE_POLICY_WIFI});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_WIFI_TETHERING, new String[]{MANAGE_DEVICE_POLICY_WIFI});
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.ENSURE_VERIFY_APPS, new String[]{MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES});

        // Restrictions not allowed to be set by admins.
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_RECORD_AUDIO, null);
        USER_RESTRICTION_PERMISSIONS.put(
                UserManager.DISALLOW_WALLPAPER, null);
    }

    private EnforcingAdmin enforcePermissionForUserRestriction(ComponentName who,
            String userRestriction, String callerPackageName, int userId) {
        String[] permissions = USER_RESTRICTION_PERMISSIONS.get(userRestriction);
        if (permissions.length > 0) {
            try {
                return enforcePermissionsAndGetEnforcingAdmin(who, permissions, callerPackageName,
                        userId);
            } catch (SecurityException e) {
                throw new SecurityException("Caller does not hold the required permission for this "
                        + "user restriction: " + userRestriction + ".\n" + e.getMessage());
            }
         }
        throw new SecurityException("Admins are not permitted to set User Restriction: "
                + userRestriction);
    }

    @Override
    public Bundle getUserRestrictionsGlobally(String callerPackage) {
        if (!mHasFeature) {
            return null;
        }
        final CallerIdentity caller = getCallerIdentity(callerPackage);
        EnforcingAdmin admin = getEnforcingAdminForCaller(/*who=*/ null, caller.getPackageName());

        return getUserRestrictionsFromPolicyEngine(admin,
                UserHandle.USER_ALL);
    }

    /**
     * Returns user restrictions set by the given admin for the provided {@code userId}.
     *
     * <p>Pass in {@link UserHandle#USER_ALL} for {@code userId} to get global restrictions set by
     * the admin
     */
    private Bundle getUserRestrictionsFromPolicyEngine(EnforcingAdmin admin, int userId) {
        Set<UserRestrictionPolicyKey> restrictionKeys =
                mDevicePolicyEngine.getUserRestrictionPolicyKeysForAdmin(
                        admin,
                        userId);
        Bundle restrictions = new Bundle();
        for (UserRestrictionPolicyKey key : restrictionKeys) {
            restrictions.putBoolean(key.getRestriction(), true);
        }
        return restrictions;
    }

    @Override
    public boolean setApplicationHidden(ComponentName who, String callerPackage, String packageName,
            boolean hidden, boolean parent) {
        CallerIdentity caller = getCallerIdentity(who, callerPackage);
        final int userId = parent ? getProfileParentId(caller.getUserId()) : caller.getUserId();
        enforcePermission(MANAGE_DEVICE_POLICY_PACKAGE_STATE, caller.getPackageName(), userId);

        List<String> exemptApps = listPolicyExemptAppsUnchecked(mContext);
        if (exemptApps.contains(packageName)) {
            Slogf.d(LOG_TAG, "setApplicationHidden(): ignoring %s as it's on policy-exempt list",
                    packageName);
            return false;
        }

        boolean result;
        synchronized (getLockObject()) {
            if (parent) {
                // Ensure the package provided is a system package, this is to ensure that this
                // API cannot be used to leak if certain non-system package exists in the person
                // profile.
                mInjector.binderWithCleanCallingIdentity(() ->
                        enforcePackageIsSystemPackage(packageName, userId));
            }
            checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_APPLICATION_HIDDEN);

            if (VERBOSE_LOG) {
                Slogf.v(LOG_TAG, "calling pm.setApplicationHiddenSettingAsUser(%s, %b, %d)",
                        packageName, hidden, userId);
            }
            EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackage);
            mDevicePolicyEngine.setLocalPolicy(
                    PolicyDefinition.APPLICATION_HIDDEN(packageName),
                    admin,
                    new BooleanPolicyValue(hidden),
                    userId);
            result = mInjector.binderWithCleanCallingIdentity(() -> {
                try {
                    // This is a best effort to continue returning the same value that was
                    // returned before the policy engine migration.
                    return mInjector.getIPackageManager().getPackageInfo(
                            packageName, MATCH_UNINSTALLED_PACKAGES, userId) != null
                            && (mIPackageManager.getApplicationHiddenSettingAsUser(
                                    packageName, userId) == hidden);
                } catch (RemoteException e) {
                    return false;
                }
            });
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_APPLICATION_HIDDEN)
                .setAdmin(caller.getPackageName())
                .setBoolean(/* isDelegate */ isCallerDelegate(caller))
                .setStrings(packageName, hidden ? "hidden" : "not_hidden",
                        parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT)
                .write();
        return result;
    }

    @Override
    public boolean isApplicationHidden(ComponentName who, String callerPackage,
            String packageName, boolean parent) {
        CallerIdentity caller = getCallerIdentity(who, callerPackage);
        int userId = parent ? getProfileParentId(caller.getUserId()) : caller.getUserId();
        // TODO: Also support DELEGATION_PACKAGE_ACCESS
        enforcePermission(MANAGE_DEVICE_POLICY_PACKAGE_STATE, caller.getPackageName(), userId);

        synchronized (getLockObject()) {
            if (parent) {
                // Ensure the package provided is a system package.
                mInjector.binderWithCleanCallingIdentity(() ->
                        enforcePackageIsSystemPackage(packageName, userId));
            }

            return mInjector.binderWithCleanCallingIdentity(
                    () -> mIPackageManager.getApplicationHiddenSettingAsUser(packageName, userId));
        }
    }

    private void enforcePackageIsSystemPackage(String packageName, int userId)
            throws RemoteException {
        boolean isSystem;
        try {
            isSystem = isSystemApp(mIPackageManager, packageName, userId);
        } catch (IllegalArgumentException e) {
            isSystem = false;
        }
        if (!isSystem) {
            throw new IllegalArgumentException("The provided package is not a system package");
        }
    }

    @Override
    public void enableSystemApp(ComponentName who, String callerPackage, String packageName) {
        final CallerIdentity caller = getCallerIdentity(who, callerPackage);
        Preconditions.checkCallAuthorization((caller.hasAdminComponent()
                && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
                || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_ENABLE_SYSTEM_APP)));

        final boolean isDemo = isCurrentUserDemo();
        int userId = caller.getUserId();
        long id = mInjector.binderClearCallingIdentity();
        try {
            if (VERBOSE_LOG) {
                Slogf.v(LOG_TAG, "installing " + packageName + " for " + userId);
            }

            Preconditions.checkArgument(isDemo || isSystemApp(mIPackageManager, packageName,
                    getProfileParentId(userId)), "Only system apps can be enabled this way");

            // Install the app.
            mIPackageManager.installExistingPackageAsUser(packageName, userId,
                    PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
                    PackageManager.INSTALL_REASON_POLICY, null);
            if (isDemo) {
                // Ensure the app is also ENABLED for demo users.
                mIPackageManager.setApplicationEnabledSetting(packageName,
                        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                        PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
            }
        } catch (RemoteException re) {
            // shouldn't happen
            Slogf.wtf(LOG_TAG, "Failed to install " + packageName, re);
        } finally {
            mInjector.binderRestoreCallingIdentity(id);
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.ENABLE_SYSTEM_APP)
                .setAdmin(caller.getPackageName())
                .setBoolean(/* isDelegate */ who == null)
                .setStrings(packageName)
                .write();
    }

    @Override
    public int enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent) {
        final CallerIdentity caller = getCallerIdentity(who, callerPackage);
        Preconditions.checkCallAuthorization((caller.hasAdminComponent()
                && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
                || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_ENABLE_SYSTEM_APP)));

        int numberOfAppsInstalled = 0;
        long id = mInjector.binderClearCallingIdentity();
        try {
            final int parentUserId = getProfileParentId(caller.getUserId());
            List<ResolveInfo> activitiesToEnable = mIPackageManager
                    .queryIntentActivities(intent,
                            intent.resolveTypeIfNeeded(mContext.getContentResolver()),
                            PackageManager.MATCH_DIRECT_BOOT_AWARE
                                    | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
                            parentUserId)
                    .getList();

            if (VERBOSE_LOG) {
                Slogf.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
            }
            if (activitiesToEnable != null) {
                for (ResolveInfo info : activitiesToEnable) {
                    if (info.activityInfo != null) {
                        String packageName = info.activityInfo.packageName;
                        if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
                            numberOfAppsInstalled++;
                            mIPackageManager.installExistingPackageAsUser(packageName,
                                    caller.getUserId(),
                                    PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
                                    PackageManager.INSTALL_REASON_POLICY, null);
                        } else {
                            Slogf.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
                                    + " system app");
                        }
                    }
                }
            }
        } catch (RemoteException e) {
            // shouldn't happen
            Slogf.wtf(LOG_TAG, "Failed to resolve intent for: " + intent, e);
            return 0;
        } finally {
            mInjector.binderRestoreCallingIdentity(id);
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.ENABLE_SYSTEM_APP_WITH_INTENT)
                .setAdmin(caller.getPackageName())
                .setBoolean(/* isDelegate */ who == null)
                .setStrings(intent.getAction())
                .write();
        return numberOfAppsInstalled;
    }

    private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
            throws RemoteException {
        ApplicationInfo appInfo = pm.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES,
                userId);
        if (appInfo == null) {
            throw new IllegalArgumentException("The application " + packageName +
                    " is not present on this device");
        }
        return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
    }

    @Override
    public boolean installExistingPackage(ComponentName who, String callerPackage,
            String packageName) {
        final CallerIdentity caller = getCallerIdentity(who, callerPackage);
        Preconditions.checkCallAuthorization((caller.hasAdminComponent()
                && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
                || (caller.hasPackage()
                && isCallerDelegate(caller, DELEGATION_INSTALL_EXISTING_PACKAGE)));

        boolean result;
        synchronized (getLockObject()) {
            Preconditions.checkCallAuthorization(
                    isUserAffiliatedWithDeviceLocked(caller.getUserId()),
                            "Admin %s is neither the device owner or "
                                    + "affiliated user's profile owner.", who);
            final long id = mInjector.binderClearCallingIdentity();
            try {
                if (VERBOSE_LOG) {
                    Slogf.v(LOG_TAG, "installing " + packageName + " for " + caller.getUserId());
                }

                // Install the package.
                result = mIPackageManager.installExistingPackageAsUser(packageName,
                        caller.getUserId(),
                        PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
                        PackageManager.INSTALL_REASON_POLICY, null)
                        == PackageManager.INSTALL_SUCCEEDED;
            } catch (RemoteException re) {
                // shouldn't happen
                Slogf.wtf(LOG_TAG, "Error installing package", re);
                return false;
            } finally {
                mInjector.binderRestoreCallingIdentity(id);
            }
        }
        if (result) {
            DevicePolicyEventLogger
                    .createEvent(DevicePolicyEnums.INSTALL_EXISTING_PACKAGE)
                    .setAdmin(caller.getPackageName())
                    .setBoolean(/* isDelegate */ who == null)
                    .setStrings(packageName)
                    .write();
        }
        return result;
    }

    @Override
    public void setAccountManagementDisabled(ComponentName who, String callerPackageName,
            String accountType, boolean disabled, boolean parent) {
        if (!mHasFeature) {
            return;
        }

        enforceMaxStringLength(accountType, "account type");

        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
        synchronized (getLockObject()) {
            int affectedUser = getAffectedUser(parent);
            EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                    who,
                    MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT,
                    caller.getPackageName(),
                    affectedUser
            );
            if (disabled) {
                mDevicePolicyEngine.setLocalPolicy(
                        PolicyDefinition.ACCOUNT_MANAGEMENT_DISABLED(accountType),
                        enforcingAdmin,
                        new BooleanPolicyValue(disabled),
                        affectedUser);
            } else {
                mDevicePolicyEngine.removeLocalPolicy(
                        PolicyDefinition.ACCOUNT_MANAGEMENT_DISABLED(accountType),
                        enforcingAdmin,
                        affectedUser);
            }
        }
    }

    @Override
    public String[] getAccountTypesWithManagementDisabled(String callerPackageName) {
        return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId(),
                callerPackageName, false);
    }

    @Override
    public String[] getAccountTypesWithManagementDisabledAsUser(int userId,
            String callerPackageName, boolean parent) {
        if (!mHasFeature) {
            return null;
        }
        CallerIdentity caller = getCallerIdentity(callerPackageName);
        Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
        final ArraySet<String> resultSet = new ArraySet<>();
        int affectedUser = parent ? getProfileParentId(userId) : userId;
        if (!hasPermission(MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT,
                callerPackageName, affectedUser)
                && !hasFullCrossUsersPermission(caller, userId)) {
            throw new SecurityException("Caller does not have permission to call this on user: "
                    + affectedUser);
        }
        Set<PolicyKey> keys = mDevicePolicyEngine.getLocalPolicyKeysSetByAllAdmins(
                PolicyDefinition.GENERIC_ACCOUNT_MANAGEMENT_DISABLED,
                affectedUser);

        for (PolicyKey key : keys) {
            if (!(key instanceof AccountTypePolicyKey)) {
                throw new IllegalStateException("PolicyKey for "
                        + "MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT is not of type "
                        + "AccountTypePolicyKey");
            }
            AccountTypePolicyKey parsedKey =
                    (AccountTypePolicyKey) key;
            String accountType = Objects.requireNonNull(parsedKey.getAccountType());

            Boolean disabled = mDevicePolicyEngine.getResolvedPolicy(
                    PolicyDefinition.ACCOUNT_MANAGEMENT_DISABLED(accountType),
                    affectedUser);
            if (disabled != null && disabled) {
                resultSet.add(accountType);
            }
        }
        return resultSet.toArray(new String[resultSet.size()]);
    }

    @Override
    public void setUninstallBlocked(ComponentName who, String callerPackage, String packageName,
            boolean uninstallBlocked) {
        final CallerIdentity caller = getCallerIdentity(who, callerPackage);

        EnforcingAdmin enforcingAdmin = enforcePermissionsAndGetEnforcingAdmin(
                who,
                new String[]{
                        MANAGE_DEVICE_POLICY_APPS_CONTROL,
                        MANAGE_DEVICE_POLICY_BLOCK_UNINSTALL
                },
                caller.getPackageName(),
                caller.getUserId());
        mDevicePolicyEngine.setLocalPolicy(
                PolicyDefinition.PACKAGE_UNINSTALL_BLOCKED(packageName),
                enforcingAdmin,
                new BooleanPolicyValue(uninstallBlocked),
                caller.getUserId());

        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_UNINSTALL_BLOCKED)
                .setAdmin(caller.getPackageName())
                .setBoolean(/* isDelegate */ isCallerDelegate(caller))
                .setStrings(packageName)
                .write();
    }

    static void setUninstallBlockedUnchecked(
            String packageName, boolean uninstallBlocked, int userId) {
        Binder.withCleanCallingIdentity(() -> {
            try {
                AppGlobals.getPackageManager().setBlockUninstallForUser(
                        packageName, uninstallBlocked, userId);
            } catch (RemoteException re) {
                // Shouldn't happen.
                Slogf.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
            }
        });
        if (uninstallBlocked) {
            final PackageManagerInternal pmi = LocalServices.getService(
                    PackageManagerInternal.class);
            pmi.removeNonSystemPackageSuspensions(packageName, userId);
            pmi.removeDistractingPackageRestrictions(packageName, userId);
            pmi.flushPackageRestrictions(userId);
        }
    }

    @Override
    public boolean isUninstallBlocked(String packageName) {
        // This function should return true if and only if the package is blocked by
        // setUninstallBlocked(). It should still return false for other cases of blocks, such as
        // when the package is a system app, or when it is an active device admin.
        final int userId = UserHandle.getCallingUserId();

        synchronized (getLockObject()) {
            try {
                return mIPackageManager.getBlockUninstallForUser(packageName, userId);
            } catch (RemoteException re) {
                // Shouldn't happen.
                Slogf.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
            }
        }
        return false;
    }

    @Override
    public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
        if (!mHasFeature) {
            return;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isProfileOwner(caller));

        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
            if (disabled) {
                admin.mManagedProfileCallerIdAccess =
                        new PackagePolicy(PackagePolicy.PACKAGE_POLICY_ALLOWLIST);
            } else {
                admin.mManagedProfileCallerIdAccess =
                        new PackagePolicy(PackagePolicy.PACKAGE_POLICY_BLOCKLIST);
            }
            saveSettingsLocked(caller.getUserId());
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CALLER_ID_DISABLED)
                .setAdmin(who)
                .setBoolean(disabled)
                .write();
    }

    @Override
    public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
        if (!mHasFeature) {
            return false;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isProfileOwner(caller));

        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
            if (admin == null) {
                return false;
            }

            if (admin.mManagedProfileCallerIdAccess == null) {
                return admin.disableCallerId;
            }

            if (admin.mManagedProfileCallerIdAccess.getPolicyType()
                    == PackagePolicy.PACKAGE_POLICY_ALLOWLIST_AND_SYSTEM) {
                Slogf.w(LOG_TAG, "Denying callerId due to PACKAGE_POLICY_SYSTEM policyType");
            }

            return admin.mManagedProfileCallerIdAccess.getPolicyType()
                    != PackagePolicy.PACKAGE_POLICY_BLOCKLIST;
        }
    }

    @Override
    public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
        Preconditions.checkArgumentNonnegative(userId, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));

        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
            if (admin == null) {
                return false;
            }

            if (admin.mManagedProfileCallerIdAccess == null) {
                return admin.disableCallerId;
            }

            return admin.mManagedProfileCallerIdAccess.getPolicyType()
                    == PackagePolicy.PACKAGE_POLICY_ALLOWLIST;
        }
    }

    @Override
    public void setManagedProfileCallerIdAccessPolicy(PackagePolicy policy) {
        if (!mHasFeature) {
            return;
        }
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization((isProfileOwner(caller)
                && isManagedProfile(caller.getUserId())));
        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
            admin.disableCallerId = false;
            admin.mManagedProfileCallerIdAccess = policy;
            saveSettingsLocked(caller.getUserId());
        }
    }

    @Override
    public PackagePolicy getManagedProfileCallerIdAccessPolicy() {
        if (!mHasFeature) {
            return null;
        }
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization((isProfileOwner(caller)
                && isManagedProfile(caller.getUserId())));
        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
            return (admin != null) ? admin.mManagedProfileCallerIdAccess : null;
        }
    }

    @Override
    public boolean hasManagedProfileCallerIdAccess(int userId, String packageName) {
        Preconditions.checkArgumentNonnegative(userId, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));

        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
            if (admin != null) {
                if (admin.mManagedProfileCallerIdAccess == null) {
                    return !admin.disableCallerId;
                }
                return admin.mManagedProfileCallerIdAccess.isPackageAllowed(packageName,
                        mContactSystemRoleHolders);
            }
        }
        return true;
    }

    @Override
    public void setManagedProfileContactsAccessPolicy(PackagePolicy policy) {
        if (!mHasFeature) {
            return;
        }
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization((isProfileOwner(caller)
                && isManagedProfile(caller.getUserId())));

        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
            admin.disableContactsSearch = false;
            admin.mManagedProfileContactsAccess = policy;
            saveSettingsLocked(caller.getUserId());
        }
    }

    @Override
    public PackagePolicy getManagedProfileContactsAccessPolicy() {
        if (!mHasFeature) {
            return null;
        }

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization((isProfileOwner(caller)
                && isManagedProfile(caller.getUserId())));

        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
            return (admin != null) ? admin.mManagedProfileContactsAccess : null;
        }
    }

    @Override
    public boolean hasManagedProfileContactsAccess(int userId, String packageName) {
        Preconditions.checkArgumentNonnegative(userId, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));

        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
            if (admin != null) {
                if (admin.mManagedProfileContactsAccess == null) {
                    return !admin.disableContactsSearch;
                }

                return admin.mManagedProfileContactsAccess.isPackageAllowed(packageName,
                        mContactSystemRoleHolders);
            }
        }
        return true;
    }

    @Override
    public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
        if (!mHasFeature) {
            return;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isProfileOwner(caller));

        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
            if (disabled) {
                admin.mManagedProfileContactsAccess =
                        new PackagePolicy(PackagePolicy.PACKAGE_POLICY_ALLOWLIST);
            } else {
                admin.mManagedProfileContactsAccess =
                        new PackagePolicy(PackagePolicy.PACKAGE_POLICY_BLOCKLIST);
            }
            saveSettingsLocked(caller.getUserId());
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CONTACTS_SEARCH_DISABLED)
                .setAdmin(who)
                .setBoolean(disabled)
                .write();
    }

    @Override
    public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
        if (!mHasFeature) {
            return false;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isProfileOwner(caller));

        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
            if (admin == null) {
                return false;
            }
            if (admin.mManagedProfileContactsAccess == null) {
                return admin.disableContactsSearch;
            }
            return admin.mManagedProfileContactsAccess.getPolicyType()
                    != PackagePolicy.PACKAGE_POLICY_BLOCKLIST;
        }
    }

    @Override
    public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
        Preconditions.checkArgumentNonnegative(userId, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));

        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
            if (admin == null) {
                return false;
            }

            if (admin.mManagedProfileContactsAccess == null) {
                return admin.disableContactsSearch;
            }
            if (admin.mManagedProfileContactsAccess.getPolicyType()
                    == PackagePolicy.PACKAGE_POLICY_ALLOWLIST_AND_SYSTEM) {
                Slogf.w(LOG_TAG, "Denying contacts due to PACKAGE_POLICY_SYSTEM policyType");
            }
            return admin.mManagedProfileContactsAccess.getPolicyType()
                    != PackagePolicy.PACKAGE_POLICY_BLOCKLIST;
        }
    }

    @Override
    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
            boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
        final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
                actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
        final int callingUserId = UserHandle.getCallingUserId();

        mInjector.binderWithCleanCallingIdentity(() -> {
            synchronized (getLockObject()) {
                final int managedUserId = getManagedUserId(callingUserId);
                if (managedUserId < 0) {
                    return;
                }
                if (isCrossProfileQuickContactDisabled(managedUserId)) {
                    if (VERBOSE_LOG) {
                        Slogf.v(LOG_TAG, "Cross-profile contacts access disabled for user %d",
                                managedUserId);
                    }
                    return;
                }
                ContactsInternal.startQuickContactWithErrorToastForUser(
                        mContext, intent, new UserHandle(managedUserId));
            }
        });
    }

    /**
     * @return true if cross-profile QuickContact is disabled
     */
    private boolean isCrossProfileQuickContactDisabled(@UserIdInt int userId) {
        return getCrossProfileCallerIdDisabledForUser(userId)
                && getCrossProfileContactsSearchDisabledForUser(userId);
    }

    /**
     * @return the user ID of the managed user that is linked to the current user, if any.
     * Otherwise UserHandle.USER_NULL (-10000).
     */
    public int getManagedUserId(@UserIdInt int callingUserId) {
        if (VERBOSE_LOG) Slogf.v(LOG_TAG, "getManagedUserId: callingUserId=%d", callingUserId);

        for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
            if (ui.id == callingUserId || !ui.isManagedProfile()) {
                continue; // Caller user self, or not a managed profile.  Skip.
            }
            if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Managed user=%d", ui.id);
            return ui.id;
        }
        if (VERBOSE_LOG)  Slogf.v(LOG_TAG, "Managed user not found.");
        return UserHandle.USER_NULL;
    }

    /**
     * Returns the userId of the managed profile on the device.
     * If none exists, return {@link UserHandle#USER_NULL}.
     *
     * We assume there is only one managed profile across all users
     * on the device, which is true for now (HSUM or not) but could
     * change in future.
     */
    private @UserIdInt int getManagedUserId() {
        // On HSUM, there is only one main user and only the main user
        // can have a managed profile (for now). On non-HSUM, only user 0
        // can host the managed profile and user 0 is the main user.
        // So in both cases, we could just get the main user and
        // search for the profile user under it.
        UserHandle mainUser = mUserManager.getMainUser();
        if (mainUser == null) return UserHandle.USER_NULL;
        return getManagedUserId(mainUser.getIdentifier());
    }

    @Override
    public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
        if (!mHasFeature) {
            return;
        }
        Objects.requireNonNull(who, "ComponentName is null");

        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || isProfileOwner(caller));

        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
            if (admin.disableBluetoothContactSharing != disabled) {
                admin.disableBluetoothContactSharing = disabled;
                saveSettingsLocked(caller.getUserId());
            }
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_BLUETOOTH_CONTACT_SHARING_DISABLED)
                .setAdmin(who)
                .setBoolean(disabled)
                .write();
    }

    @Override
    public boolean getBluetoothContactSharingDisabled(ComponentName who) {
        if (!mHasFeature) {
            return false;
        }
        Objects.requireNonNull(who, "ComponentName is null");

        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || isProfileOwner(caller));

        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
            return admin.disableBluetoothContactSharing;
        }
    }

    @Override
    public boolean getBluetoothContactSharingDisabledForUser(int userId) {
        // TODO: Should there be a check to make sure this relationship is
        // within a profile group?
        // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
            return (admin != null) ? admin.disableBluetoothContactSharing : false;
        }
    }

    @Override
    public void setSecondaryLockscreenEnabled(ComponentName who, boolean enabled) {
        Objects.requireNonNull(who, "ComponentName is null");

        // Check can set secondary lockscreen enabled
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || isProfileOwner(caller));
        Preconditions.checkCallAuthorization(!isManagedProfile(caller.getUserId()),
                "User %d is not allowed to call setSecondaryLockscreenEnabled",
                        caller.getUserId());

        synchronized (getLockObject()) {
            // Allow testOnly admins to bypass supervision config requirement.
            Preconditions.checkCallAuthorization(isAdminTestOnlyLocked(who, caller.getUserId())
                    || isSupervisionComponentLocked(caller.getComponentName()), "Admin %s is not "
                    + "the default supervision component", caller.getComponentName());
            DevicePolicyData policy = getUserData(caller.getUserId());
            policy.mSecondaryLockscreenEnabled = enabled;
            saveSettingsLocked(caller.getUserId());
        }
    }

    @Override
    public boolean isSecondaryLockscreenEnabled(@NonNull UserHandle userHandle) {
        synchronized (getLockObject()) {
            return getUserData(userHandle.getIdentifier()).mSecondaryLockscreenEnabled;
        }
    }

    private boolean isManagedProfileOwner(CallerIdentity caller) {
        return isProfileOwner(caller) && isManagedProfile(caller.getUserId());
    }

    @Override
    public void setPreferentialNetworkServiceConfigs(
            List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs) {
        if (!mHasFeature) {
            return;
        }
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization((isProfileOwner(caller)
                        && isManagedProfile(caller.getUserId()))
                        || isDefaultDeviceOwner(caller),
                "Caller is not managed profile owner or device owner;"
                        + " only managed profile owner or device owner may control the preferential"
                        + " network service");

        try {
            updateNetworkPreferenceForUser(caller.getUserId(), preferentialNetworkServiceConfigs);
            synchronized (getLockObject()) {
                final ActiveAdmin requiredAdmin = getDeviceOrProfileOwnerAdminLocked(
                        caller.getUserId());
                if (!requiredAdmin.mPreferentialNetworkServiceConfigs.equals(
                        preferentialNetworkServiceConfigs)) {
                    requiredAdmin.mPreferentialNetworkServiceConfigs =
                            new ArrayList<>(preferentialNetworkServiceConfigs);
                    saveSettingsLocked(caller.getUserId());
                }
            }
        } catch (Exception e) {
            Slogf.e(LOG_TAG, "Failed to set preferential network service configs");
            throw e;
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_PREFERENTIAL_NETWORK_SERVICE_ENABLED)
                .setBoolean(preferentialNetworkServiceConfigs
                        .stream().anyMatch(c -> c.isEnabled()))
                .write();
    }

    @Override
    public List<PreferentialNetworkServiceConfig> getPreferentialNetworkServiceConfigs() {
        if (!mHasFeature) {
            return List.of(PreferentialNetworkServiceConfig.DEFAULT);
        }

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization((isProfileOwner(caller)
                        && isManagedProfile(caller.getUserId()))
                        || isDefaultDeviceOwner(caller),
                "Caller is not managed profile owner or device owner;"
                        + " only managed profile owner or device owner may retrieve the "
                        + "preferential network service configurations");
        synchronized (getLockObject()) {
            final ActiveAdmin requiredAdmin = getDeviceOrProfileOwnerAdminLocked(
                    caller.getUserId());
            return requiredAdmin.mPreferentialNetworkServiceConfigs;
        }
    }

    @Override
    public void setLockTaskPackages(ComponentName who, String callerPackageName, String[] packages)
            throws SecurityException {
        Objects.requireNonNull(packages, "packages is null");
        for (String pkg : packages) {
            enforceMaxPackageNameLength(pkg);
        }

        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_LOCK_TASK_PACKAGES);

        EnforcingAdmin enforcingAdmin;
        synchronized (getLockObject()) {
            enforcingAdmin = enforceCanCallLockTaskLocked(who, caller.getPackageName());
        }
        LockTaskPolicy currentPolicy = mDevicePolicyEngine.getLocalPolicySetByAdmin(
                PolicyDefinition.LOCK_TASK,
                enforcingAdmin,
                caller.getUserId());
        LockTaskPolicy policy;
        if (currentPolicy == null) {
            policy = new LockTaskPolicy(Set.of(packages));
        } else {
            policy = new LockTaskPolicy(currentPolicy);
            policy.setPackages(Set.of(packages));
        }
        if (policy.getPackages().isEmpty()) {
            mDevicePolicyEngine.removeLocalPolicy(
                    PolicyDefinition.LOCK_TASK,
                    enforcingAdmin,
                    caller.getUserId());
        } else {
            mDevicePolicyEngine.setLocalPolicy(
                    PolicyDefinition.LOCK_TASK,
                    enforcingAdmin,
                    policy,
                    caller.getUserId());
        }
    }

    private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
        DevicePolicyData policy = getUserData(userHandle);
        policy.mLockTaskPackages = packages;

        // Store the settings persistently.
        saveSettingsLocked(userHandle);
        updateLockTaskPackagesLocked(mContext, packages, userHandle);
    }

    @Override
    public String[] getLockTaskPackages(ComponentName who, String callerPackageName) {
        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
        final int userHandle = caller.getUserId();

        synchronized (getLockObject()) {
            enforceCanQueryLockTaskLocked(who, caller.getPackageName());
        }
        LockTaskPolicy policy = mDevicePolicyEngine.getResolvedPolicy(
                PolicyDefinition.LOCK_TASK, userHandle);
        if (policy == null) {
            return new String[0];
        } else {
            return policy.getPackages().toArray(new String[policy.getPackages().size()]);
        }
    }

    @Override
    public boolean isLockTaskPermitted(String pkg) {
        // Check policy-exempt apps first, as it doesn't require the lock
        if (listPolicyExemptAppsUnchecked(mContext).contains(pkg)) {
            if (VERBOSE_LOG) {
                Slogf.v(LOG_TAG, "isLockTaskPermitted(%s): returning true for policy-exempt app",
                            pkg);
            }
            return true;
        }

        final int userId = mInjector.userHandleGetCallingUserId();
        LockTaskPolicy policy = mDevicePolicyEngine.getResolvedPolicy(
                PolicyDefinition.LOCK_TASK, userId);
        if (policy == null) {
            return false;
        }
        return policy.getPackages().contains(pkg);
    }

    @Override
    public void setLockTaskFeatures(ComponentName who, String callerPackageName, int flags) {
        // Throw if Overview is used without Home.
        boolean hasHome = (flags & LOCK_TASK_FEATURE_HOME) != 0;
        boolean hasOverview = (flags & LOCK_TASK_FEATURE_OVERVIEW) != 0;
        Preconditions.checkArgument(hasHome || !hasOverview,
                "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME");
        boolean hasNotification = (flags & LOCK_TASK_FEATURE_NOTIFICATIONS) != 0;
        Preconditions.checkArgument(hasHome || !hasNotification,
            "Cannot use LOCK_TASK_FEATURE_NOTIFICATIONS without LOCK_TASK_FEATURE_HOME");

        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
        final int userHandle = caller.getUserId();
        synchronized (getLockObject()) {
            checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_LOCK_TASK_FEATURES);
        }

        EnforcingAdmin enforcingAdmin;
        synchronized (getLockObject()) {
            enforcingAdmin = enforceCanCallLockTaskLocked(who, caller.getPackageName());
            enforceCanSetLockTaskFeaturesOnFinancedDevice(caller, flags);
        }
        LockTaskPolicy currentPolicy = mDevicePolicyEngine.getLocalPolicySetByAdmin(
                PolicyDefinition.LOCK_TASK,
                enforcingAdmin,
                caller.getUserId());
        LockTaskPolicy policy;
        if (currentPolicy == null) {
            policy = new LockTaskPolicy(flags);
        } else {
            policy = new LockTaskPolicy(currentPolicy);
            policy.setFlags(flags);
        }
        if (policy.getPackages().isEmpty()
                && policy.getFlags() == DevicePolicyManager.LOCK_TASK_FEATURE_NONE) {
            mDevicePolicyEngine.removeLocalPolicy(
                    PolicyDefinition.LOCK_TASK,
                    enforcingAdmin,
                    caller.getUserId());
        } else {
            mDevicePolicyEngine.setLocalPolicy(
                    PolicyDefinition.LOCK_TASK,
                    enforcingAdmin,
                    policy,
                    caller.getUserId());
        }
    }

    private void setLockTaskFeaturesLocked(int userHandle, int flags) {
        DevicePolicyData policy = getUserData(userHandle);
        policy.mLockTaskFeatures = flags;
        saveSettingsLocked(userHandle);
        updateLockTaskFeaturesLocked(flags, userHandle);
    }

    @Override
    public int getLockTaskFeatures(ComponentName who, String callerPackageName) {
        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
        final int userHandle = caller.getUserId();

        synchronized (getLockObject()) {
            enforceCanQueryLockTaskLocked(who, caller.getPackageName());
        }
        LockTaskPolicy policy = mDevicePolicyEngine.getResolvedPolicy(
                PolicyDefinition.LOCK_TASK, userHandle);
        if (policy == null) {
            // We default on the power button menu, in order to be consistent with pre-P
            // behaviour.
            return DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS;
        }
        return policy.getFlags();
    }

    private void maybeClearLockTaskPolicyLocked() {
        mInjector.binderWithCleanCallingIdentity(() -> {
            final List<UserInfo> userInfos = mUserManager.getAliveUsers();
            for (int i = userInfos.size() - 1; i >= 0; i--) {
                int userId = userInfos.get(i).id;
                if (canDPCManagedUserUseLockTaskLocked(userId)) {
                    continue;
                }
                Map<EnforcingAdmin, PolicyValue<LockTaskPolicy>> policies =
                        mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
                                PolicyDefinition.LOCK_TASK, userId);
                Set<EnforcingAdmin> admins = new HashSet<>(policies.keySet());
                for (EnforcingAdmin admin : admins) {
                    if (admin.hasAuthority(EnforcingAdmin.DPC_AUTHORITY)) {
                        mDevicePolicyEngine.removeLocalPolicy(
                                PolicyDefinition.LOCK_TASK, admin, userId);
                    }
                }
            }
        });
    }

    private void enforceCanSetLockTaskFeaturesOnFinancedDevice(CallerIdentity caller, int flags) {
        int allowedFlags = LOCK_TASK_FEATURE_SYSTEM_INFO | LOCK_TASK_FEATURE_KEYGUARD
                | LOCK_TASK_FEATURE_HOME | LOCK_TASK_FEATURE_GLOBAL_ACTIONS
                | LOCK_TASK_FEATURE_NOTIFICATIONS | LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK;

        if (!isFinancedDeviceOwner(caller)) {
            return;
        }

        if ((flags & ~(allowedFlags)) != 0) {
            throw new SecurityException(
                    "Permitted lock task features when managing a financed device: "
                            + "LOCK_TASK_FEATURE_SYSTEM_INFO, LOCK_TASK_FEATURE_KEYGUARD, "
                            + "LOCK_TASK_FEATURE_HOME, LOCK_TASK_FEATURE_GLOBAL_ACTIONS, "
                            + "LOCK_TASK_FEATURE_NOTIFICATIONS"
                            + " or LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK");
        }
    }

    @Override
    public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
        Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
                String.format(NOT_SYSTEM_CALLER_MSG, "call notifyLockTaskModeChanged"));
        synchronized (getLockObject()) {
            final DevicePolicyData policy = getUserData(userHandle);

            if (policy.mStatusBarDisabled) {
                // Status bar is managed by LockTaskController during LockTask, so we cancel this
                // policy when LockTask starts, and reapply it when LockTask ends
                setStatusBarDisabledInternal(!isEnabled, userHandle);
            }

            Bundle adminExtras = new Bundle();
            adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
            for (ActiveAdmin admin : policy.mAdminList) {
                final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
                final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
                // TODO(b/281738975): Should we be logging this for all admins?
                if (ownsDevice || ownsProfile) {
                    if (isEnabled) {
                        sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
                                adminExtras, null);
                    } else {
                        sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
                    }
                    DevicePolicyEventLogger
                            .createEvent(DevicePolicyEnums.SET_LOCKTASK_MODE_ENABLED)
                            .setAdmin(admin.info == null ? null : admin.info.getPackageName())
                            .setBoolean(isEnabled)
                            .setStrings(pkg)
                            .write();
                }
            }
        }
        // TODO(b/281738975): Should we be logging this for all admins?
        for(EnforcingAdmin admin : mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
                PolicyDefinition.LOCK_TASK, userHandle).keySet()) {
            if (admin.hasAuthority(EnforcingAdmin.DPC_AUTHORITY)) {
                // already handled above
                continue;
            }
            DevicePolicyEventLogger
                    .createEvent(DevicePolicyEnums.SET_LOCKTASK_MODE_ENABLED)
                    .setAdmin(admin.getPackageName())
                    .setBoolean(isEnabled)
                    .setStrings(pkg)
                    .write();
        }
    }

    @Override
    public void setGlobalSetting(ComponentName who, String setting, String value) {
        final CallerIdentity caller = getCallerIdentity(who);
        if (Global.ALLOW_WORK_PROFILE_TELEPHONY_FOR_NON_DPM_ROLE_HOLDERS.equals(setting)) {
            Preconditions.checkCallAuthorization(isCallerDevicePolicyManagementRoleHolder(caller));
            mInjector.binderWithCleanCallingIdentity(
                    () -> mInjector.settingsGlobalPutString(setting, value));
            return;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));

        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_GLOBAL_SETTING)
                .setAdmin(who)
                .setStrings(setting, value)
                .write();

        synchronized (getLockObject()) {
            // Some settings are no supported any more. However we do not want to throw a
            // SecurityException to avoid breaking apps.
            if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
                Slogf.i(LOG_TAG, "Global setting no longer supported: %s", setting);
                return;
            }

            if (!GLOBAL_SETTINGS_ALLOWLIST.contains(setting)
                    && !UserManager.isDeviceInDemoMode(mContext)) {
                throw new SecurityException(String.format(
                        "Permission denial: device owners cannot update %1$s", setting));
            }

            if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
                // ignore if it contradicts an existing policy
                long timeMs = getMaximumTimeToLock(
                        who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
                if (timeMs > 0 && timeMs < Long.MAX_VALUE) {
                    return;
                }
            }

            mInjector.binderWithCleanCallingIdentity(
                    () -> mInjector.settingsGlobalPutString(setting, value));
        }
    }

    @Override
    public void setSystemSetting(ComponentName who, String setting, String value) {
        Objects.requireNonNull(who, "ComponentName is null");
        Preconditions.checkStringNotEmpty(setting, "String setting is null or empty");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isProfileOwner(caller) || isDefaultDeviceOwner(caller));
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_SYSTEM_SETTING);

        synchronized (getLockObject()) {
            if (!SYSTEM_SETTINGS_ALLOWLIST.contains(setting)) {
                throw new SecurityException(String.format(
                        "Permission denial: device owners cannot update %1$s", setting));
            }

            mInjector.binderWithCleanCallingIdentity(() ->
                    mInjector.settingsSystemPutStringForUser(setting, value, caller.getUserId()));
        }
    }

    @Override
    public void setConfiguredNetworksLockdownState(
            ComponentName who, String callerPackageName, boolean lockdown) {
        if (!mHasFeature) {
            return;
        }
        CallerIdentity caller;

        if (isPermissionCheckFlagEnabled()) {
            caller = getCallerIdentity(who, callerPackageName);
            enforcePermission(MANAGE_DEVICE_POLICY_WIFI, caller.getPackageName(),
                    UserHandle.USER_ALL);
        } else {
            caller = getCallerIdentity(who);
            Preconditions.checkNotNull(who, "ComponentName is null");
            Preconditions.checkCallAuthorization(
                    isDefaultDeviceOwner(caller)
                            || isProfileOwnerOfOrganizationOwnedDevice(caller));
        }

        mInjector.binderWithCleanCallingIdentity(() ->
                mInjector.settingsGlobalPutInt(Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN,
                        lockdown ? 1 : 0));

        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.ALLOW_MODIFICATION_OF_ADMIN_CONFIGURED_NETWORKS)
                .setAdmin(caller.getPackageName())
                .setBoolean(lockdown)
                .write();
    }

    @Override
    public boolean hasLockdownAdminConfiguredNetworks(ComponentName who) {
        if (!mHasFeature) {
            return false;
        }
        CallerIdentity caller = getCallerIdentity(who);
        if (isPermissionCheckFlagEnabled()) {
            enforcePermission(MANAGE_DEVICE_POLICY_WIFI, who.getPackageName(),
                    UserHandle.USER_ALL);
        } else {
            Preconditions.checkNotNull(who, "ComponentName is null");

            Preconditions.checkCallAuthorization(
                    isDefaultDeviceOwner(caller)
                            || isProfileOwnerOfOrganizationOwnedDevice(caller));
        }

        return mInjector.binderWithCleanCallingIdentity(() ->
                mInjector.settingsGlobalGetInt(Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0) > 0);
    }

    @Override
    public void setLocationEnabled(ComponentName who, boolean locationEnabled) {
        Preconditions.checkNotNull(who, "ComponentName is null");

        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));

        UserHandle userHandle = caller.getUserHandle();
        if (mIsAutomotive && !locationEnabled) {
            Slogf.i(LOG_TAG, "setLocationEnabled(%s, %b): ignoring for user %s on automotive build",
                    who.flattenToShortString(), locationEnabled, userHandle);
            return;
        }

        mInjector.binderWithCleanCallingIdentity(() -> {
            boolean wasLocationEnabled = mInjector.getLocationManager().isLocationEnabledForUser(
                    userHandle);
            Slogf.v(LOG_TAG, "calling locationMgr.setLocationEnabledForUser(%b, %s) when it was %b",
                    locationEnabled, userHandle, wasLocationEnabled);
            mInjector.getLocationManager().setLocationEnabledForUser(locationEnabled, userHandle);

            // make a best effort to only show the notification if the admin is actually enabling
            // location. this is subject to race conditions with settings changes, but those are
            // unlikely to realistically interfere
            if (locationEnabled && !wasLocationEnabled) {
                showLocationSettingsEnabledNotification(userHandle);
            }
        });

        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_SECURE_SETTING)
                .setAdmin(who)
                .setStrings(Settings.Secure.LOCATION_MODE, Integer.toString(
                        locationEnabled ? Settings.Secure.LOCATION_MODE_ON
                                : Settings.Secure.LOCATION_MODE_OFF))
                .write();
    }

    private void showLocationSettingsEnabledNotification(UserHandle user) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                .addFlags(FLAG_ACTIVITY_NEW_TASK);
        // Fill the component explicitly to prevent the PendingIntent from being intercepted
        // and fired with crafted target. b/155183624
        ActivityInfo targetInfo = intent.resolveActivityInfo(
                mInjector.getPackageManager(user.getIdentifier()),
                PackageManager.MATCH_SYSTEM_ONLY);
        if (targetInfo != null) {
            intent.setComponent(targetInfo.getComponentName());
        } else {
            Slogf.wtf(LOG_TAG, "Failed to resolve intent for location settings");
        }

        // Simple notification clicks are immutable
        PendingIntent locationSettingsIntent = mInjector.pendingIntentGetActivityAsUser(mContext, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE, null,
                user);
        Notification notification = new Notification.Builder(mContext,
                SystemNotificationChannels.DEVICE_ADMIN)
                .setSmallIcon(R.drawable.ic_info_outline)
                .setContentTitle(getLocationChangedTitle())
                .setContentText(getLocationChangedText())
                .setColor(mContext.getColor(R.color.system_notification_accent_color))
                .setShowWhen(true)
                .setContentIntent(locationSettingsIntent)
                .setAutoCancel(true)
                .build();
        mHandler.post(() -> mInjector.getNotificationManager().notify(
                SystemMessage.NOTE_LOCATION_CHANGED, notification));
    }

    private String getLocationChangedTitle() {
        return getUpdatableString(
                LOCATION_CHANGED_TITLE, R.string.location_changed_notification_title);
    }

    private String getLocationChangedText() {
        return getUpdatableString(
                LOCATION_CHANGED_MESSAGE, R.string.location_changed_notification_text);
    }

    @Override
    public boolean setTime(@Nullable ComponentName who, String callerPackageName, long millis) {
        CallerIdentity caller;
        if (isPermissionCheckFlagEnabled()) {
            caller = getCallerIdentity(who, callerPackageName);
            // This is a global action.
            enforcePermission(SET_TIME, caller.getPackageName(), UserHandle.USER_ALL);
        } else {
            caller = getCallerIdentity(who);
            Objects.requireNonNull(who, "ComponentName is null");
            Preconditions.checkCallAuthorization(
                    isDefaultDeviceOwner(caller)
                            || isProfileOwnerOfOrganizationOwnedDevice(caller));
        }

        // Don't allow set time when auto time is on.
        if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) == 1) {
            return false;
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_TIME)
                .setAdmin(caller.getPackageName())
                .write();
        mInjector.binderWithCleanCallingIdentity(() -> mInjector.getAlarmManager().setTime(millis));
        return true;
    }

    @Override
    public boolean setTimeZone(@Nullable ComponentName who, String callerPackageName,
            String timeZone) {
        CallerIdentity caller;
        if (isPermissionCheckFlagEnabled()) {
            caller = getCallerIdentity(who, callerPackageName);
            // This is a global action.
            enforcePermission(SET_TIME_ZONE, caller.getPackageName(), UserHandle.USER_ALL);
        } else {
            caller = getCallerIdentity(who);
            Objects.requireNonNull(who, "ComponentName is null");
            Preconditions.checkCallAuthorization(
                    isDefaultDeviceOwner(caller)
                            || isProfileOwnerOfOrganizationOwnedDevice(caller));
        }

        // Don't allow set timezone when auto timezone is on.
        if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) == 1) {
            return false;
        }
        String logInfo = "DevicePolicyManager.setTimeZone()";
        mInjector.binderWithCleanCallingIdentity(() ->
                mInjector.getAlarmManagerInternal()
                        .setTimeZone(timeZone, TIME_ZONE_CONFIDENCE_HIGH, logInfo));

        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_TIME_ZONE)
                .setAdmin(caller.getPackageName())
                .write();
        return true;
    }

    @Override
    public void setSecureSetting(ComponentName who, String setting, String value) {
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isProfileOwner(caller) || isDefaultDeviceOwner(caller));

        int callingUserId = caller.getUserId();
        synchronized (getLockObject()) {
            if (isDeviceOwner(who, callingUserId)) {
                if (!SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST.contains(setting)
                        && !isCurrentUserDemo()) {
                    throw new SecurityException(String.format(
                            "Permission denial: Device owners cannot update %1$s", setting));
                }
            } else if (!SECURE_SETTINGS_ALLOWLIST.contains(setting) && !isCurrentUserDemo()) {
                throw new SecurityException(String.format(
                        "Permission denial: Profile owners cannot update %1$s", setting));
            }
            if (setting.equals(Settings.Secure.LOCATION_MODE)
                    && isSetSecureSettingLocationModeCheckEnabled(who.getPackageName(),
                    callingUserId)) {
                throw new UnsupportedOperationException(Settings.Secure.LOCATION_MODE + " is "
                        + "deprecated. Please use setLocationEnabled() instead.");
            }
            if (setting.equals(Settings.Secure.INSTALL_NON_MARKET_APPS)) {
                if (getTargetSdk(who.getPackageName(), callingUserId) >= Build.VERSION_CODES.O) {
                    throw new UnsupportedOperationException(Settings.Secure.INSTALL_NON_MARKET_APPS
                            + " is deprecated. Please use one of the user restrictions "
                            + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " or "
                            + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY + " instead.");
                }
                if (!mUserManager.isManagedProfile(callingUserId)) {
                    Slogf.e(LOG_TAG, "Ignoring setSecureSetting request for "
                            + setting + ". User restriction "
                            + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " or "
                            + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY
                            + " should be used instead.");
                } else {
                    try {
                        setUserRestriction(who, who.getPackageName(),
                                UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
                                (Integer.parseInt(value) == 0) ? true : false, /* parent */ false);
                        DevicePolicyEventLogger
                                .createEvent(DevicePolicyEnums.SET_SECURE_SETTING)
                                .setAdmin(who)
                                .setStrings(setting, value)
                                .write();
                    } catch (NumberFormatException exc) {
                        Slogf.e(LOG_TAG, "Invalid value: " + value + " for setting " + setting);
                    }
                }
                return;
            }
            mInjector.binderWithCleanCallingIdentity(() -> {
                if (Settings.Secure.DEFAULT_INPUT_METHOD.equals(setting)) {
                    final String currentValue = mInjector.settingsSecureGetStringForUser(
                            Settings.Secure.DEFAULT_INPUT_METHOD, callingUserId);
                    if (!TextUtils.equals(currentValue, value)) {
                        // Tell the content observer that the next change will be due to the owner
                        // changing the value. There is a small race condition here that we cannot
                        // avoid: Change notifications are sent asynchronously, so it is possible
                        // that there are prior notifications queued up before the one we are about
                        // to trigger. This is a corner case that will have no impact in practice.
                        mSetupContentObserver.addPendingChangeByOwnerLocked(callingUserId);
                    }
                    getUserData(callingUserId).mCurrentInputMethodSet = true;
                    saveSettingsLocked(callingUserId);
                }
                mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
                // Notify the user if it's the location mode setting that's been set, to any value
                // other than 'off'.
                if (setting.equals(Settings.Secure.LOCATION_MODE)
                        && (Integer.parseInt(value) != 0)) {
                    showLocationSettingsEnabledNotification(UserHandle.of(callingUserId));
                }
            });
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_SECURE_SETTING)
                .setAdmin(who)
                .setStrings(setting, value)
                .write();
    }

    private boolean isSetSecureSettingLocationModeCheckEnabled(String packageName, int userId) {
        return mInjector.isChangeEnabled(USE_SET_LOCATION_ENABLED, packageName, userId);
    }

    @Override
    public void setMasterVolumeMuted(ComponentName who, boolean on) {
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isProfileOwner(caller) || isDefaultDeviceOwner(caller));
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_MASTER_VOLUME_MUTED);

        synchronized (getLockObject()) {
            setUserRestriction(who, who.getPackageName(), UserManager.DISALLOW_UNMUTE_DEVICE, on,
                    /* parent */ false);
            DevicePolicyEventLogger
                    .createEvent(DevicePolicyEnums.SET_MASTER_VOLUME_MUTED)
                    .setAdmin(who)
                    .setBoolean(on)
                    .write();
        }
    }

    @Override
    public boolean isMasterVolumeMuted(ComponentName who) {
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isProfileOwner(caller) || isDefaultDeviceOwner(caller));

        synchronized (getLockObject()) {
            AudioManager audioManager =
                    (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            return audioManager.isMasterMute();
        }
    }

    @Override
    public void setUserIcon(ComponentName who, Bitmap icon) {
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isProfileOwner(caller) || isDefaultDeviceOwner(caller));

        synchronized (getLockObject()) {
            mInjector.binderWithCleanCallingIdentity(
                    () -> mUserManagerInternal.setUserIcon(caller.getUserId(), icon));
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_USER_ICON)
                .setAdmin(who)
                .write();
    }

    @Override
    public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isProfileOwner(caller) || isDefaultDeviceOwner(caller));

        final int userId = caller.getUserId();
        synchronized (getLockObject()) {
            Preconditions.checkCallAuthorization(isUserAffiliatedWithDeviceLocked(userId),
                    String.format(
                            "Admin %s is neither the device owner or affiliated user's profile "
                                    + "owner.", who));
        }
        if (isManagedProfile(userId)) {
            throw new SecurityException("Managed profile cannot disable keyguard");
        }
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_KEYGUARD_DISABLED);

        long ident = mInjector.binderClearCallingIdentity();
        try {
            // disallow disabling the keyguard if a password is currently set
            if (disabled && mLockPatternUtils.isSecure(userId)) {
                return false;
            }
            mLockPatternUtils.setLockScreenDisabled(disabled, userId);
            if (disabled) {
                mInjector
                        .getIWindowManager()
                        .dismissKeyguard(null /* callback */, null /* message */);
            }
            DevicePolicyEventLogger
                    .createEvent(DevicePolicyEnums.SET_KEYGUARD_DISABLED)
                    .setAdmin(who)
                    .setBoolean(disabled)
                    .write();
        } catch (RemoteException e) {
            // Same process, does not happen.
        } finally {
            mInjector.binderRestoreCallingIdentity(ident);
        }
        return true;
    }

    @Override
    public boolean setStatusBarDisabled(ComponentName who, String callerPackageName,
            boolean disabled) {
        CallerIdentity caller;
        if (isUnicornFlagEnabled()) {
            caller = getCallerIdentity(who, callerPackageName);
        } else {
            caller = getCallerIdentity(who);
        }
        if (isUnicornFlagEnabled()) {
            enforcePermission(MANAGE_DEVICE_POLICY_STATUS_BAR, caller.getPackageName(),
                    UserHandle.USER_ALL);
        } else {
            Objects.requireNonNull(who, "ComponentName is null");
            Preconditions.checkCallAuthorization(
                    isProfileOwner(caller) || isDefaultDeviceOwner(caller));
        }

        int userId = caller.getUserId();
        synchronized (getLockObject()) {
            if (!isUnicornFlagEnabled()) {
                Preconditions.checkCallAuthorization(isUserAffiliatedWithDeviceLocked(userId),
                        "Admin " + who + " is neither the device owner or affiliated "
                                + "user's profile owner.");
                if (isManagedProfile(userId)) {
                    throw new SecurityException("Managed profile cannot disable status bar");
                }
            }
            checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_STATUS_BAR_DISABLED);

            DevicePolicyData policy = getUserData(userId);
            if (policy.mStatusBarDisabled != disabled) {
                boolean isLockTaskMode = false;
                try {
                    isLockTaskMode = mInjector.getIActivityTaskManager().getLockTaskModeState()
                            != LOCK_TASK_MODE_NONE;
                } catch (RemoteException e) {
                    Slogf.e(LOG_TAG, "Failed to get LockTask mode");
                }
                if (!isLockTaskMode) {
                    if (!setStatusBarDisabledInternal(disabled, userId)) {
                        return false;
                    }
                }
                policy.mStatusBarDisabled = disabled;
                saveSettingsLocked(userId);
            }
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_STATUS_BAR_DISABLED)
                .setAdmin(caller.getPackageName())
                .setBoolean(disabled)
                .write();
        return true;
    }

    private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
        long ident = mInjector.binderClearCallingIdentity();
        try {
            IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
                    ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
            if (statusBarService != null) {
                int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
                int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
                statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
                statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
                return true;
            }
        } catch (RemoteException e) {
            Slogf.e(LOG_TAG, "Failed to disable the status bar", e);
        } finally {
            mInjector.binderRestoreCallingIdentity(ident);
        }
        return false;
    }

    @Override
    public boolean isStatusBarDisabled(String callerPackage) {
        final CallerIdentity caller = getCallerIdentity(callerPackage);
        if (isUnicornFlagEnabled()) {
            enforceCanQuery(
                    MANAGE_DEVICE_POLICY_STATUS_BAR, caller.getPackageName(), caller.getUserId());
        } else {
            Preconditions.checkCallAuthorization(
                    isProfileOwner(caller) || isDefaultDeviceOwner(caller));
        }

        int userId = caller.getUserId();
        synchronized (getLockObject()) {
            if (!isUnicornFlagEnabled()) {
                Preconditions.checkCallAuthorization(isUserAffiliatedWithDeviceLocked(userId),
                        "Admin " + callerPackage
                                + " is neither the device owner or affiliated user's profile owner.");
                if (isManagedProfile(userId)) {
                    throw new SecurityException("Managed profile cannot disable status bar");
                }
            }
            DevicePolicyData policy = getUserData(userId);
            return policy.mStatusBarDisabled;
        }
    }

    private Set<String> getPackagesSuspendedByAdmin(@UserIdInt int userId) {
        synchronized (getLockObject()) {
            ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userId);
            if (admin == null || admin.suspendedPackages == null) {
                return Collections.emptySet();
            } else {
                return new ArraySet<>(admin.suspendedPackages);
            }
        }
    }

    /**
     * We need to update the internal state of whether a user has completed setup or a
     * device has paired once. After that, we ignore any changes that reset the
     * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change
     * as we don't trust any apps that might try to reset them.
     * <p>
     * Unfortunately, we don't know which user's setup state was changed, so we write all of
     * them.
     */
    void updateUserSetupCompleteAndPaired() {
        List<UserInfo> users = mUserManager.getAliveUsers();
        final int N = users.size();
        for (int i = 0; i < N; i++) {
            int userHandle = users.get(i).id;
            if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
                    userHandle) != 0) {
                DevicePolicyData policy = getUserData(userHandle);
                if (!policy.mUserSetupComplete) {
                    policy.mUserSetupComplete = true;
                    if (userHandle == UserHandle.USER_SYSTEM) {
                        mStateCache.setDeviceProvisioned(true);
                    }
                    synchronized (getLockObject()) {
                        saveSettingsLocked(userHandle);
                    }
                }
            }
            if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0,
                    userHandle) != 0) {
                DevicePolicyData policy = getUserData(userHandle);
                if (!policy.mPaired) {
                    policy.mPaired = true;
                    synchronized (getLockObject()) {
                        saveSettingsLocked(userHandle);
                    }
                }
            }
        }
    }

    private class SetupContentObserver extends ContentObserver {
        private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
                Settings.Secure.USER_SETUP_COMPLETE);
        private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
                Settings.Global.DEVICE_PROVISIONED);
        private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED);
        private final Uri mDefaultImeChanged = Settings.Secure.getUriFor(
                Settings.Secure.DEFAULT_INPUT_METHOD);

        @GuardedBy("getLockObject()")
        private Set<Integer> mUserIdsWithPendingChangesByOwner = new ArraySet<>();

        public SetupContentObserver(Handler handler) {
            super(handler);
        }

        void register() {
            mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
            mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
            if (mIsWatch) {
                mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL);
            }
            mInjector.registerContentObserver(mDefaultImeChanged, false, this, UserHandle.USER_ALL);
        }

        @GuardedBy("getLockObject()")
        private void addPendingChangeByOwnerLocked(int userId) {
            mUserIdsWithPendingChangesByOwner.add(userId);
        }

        @Override
        public void onChange(boolean selfChange, Uri uri, int userId) {
            if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) {
                updateUserSetupCompleteAndPaired();
            } else if (mDeviceProvisioned.equals(uri)) {
                synchronized (getLockObject()) {
                    // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
                    // is delayed until device is marked as provisioned.
                    setDeviceOwnershipSystemPropertyLocked();
                }
            } else if (mDefaultImeChanged.equals(uri)) {
                synchronized (getLockObject()) {
                    if (mUserIdsWithPendingChangesByOwner.contains(userId)) {
                        // This change notification was triggered by the owner changing the current
                        // IME. Ignore it.
                        mUserIdsWithPendingChangesByOwner.remove(userId);
                    } else {
                        // This change notification was triggered by the user manually changing the
                        // current IME.
                        getUserData(userId).mCurrentInputMethodSet = false;
                        saveSettingsLocked(userId);
                    }
                }
            }
        }
    }

    private class DevicePolicyConstantsObserver extends ContentObserver {
        final Uri mConstantsUri =
                Settings.Global.getUriFor(Settings.Global.DEVICE_POLICY_CONSTANTS);

        DevicePolicyConstantsObserver(Handler handler) {
            super(handler);
        }

        void register() {
            mInjector.registerContentObserver(
                    mConstantsUri, /* notifyForDescendents= */ false, this, UserHandle.USER_ALL);
        }

        @Override
        public void onChange(boolean selfChange, Uri uri, int userId) {
            mConstants = loadConstants();
            invalidateBinderCaches();

            mInjector.binderWithCleanCallingIdentity(() -> {
                final Intent intent = new Intent(
                        DevicePolicyManager.ACTION_DEVICE_POLICY_CONSTANTS_CHANGED);
                intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
                final List<UserInfo> users = mUserManager.getAliveUsers();
                for (int i = 0; i < users.size(); i++) {
                    mContext.sendBroadcastAsUser(intent, UserHandle.of(users.get(i).id));
                }
            });
        }
    }

    @VisibleForTesting
    final class LocalService extends DevicePolicyManagerInternal
            implements DevicePolicyManagerLiteInternal {
        private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;

        @Override
        public List<String> getCrossProfileWidgetProviders(int profileId) {
            synchronized (getLockObject()) {
                if (mOwners == null) {
                    return Collections.emptyList();
                }
                ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
                if (ownerComponent == null) {
                    return Collections.emptyList();
                }

                DevicePolicyData policy = getUserDataUnchecked(profileId);
                ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);

                if (admin == null || admin.crossProfileWidgetProviders == null
                        || admin.crossProfileWidgetProviders.isEmpty()) {
                    return Collections.emptyList();
                }

                return admin.crossProfileWidgetProviders;
            }
        }

        @Override
        public void addOnCrossProfileWidgetProvidersChangeListener(
                OnCrossProfileWidgetProvidersChangeListener listener) {
            synchronized (getLockObject()) {
                if (mWidgetProviderListeners == null) {
                    mWidgetProviderListeners = new ArrayList<>();
                }
                if (!mWidgetProviderListeners.contains(listener)) {
                    mWidgetProviderListeners.add(listener);
                }
            }
        }

        @Override
        public @Nullable ComponentName getProfileOwnerOrDeviceOwnerSupervisionComponent(
                @NonNull UserHandle userHandle) {
            return DevicePolicyManagerService.this.getProfileOwnerOrDeviceOwnerSupervisionComponent(
                    userHandle);
        }

        @Override
        public boolean isActiveDeviceOwner(int uid) {
            return isDefaultDeviceOwner(new CallerIdentity(uid, null, null));
        }

        @Override
        public boolean isActiveProfileOwner(int uid) {
            return isProfileOwner(new CallerIdentity(uid, null, null));
        }

        @Override
        public boolean isActiveSupervisionApp(int uid) {
            if (!isProfileOwner(new CallerIdentity(uid, null, null))) {
                return false;
            }
            synchronized (getLockObject()) {
                final ActiveAdmin admin = getProfileOwnerAdminLocked(UserHandle.getUserId(uid));
                if (admin == null) {
                    return false;
                }

                return isSupervisionComponentLocked(admin.info.getComponent());
            }
        }

        private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
            final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
            synchronized (getLockObject()) {
                listeners = new ArrayList<>(mWidgetProviderListeners);
            }
            final int listenerCount = listeners.size();
            for (int i = 0; i < listenerCount; i++) {
                OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
                listener.onCrossProfileWidgetProvidersChanged(userId, packages);
            }
        }

        @Override
        public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) {
            // This method is called from AM with its lock held, so don't take the DPMS lock.
            // b/29242568

            if (getEnforcingAdminAndUserDetailsInternal(userId, null) != null
                    || useDefaultIfNoAdmin) {
                return DevicePolicyManagerService.this.createShowAdminSupportIntent(userId);
            }
            return null;
        }

        @Override
        public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) {
            Intent intent = null;
            if (getEnforcingAdminAndUserDetailsInternal(userId, userRestriction) != null) {
                intent = DevicePolicyManagerService.this.createShowAdminSupportIntent(userId);
                intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, userRestriction);
            }
            return intent;
        }

        @Override
        public boolean isUserAffiliatedWithDevice(int userId) {
            return DevicePolicyManagerService.this.isUserAffiliatedWithDeviceLocked(userId);
        }

        @Override
        public boolean canSilentlyInstallPackage(String callerPackage, int callerUid) {
            if (callerPackage == null) {
                return false;
            }

            CallerIdentity caller = new CallerIdentity(callerUid, null, null);
            if (isUserAffiliatedWithDevice(UserHandle.getUserId(callerUid))
                    && (isActiveProfileOwner(callerUid)
                    || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller))) {
                // device owner or a profile owner affiliated with the device owner
                return true;
            }
            return false;
        }

        @Override
        public void reportSeparateProfileChallengeChanged(@UserIdInt int userId) {
            mInjector.binderWithCleanCallingIdentity(() -> {
                synchronized (getLockObject()) {
                    updateMaximumTimeToLockLocked(userId);
                    updatePasswordQualityCacheForUserGroup(userId);
                }
            });
            DevicePolicyEventLogger
                    .createEvent(DevicePolicyEnums.SEPARATE_PROFILE_CHALLENGE_CHANGED)
                    .setBoolean(isSeparateProfileChallengeEnabled(userId))
                    .write();
            invalidateBinderCaches();
        }

        @Override
        public CharSequence getPrintingDisabledReasonForUser(@UserIdInt int userId) {
            synchronized (getLockObject()) {
                if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_PRINTING,
                        UserHandle.of(userId))) {
                    Slogf.e(LOG_TAG, "printing is enabled for user %d", userId);
                    return null;
                }
                String ownerPackage = mOwners.getProfileOwnerPackage(userId);
                if (ownerPackage == null) {
                    ownerPackage = mOwners.getDeviceOwnerPackageName();
                }
                final String packageName = ownerPackage;
                PackageManager pm = mInjector.getPackageManager();
                PackageInfo packageInfo = mInjector.binderWithCleanCallingIdentity(() -> {
                    try {
                        return pm.getPackageInfo(packageName, 0);
                    } catch (NameNotFoundException e) {
                        Slogf.e(LOG_TAG, "getPackageInfo error", e);
                        return null;
                    }
                });
                if (packageInfo == null) {
                    Slogf.e(LOG_TAG, "packageInfo is inexplicably null");
                    return null;
                }
                ApplicationInfo appInfo = packageInfo.applicationInfo;
                if (appInfo == null) {
                    Slogf.e(LOG_TAG, "appInfo is inexplicably null");
                    return null;
                }
                CharSequence appLabel = pm.getApplicationLabel(appInfo);
                if (appLabel == null) {
                    Slogf.e(LOG_TAG, "appLabel is inexplicably null");
                    return null;
                }
                return getUpdatableString(
                        PRINTING_DISABLED_NAMED_ADMIN,
                        R.string.printing_disabled_by,
                        appLabel);
            }
        }

        @Override
        protected DevicePolicyCache getDevicePolicyCache() {
            return mPolicyCache;
        }

        @Override
        protected DeviceStateCache getDeviceStateCache() {
            return mStateCache;
        }

        @Override
        public List<String> getAllCrossProfilePackages(int userId) {
            return DevicePolicyManagerService.this.getAllCrossProfilePackages(userId);
        }

        @Override
        public List<String> getDefaultCrossProfilePackages() {
            return DevicePolicyManagerService.this.getDefaultCrossProfilePackages();
        }

        @Override
        public void broadcastIntentToManifestReceivers(
                Intent intent, UserHandle parentHandle, boolean requiresPermission) {
            Objects.requireNonNull(intent);
            Objects.requireNonNull(parentHandle);
            Slogf.i(LOG_TAG, "Sending %s broadcast to manifest receivers.", intent.getAction());
            broadcastIntentToCrossProfileManifestReceivers(
                    intent, parentHandle, requiresPermission);
            broadcastExplicitIntentToRoleHolder(
                    intent, RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT, parentHandle);
        }

        @Override
        public void enforcePermission(String callerPackage, String permission, int targetUserId) {
            DevicePolicyManagerService.this.enforcePermission(permission, callerPackage,
                    targetUserId);
        }

        @Override
        public boolean hasPermission(String callerPackage, String permission, int targetUserId) {
            return DevicePolicyManagerService.this.hasPermission(permission, callerPackage,
                    targetUserId);
        }

        private void broadcastIntentToCrossProfileManifestReceivers(
                Intent intent, UserHandle userHandle, boolean requiresPermission) {
            final int userId = userHandle.getIdentifier();
            try {
                final List<ResolveInfo> receivers = mIPackageManager.queryIntentReceivers(
                        intent, /* resolvedType= */ null,
                        STOCK_PM_FLAGS, userId).getList();
                for (ResolveInfo receiver : receivers) {
                    final String packageName = receiver.getComponentInfo().packageName;
                    if (checkCrossProfilePackagePermissions(packageName, userId,
                            requiresPermission)
                            || checkModifyQuietModePermission(packageName, userId)) {
                        Slogf.i(LOG_TAG, "Sending %s broadcast to %s.", intent.getAction(),
                                packageName);
                        final Intent packageIntent = new Intent(intent)
                                .setComponent(receiver.getComponentInfo().getComponentName())
                                .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
                        mContext.sendBroadcastAsUser(packageIntent, userHandle);
                    }
                }
            } catch (RemoteException ex) {
                Slogf.w(LOG_TAG, "Cannot get list of broadcast receivers for %s because: %s.",
                        intent.getAction(), ex);
            }
        }

        /**
         * Checks whether the package {@code packageName} has the {@code MODIFY_QUIET_MODE}
         * permission granted for the user {@code userId}.
         */
        private boolean checkModifyQuietModePermission(String packageName, @UserIdInt int userId) {
            try {
                final int uid = Objects.requireNonNull(
                        mInjector.getPackageManager().getApplicationInfoAsUser(
                                Objects.requireNonNull(packageName), /* flags= */ 0, userId)).uid;
                return PackageManager.PERMISSION_GRANTED
                        == ActivityManager.checkComponentPermission(
                        android.Manifest.permission.MODIFY_QUIET_MODE, uid, /* owningUid= */
                        -1, /* exported= */ true);
            } catch (NameNotFoundException ex) {
                Slogf.w(LOG_TAG, "Cannot find the package %s to check for permissions.",
                        packageName);
                return false;
            }
        }

        /**
         * Checks whether the package {@code packageName} has the required permissions to receive
         * cross-profile broadcasts on behalf of the user {@code userId}.
         */
        private boolean checkCrossProfilePackagePermissions(String packageName,
                @UserIdInt int userId, boolean requiresPermission) {
            final PackageManagerInternal pmInternal = LocalServices.getService(
                    PackageManagerInternal.class);
            final AndroidPackage androidPackage = pmInternal.getPackage(packageName);
            if (androidPackage == null || !androidPackage.isCrossProfile()) {
                return false;
            }
            if (!requiresPermission) {
                return true;
            }
            if (!isPackageEnabled(packageName, userId)) {
                return false;
            }
            try {
                final CrossProfileAppsInternal crossProfileAppsService = LocalServices.getService(
                        CrossProfileAppsInternal.class);
                return crossProfileAppsService.verifyPackageHasInteractAcrossProfilePermission(
                        packageName, userId);
            } catch (NameNotFoundException ex) {
                Slogf.w(LOG_TAG, "Cannot find the package %s to check for permissions.",
                        packageName);
                return false;
            }
        }

        private boolean isPackageEnabled(String packageName, @UserIdInt int userId) {
            final int callingUid = Binder.getCallingUid();
            final long ident = Binder.clearCallingIdentity();
            try {
                final PackageInfo info = mInjector.getPackageManagerInternal()
                        .getPackageInfo(
                                packageName,
                                MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
                                callingUid,
                                userId);
                return info != null && info.applicationInfo.enabled;
            } finally {
                Binder.restoreCallingIdentity(ident);
            }
        }

        @Override
        public ComponentName getProfileOwnerAsUser(@UserIdInt int userId) {
            return DevicePolicyManagerService.this.getProfileOwnerAsUser(userId);
        }

        @Override
        public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
            return DevicePolicyManagerService.this.getDeviceOwnerComponent(callingUserOnly);
        }

        @Override
        public int getDeviceOwnerUserId() {
            return DevicePolicyManagerService.this.getDeviceOwnerUserId();
        }

        @Override
        public boolean isDeviceOrProfileOwnerInCallingUser(String packageName) {
            return isDeviceOwnerInCallingUser(packageName)
                    || isProfileOwnerInCallingUser(packageName);
        }

        private boolean isDeviceOwnerInCallingUser(String packageName) {
            final ComponentName deviceOwnerInCallingUser =
                    DevicePolicyManagerService.this.getDeviceOwnerComponent(
                            /* callingUserOnly= */ true);
            return deviceOwnerInCallingUser != null
                    && packageName.equals(deviceOwnerInCallingUser.getPackageName());
        }

        private boolean isProfileOwnerInCallingUser(String packageName) {
            final ComponentName profileOwnerInCallingUser =
                    getProfileOwnerAsUser(UserHandle.getCallingUserId());
            return profileOwnerInCallingUser != null
                    && packageName.equals(profileOwnerInCallingUser.getPackageName());
        }

        @Override
        public boolean supportsResetOp(int op) {
            return op == AppOpsManager.OP_INTERACT_ACROSS_PROFILES
                    && LocalServices.getService(CrossProfileAppsInternal.class) != null;
        }

        @Override
        public void resetOp(int op, String packageName, @UserIdInt int userId) {
            if (op != AppOpsManager.OP_INTERACT_ACROSS_PROFILES) {
                throw new IllegalArgumentException("Unsupported op for DPM reset: " + op);
            }
            LocalServices.getService(CrossProfileAppsInternal.class)
                    .setInteractAcrossProfilesAppOp(
                            packageName, findInteractAcrossProfilesResetMode(packageName), userId);
        }

        @Override
        public void notifyUnsafeOperationStateChanged(DevicePolicySafetyChecker checker, int reason,
                boolean isSafe) {
            // TODO(b/178494483): use EventLog instead
            // TODO(b/178494483): log metrics?
            if (VERBOSE_LOG) {
                Slogf.v(LOG_TAG, "notifyUnsafeOperationStateChanged(): %s=%b",
                        DevicePolicyManager.operationSafetyReasonToString(reason), isSafe);
            }
            Preconditions.checkArgument(mSafetyChecker == checker,
                    "invalid checker: should be %s, was %s", mSafetyChecker, checker);

            Bundle extras = new Bundle();
            extras.putInt(DeviceAdminReceiver.EXTRA_OPERATION_SAFETY_REASON, reason);
            extras.putBoolean(DeviceAdminReceiver.EXTRA_OPERATION_SAFETY_STATE, isSafe);

            if (mOwners.hasDeviceOwner()) {
                if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Notifying DO");
                sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_OPERATION_SAFETY_STATE_CHANGED,
                        extras);
            }
            for (int profileOwnerId : mOwners.getProfileOwnerKeys()) {
                if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Notifying PO for user " + profileOwnerId);
                sendProfileOwnerCommand(DeviceAdminReceiver.ACTION_OPERATION_SAFETY_STATE_CHANGED,
                        extras, profileOwnerId);
            }
        }

        private @Mode int findInteractAcrossProfilesResetMode(String packageName) {
            return getDefaultCrossProfilePackages().contains(packageName)
                    ? AppOpsManager.MODE_ALLOWED
                    : AppOpsManager.opToDefaultMode(AppOpsManager.OP_INTERACT_ACROSS_PROFILES);
        }

        @Override
        public boolean isUserOrganizationManaged(@UserIdInt int userHandle) {
            return getDeviceStateCache().isUserOrganizationManaged(userHandle);
        }

        @Override
        public boolean isApplicationExemptionsFlagEnabled() {
            return DeviceConfig.getBoolean(
                    NAMESPACE_DEVICE_POLICY_MANAGER,
                    APPLICATION_EXEMPTIONS_FLAG,
                    DEFAULT_APPLICATION_EXEMPTIONS_FLAG);
        }

        @Override
        public List<Bundle> getApplicationRestrictionsPerAdminForUser(
                String packageName, @UserIdInt int userId) {
            if (UserHandle.getCallingUserId() != userId
                    || !UserHandle.isSameApp(
                    Binder.getCallingUid(), getUidForPackage(packageName, userId))) {
                final int uid = Binder.getCallingUid();
                if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
                    throw new SecurityException("Only system may: get application restrictions for "
                            + "other user/app " + packageName);
                }
            }
            LinkedHashMap<EnforcingAdmin, PolicyValue<Bundle>> policies =
                    mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
                            PolicyDefinition.APPLICATION_RESTRICTIONS(packageName),
                            userId);
            List<Bundle> restrictions = new ArrayList<>();
            for (EnforcingAdmin admin : policies.keySet()) {
                restrictions.add(policies.get(admin).getValue());
            }
            if (!restrictions.isEmpty()) {
                return restrictions;
            }

            return mInjector.binderWithCleanCallingIdentity(() -> {
                // Could be a device that has a DPC that hasn't migrated yet, so just return any
                // restrictions saved in userManager.
                Bundle bundle = mUserManager.getApplicationRestrictions(
                        packageName, UserHandle.of(userId));
                if (bundle == null || bundle.isEmpty()) {
                    return new ArrayList<>();
                }
                return List.of(bundle);
            });
        }

        public List<EnforcingUser> getUserRestrictionSources(String restriction,
                @UserIdInt int userId) {
            PolicyDefinition<Boolean> policy =
                    PolicyDefinition.getPolicyDefinitionForUserRestriction(restriction);

            Set<EnforcingAdmin> localAdmins =
                    mDevicePolicyEngine.getLocalPoliciesSetByAdmins(policy, userId).keySet();

            Set<EnforcingAdmin> globalAdmins =
                    mDevicePolicyEngine.getGlobalPoliciesSetByAdmins(policy).keySet();

            List<EnforcingUser> enforcingUsers = new ArrayList();
            enforcingUsers.addAll(getEnforcingUsers(localAdmins));
            enforcingUsers.addAll(getEnforcingUsers(globalAdmins));
            return enforcingUsers;
        }

        private List<EnforcingUser> getEnforcingUsers(Set<EnforcingAdmin> admins) {
            List<EnforcingUser> enforcingUsers = new ArrayList();
            ComponentName deviceOwner = mOwners.getDeviceOwnerComponent();
            for (EnforcingAdmin admin : admins) {
                if (deviceOwner != null
                        && deviceOwner.getPackageName().equals(admin.getPackageName())) {
                    enforcingUsers.add(new EnforcingUser(admin.getUserId(),
                            UserManager.RESTRICTION_SOURCE_DEVICE_OWNER));
                } else {
                    enforcingUsers.add(new EnforcingUser(admin.getUserId(),
                            UserManager.RESTRICTION_SOURCE_PROFILE_OWNER));
                }
            }
            return enforcingUsers;
        }
    }

    private Intent createShowAdminSupportIntent(int userId) {
        // This method is called with AMS lock held, so don't take DPMS lock
        final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
        intent.putExtra(Intent.EXTRA_USER_ID, userId);
        intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
        return intent;
    }

    /**
     * @param restriction The restriction enforced by admin. It could be any user restriction or
     *                    policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA},
     *                    {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE} and  {@link
     *                    DevicePolicyManager#POLICY_SUSPEND_PACKAGES}.
     */
    private Bundle getEnforcingAdminAndUserDetailsInternal(int userId, String restriction) {
        Bundle result = null;

        // For POLICY_SUSPEND_PACKAGES return PO or DO to keep the behavior same as
        // before the bug fix for b/192245204.
        if (restriction == null || DevicePolicyManager.POLICY_SUSPEND_PACKAGES.equals(
                restriction)) {
            ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
            if (profileOwner != null) {
                result = new Bundle();
                result.putInt(Intent.EXTRA_USER_ID, userId);
                result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
                        profileOwner);
                return result;
            }
            final Pair<Integer, ComponentName> deviceOwner =
                    mOwners.getDeviceOwnerUserIdAndComponent();
            if (deviceOwner != null && deviceOwner.first == userId) {
                result = new Bundle();
                result.putInt(Intent.EXTRA_USER_ID, userId);
                result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
                        deviceOwner.second);
                return result;
            }
        } else if (DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) {
            Boolean value = mDevicePolicyEngine.getResolvedPolicy(
                    PolicyDefinition.SCREEN_CAPTURE_DISABLED, userId);
            if (value != null && value) {
                result = new Bundle();
                result.putInt(Intent.EXTRA_USER_ID, userId);
                return result;
            }
        } else if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) {
            PolicyDefinition<Boolean> policyDefinition =
                    PolicyDefinition.getPolicyDefinitionForUserRestriction(
                            UserManager.DISALLOW_CAMERA);
            Boolean value = mDevicePolicyEngine.getResolvedPolicy(policyDefinition, userId);
            if (value != null && value) {
                result = new Bundle();
                result.putInt(Intent.EXTRA_USER_ID, userId);
                return result;
            }
        } else {
            long ident = mInjector.binderClearCallingIdentity();
            try {
                if (getEnforcingAdminsForRestrictionInternal(userId, restriction).size() == 0) {
                    return null;
                }

                ActiveAdmin admin = getMostProbableDPCAdminForLocalPolicy(userId);
                if (admin != null) {
                    result = new Bundle();
                    result.putInt(Intent.EXTRA_USER_ID, admin.getUserHandle().getIdentifier());
                    result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
                            admin.info.getComponent());
                    return result;
                }
                return null;
            } finally {
                mInjector.binderRestoreCallingIdentity(ident);
            }
        }
        return null;
    }

    /**
     * @param restriction The restriction enforced by admin. It could be any user restriction or
     *                    policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA},
     *                    {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE} and  {@link
     *                    DevicePolicyManager#POLICY_SUSPEND_PACKAGES}.
     */
    private Set<android.app.admin.EnforcingAdmin> getEnforcingAdminsForRestrictionInternal(
            int userId, @NonNull String restriction) {
        Objects.requireNonNull(restriction);
        Set<android.app.admin.EnforcingAdmin> admins = new HashSet<>();
        // For POLICY_SUSPEND_PACKAGES return PO or DO to keep the behavior same as
        // before the bug fix for b/192245204.
        if (DevicePolicyManager.POLICY_SUSPEND_PACKAGES.equals(
                restriction)) {
            ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
            if (profileOwner != null) {
                EnforcingAdmin admin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
                        profileOwner, userId);
                admins.add(admin.getParcelableAdmin());
                return admins;
            }
            final Pair<Integer, ComponentName> deviceOwner =
                    mOwners.getDeviceOwnerUserIdAndComponent();
            if (deviceOwner != null && deviceOwner.first == userId) {
                EnforcingAdmin admin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
                        deviceOwner.second, deviceOwner.first);
                admins.add(admin.getParcelableAdmin());
                return admins;
            }
        } else {
            long ident = mInjector.binderClearCallingIdentity();
            try {
                PolicyDefinition<Boolean> policyDefinition = getPolicyDefinitionForRestriction(
                        restriction);
                Boolean value = mDevicePolicyEngine.getResolvedPolicy(policyDefinition, userId);
                if (value != null && value) {
                    Map<EnforcingAdmin, PolicyValue<Boolean>> globalPolicies =
                            mDevicePolicyEngine.getGlobalPoliciesSetByAdmins(policyDefinition);
                    for (EnforcingAdmin admin : globalPolicies.keySet()) {
                        if (globalPolicies.get(admin) != null
                                && Boolean.TRUE.equals(globalPolicies.get(admin).getValue())) {
                            admins.add(admin.getParcelableAdmin());
                        }
                    }

                    Map<EnforcingAdmin, PolicyValue<Boolean>> localPolicies =
                            mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
                                    policyDefinition, userId);
                    for (EnforcingAdmin admin : localPolicies.keySet()) {
                        if (localPolicies.get(admin) != null
                                && Boolean.TRUE.equals(localPolicies.get(admin).getValue())) {
                            admins.add(admin.getParcelableAdmin());
                        }
                    }
                    return admins;
                }
            } finally {
                mInjector.binderRestoreCallingIdentity(ident);
            }
        }
        return admins;
    }

    private static PolicyDefinition<Boolean> getPolicyDefinitionForRestriction(
            @NonNull String restriction) {
        Objects.requireNonNull(restriction);
        if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) {
            return PolicyDefinition.getPolicyDefinitionForUserRestriction(
                    UserManager.DISALLOW_CAMERA);
        } else if (DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) {
            return PolicyDefinition.SCREEN_CAPTURE_DISABLED;
        } else {
            return PolicyDefinition.getPolicyDefinitionForUserRestriction(restriction);
        }
    }


    /**
     *  Excludes restrictions imposed by UserManager.
     */
    private List<UserManager.EnforcingUser> getDevicePolicySources(
            List<UserManager.EnforcingUser> sources) {
        int sizeBefore = sources.size();
        List<UserManager.EnforcingUser> realSources = new ArrayList<>(sizeBefore);
        for (int i = 0; i < sizeBefore; i++) {
            UserManager.EnforcingUser source = sources.get(i);
            int type = source.getUserRestrictionSource();
            if (type != UserManager.RESTRICTION_SOURCE_PROFILE_OWNER
                    && type != UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) {
                // TODO(b/128928355): add unit test
                Slogf.d(LOG_TAG, "excluding source of type %s at index %d",
                        userRestrictionSourceToString(type), i);
                continue;
            }
            realSources.add(source);
        }
        return realSources;
    }

    private static String userRestrictionSourceToString(@UserRestrictionSource int source) {
        return DebugUtils.flagsToString(UserManager.class, "RESTRICTION_", source);
    }

    /**
     * @param restriction The restriction enforced by admin. It could be any user restriction or
     *                    policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA} and
     *                    {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE}.
     * @return Details of admin and user which enforced the restriction for the userId.
     */
    @Override
    public Bundle getEnforcingAdminAndUserDetails(int userId, String restriction) {
        Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()));
        return getEnforcingAdminAndUserDetailsInternal(userId, restriction);
    }

    @Override
    public List<android.app.admin.EnforcingAdmin> getEnforcingAdminsForRestriction(
            int userId, String restriction) {
        Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()));
        return new ArrayList<>(getEnforcingAdminsForRestrictionInternal(userId, restriction));
    }

    /**
     * @param restriction The restriction enforced by admin. It could be any user restriction or
     *                    policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA} and
     *                    {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE}.
     */
    @Override
    public Intent createAdminSupportIntent(String restriction) {
        Objects.requireNonNull(restriction);
        final CallerIdentity caller = getCallerIdentity();
        final int userId = caller.getUserId();
        Intent intent = null;
        if (getEnforcingAdminAndUserDetailsInternal(userId, restriction) != null) {
            intent = createShowAdminSupportIntent(userId);
            intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, restriction);
        }
        return intent;
    }

    /**
     * Returns true if specified admin is allowed to limit passwords and has a
     * {@code mPasswordPolicy.quality} of at least {@code minPasswordQuality}
     */
    private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
        if (admin.mPasswordPolicy.quality < minPasswordQuality) {
            return false;
        }
        return admin.isPermissionBased || admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
    }

    @Override
    public void setCredentialManagerPolicy(PackagePolicy policy) {
        if (!mHasFeature) {
            return;
        }
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(canWriteCredentialManagerPolicy(caller));

        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
            if (Objects.equals(admin.mCredentialManagerPolicy, policy)) {
                return;
            }

            admin.mCredentialManagerPolicy = policy;
            saveSettingsLocked(caller.getUserId());
        }
    }

    private boolean canWriteCredentialManagerPolicy(CallerIdentity caller) {
        return (isProfileOwner(caller) && isManagedProfile(caller.getUserId()))
                        || isDefaultDeviceOwner(caller)
                        || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS);
    }

    @Override
    public PackagePolicy getCredentialManagerPolicy(int userId) {
        if (!mHasFeature) {
            return null;
        }
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(
                canWriteCredentialManagerPolicy(caller) || canQueryAdminPolicy(caller));
        if (userId != caller.getUserId()) {
            Preconditions.checkCallAuthorization(
                    hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS));
        }

        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(userId);
            return (admin != null) ? admin.mCredentialManagerPolicy : null;
        }
    }

    @Override
    public void setSystemUpdatePolicy(
            ComponentName who, String callerPackageName, SystemUpdatePolicy policy) {
        if (policy != null) {
            // throws exception if policy type is invalid
            policy.validateType();
            // throws exception if freeze period is invalid
            policy.validateFreezePeriods();
            Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord();
            // throws exception if freeze period is incompatible with previous freeze period record
            policy.validateAgainstPreviousFreezePeriod(record.first, record.second,
                    LocalDate.now());
        }
        CallerIdentity caller;

        synchronized (getLockObject()) {
            if (isPermissionCheckFlagEnabled()) {
                caller = getCallerIdentity(who, callerPackageName);
                enforcePermission(MANAGE_DEVICE_POLICY_SYSTEM_UPDATES, caller.getPackageName(),
                        UserHandle.USER_ALL);
            } else {
                caller = getCallerIdentity(who);
                Preconditions.checkCallAuthorization(
                        isProfileOwnerOfOrganizationOwnedDevice(caller)
                        || isDefaultDeviceOwner(caller));
            }

            checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_SYSTEM_UPDATE_POLICY);

            if (policy == null) {
                mOwners.clearSystemUpdatePolicy();
            } else {
                mOwners.setSystemUpdatePolicy(policy);
                updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ false);
            }
            mOwners.writeDeviceOwner();
        }
        mInjector.binderWithCleanCallingIdentity(() -> mContext.sendBroadcastAsUser(
                new Intent(ACTION_SYSTEM_UPDATE_POLICY_CHANGED), UserHandle.SYSTEM));
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_SYSTEM_UPDATE_POLICY)
                .setAdmin(caller.getPackageName())
                .setInt(policy != null ? policy.getPolicyType() : 0)
                .write();
    }

    @Override
    public SystemUpdatePolicy getSystemUpdatePolicy() {
        synchronized (getLockObject()) {
            SystemUpdatePolicy policy =  mOwners.getSystemUpdatePolicy();
            if (policy != null && !policy.isValid()) {
                Slogf.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
                return null;
            }
            return policy;
        }
    }

    private static boolean withinRange(Pair<LocalDate, LocalDate> range, LocalDate date) {
        return (!date.isBefore(range.first) && !date.isAfter(range.second));
    }

    /**
     * keeps track of the last continuous period when the system is under OTA freeze.
     *
     * DPMS keeps track of the previous dates during which OTA was freezed as a result of an
     * system update policy with freeze periods in effect. This is needed to make robust
     * validation on new system update polices, for example to prevent the OTA from being
     * frozen for more than 90 days if the DPC keeps resetting a new 24-hour freeze period
     * on midnight everyday, or having freeze periods closer than 60 days apart by DPC resetting
     * a new freeze period after a few days.
     *
     * @param saveIfChanged whether to persist the result on disk if freeze period record is
     *            updated. This should only be set to {@code false} if there is a guaranteed
     *            mOwners.writeDeviceOwner() later in the control flow to reduce the number of
     *            disk writes. Otherwise you risk inconsistent on-disk state.
     *
     * @see SystemUpdatePolicy#validateAgainstPreviousFreezePeriod
     */
    private void updateSystemUpdateFreezePeriodsRecord(boolean saveIfChanged) {
        Slogf.d(LOG_TAG, "updateSystemUpdateFreezePeriodsRecord");
        synchronized (getLockObject()) {
            final SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy();
            if (policy == null) {
                return;
            }
            final LocalDate now = LocalDate.now();
            final Pair<LocalDate, LocalDate> currentPeriod = policy.getCurrentFreezePeriod(now);
            if (currentPeriod == null) {
                return;
            }
            final Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord();
            final LocalDate start = record.first;
            final LocalDate end = record.second;
            final boolean changed;
            if (end == null || start == null) {
                // Start a new period if there is none at the moment
                changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now);
            } else if (now.equals(end.plusDays(1))) {
                // Extend the existing period
                changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now);
            } else if (now.isAfter(end.plusDays(1))) {
                if (withinRange(currentPeriod, start) && withinRange(currentPeriod, end)) {
                    // The device might be off for some period. If the past freeze record
                    // is within range of the current freeze period, assume the device was off
                    // during the period [end, now] and extend the freeze record to [start, now].
                    changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now);
                } else {
                    changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now);
                }
            } else if (now.isBefore(start)) {
                // Systm clock was adjusted backwards, restart record
                changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now);
            } else /* start <= now <= end */ {
                changed = false;
            }
            if (changed && saveIfChanged) {
                mOwners.writeDeviceOwner();
            }
        }
    }

    @Override
    public void clearSystemUpdatePolicyFreezePeriodRecord() {
        Preconditions.checkCallAuthorization(isAdb(getCallerIdentity())
                        || hasCallingOrSelfPermission(permission.CLEAR_FREEZE_PERIOD),
                "Caller must be shell, or hold CLEAR_FREEZE_PERIOD permission to call "
                        + "clearSystemUpdatePolicyFreezePeriodRecord");
        synchronized (getLockObject()) {
            // Print out current record to help diagnosed CTS failures
            Slogf.i(LOG_TAG, "Clear freeze period record: "
                    + mOwners.getSystemUpdateFreezePeriodRecordAsString());
            if (mOwners.setSystemUpdateFreezePeriodRecord(null, null)) {
                mOwners.writeDeviceOwner();
            }
        }
    }

    /**
     * Checks if any of the packages associated with the UID of the app provided is that
     * of the device owner.
     * @param appUid UID of the app to check.
     * @return {@code true} if any of the packages are the device owner, {@code false} otherwise.
     */
    private boolean isUidDeviceOwnerLocked(int appUid) {
        ensureLocked();
        final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
                .getPackageName();
        try {
            String[] pkgs = mInjector.getIPackageManager().getPackagesForUid(appUid);
            if (pkgs == null) {
                return false;
            }

            for (String pkg : pkgs) {
                if (deviceOwnerPackageName.equals(pkg)) {
                    return true;
                }
            }
        } catch (RemoteException e) {
            return false;
        }
        return false;
    }

    @Override
    public void notifyPendingSystemUpdate(@Nullable SystemUpdateInfo info) {
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE),
                "Only the system update service can broadcast update information");

        mInjector.binderWithCleanCallingIdentity(() -> {
            if (!mUserManager.getUserInfo(UserHandle.getCallingUserId()).isMain()) {
                Slogf.w(LOG_TAG, "Only the system update service in the main user can broadcast "
                        + "update information.");
                return;
            }
        });

        if (!mOwners.saveSystemUpdateInfo(info)) {
            // Pending system update hasn't changed, don't send duplicate notification.
            return;
        }

        final Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE)
                .putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
                        info == null ? -1 : info.getReceivedTime());

        mInjector.binderWithCleanCallingIdentity(() -> {
            synchronized (getLockObject()) {
                // Broadcast to device owner first if there is one.
                if (mOwners.hasDeviceOwner()) {
                    final UserHandle deviceOwnerUser =
                            UserHandle.of(mOwners.getDeviceOwnerUserId());
                    intent.setComponent(mOwners.getDeviceOwnerComponent());
                    mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
                }
            }
            // Get running users.
            final int runningUserIds[];
            try {
                runningUserIds = mInjector.getIActivityManager().getRunningUserIds();
            } catch (RemoteException e) {
                // Shouldn't happen.
                Slogf.e(LOG_TAG, "Could not retrieve the list of running users", e);
                return;
            }
            // Send broadcasts to corresponding profile owners if any.
            for (final int userId : runningUserIds) {
                synchronized (getLockObject()) {
                    final ComponentName profileOwnerPackage =
                            mOwners.getProfileOwnerComponent(userId);
                    if (profileOwnerPackage != null) {
                        intent.setComponent(profileOwnerPackage);
                        mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
                    }
                }
            }
        });
    }

    @Override
    public SystemUpdateInfo getPendingSystemUpdate(ComponentName admin) {
        Objects.requireNonNull(admin, "ComponentName is null");

        final CallerIdentity caller = getCallerIdentity(admin);
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || isProfileOwner(caller));

        return mOwners.getSystemUpdateInfo();
    }

    @Override
    public void setPermissionPolicy(ComponentName admin, String callerPackage, int policy) {
        final CallerIdentity caller = getCallerIdentity(admin, callerPackage);
        Preconditions.checkCallAuthorization((caller.hasAdminComponent()
                && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
                || (caller.hasPackage() && isCallerDelegate(caller,
                DELEGATION_PERMISSION_GRANT)));
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_PERMISSION_POLICY);

        final int forUser = caller.getUserId();
        synchronized (getLockObject()) {
            DevicePolicyData userPolicy = getUserData(forUser);
            if (userPolicy.mPermissionPolicy != policy) {
                userPolicy.mPermissionPolicy = policy;
                mPolicyCache.setPermissionPolicy(forUser, policy);
                saveSettingsLocked(forUser);
            }
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_PERMISSION_POLICY)
                .setAdmin(caller.getPackageName())
                .setInt(policy)
                .setBoolean(/* isDelegate */ admin == null)
                .write();
    }

    private void updatePermissionPolicyCache(int userId) {
        synchronized (getLockObject()) {
            DevicePolicyData userPolicy = getUserData(userId);
            mPolicyCache.setPermissionPolicy(userId, userPolicy.mPermissionPolicy);
        }
    }

    @Override
    public int getPermissionPolicy(ComponentName admin) throws RemoteException {
        int userId = UserHandle.getCallingUserId();
        return mPolicyCache.getPermissionPolicy(userId);
    }

    @Override
    public void setPermissionGrantState(ComponentName admin, String callerPackage,
            String packageName, String permission, int grantState, RemoteCallback callback)
            throws RemoteException {
        Objects.requireNonNull(callback);

        final CallerIdentity caller = getCallerIdentity(admin, callerPackage);
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_PERMISSION_GRANT_STATE);

        synchronized (getLockObject()) {
            if (isFinancedDeviceOwner(caller)) {
                enforcePermissionGrantStateOnFinancedDevice(packageName, permission);
            }
        }
        EnforcingAdmin enforcingAdmin;
        if (isUnicornFlagEnabled()) {
            enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                    admin,
                    MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS,
                    callerPackage,
                    caller.getUserId());
            if (SENSOR_PERMISSIONS.contains(permission)
                    && grantState == PERMISSION_GRANT_STATE_GRANTED
                    && (!canAdminGrantSensorsPermissions() || isCallerDelegate(caller))) {
                if (mInjector.isChangeEnabled(THROW_SECURITY_EXCEPTION_FOR_SENSOR_PERMISSIONS,
                        caller.getPackageName(), caller.getUserId())) {
                    throw new SecurityException(
                            "Caller not permitted to grant sensor permissions.");
                } else {
                    // This is to match the legacy behaviour.
                    callback.sendResult(Bundle.EMPTY);
                    return;
                }
            }
            // Check all the states where Exceptions aren't thrown but the permission
            // isn't granted either.
            if (!canGrantPermission(caller, permission, packageName)) {
                callback.sendResult(null);
                return;
            }
        } else {
            Preconditions.checkCallAuthorization((caller.hasAdminComponent()
                    && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)
                    || isFinancedDeviceOwner(caller)))
                    || (caller.hasPackage() && isCallerDelegate(caller,
                    DELEGATION_PERMISSION_GRANT)));
            synchronized (getLockObject()) {
                long ident = mInjector.binderClearCallingIdentity();
                try {
                    boolean isPostQAdmin = getTargetSdk(caller.getPackageName(), caller.getUserId())
                            >= android.os.Build.VERSION_CODES.Q;
                    if (!isPostQAdmin) {
                        // Legacy admins assume that they cannot control pre-M apps
                        if (getTargetSdk(packageName, caller.getUserId())
                                < android.os.Build.VERSION_CODES.M) {
                            callback.sendResult(null);
                            return;
                        }
                    }
                    if (!isRuntimePermission(permission)) {
                        callback.sendResult(null);
                        return;
                    }
                } catch (SecurityException e) {
                    Slogf.e(LOG_TAG, "Could not set permission grant state", e);
                    callback.sendResult(null);
                } finally {
                    mInjector.binderRestoreCallingIdentity(ident);
                }
            }
        }
        // TODO(b/278710449): enable when we stop policy enforecer callback from blocking the main
        //  thread
        if (false) {
            // TODO(b/266924257): decide how to handle the internal state if the package doesn't
            //  exist, or the permission isn't requested by the app, because we could end up with
            //  inconsistent state between the policy engine and package manager. Also a package
            //  might get removed or has it's permission updated after we've set the policy.
            if (grantState == PERMISSION_GRANT_STATE_DEFAULT) {
                mDevicePolicyEngine.removeLocalPolicy(
                        PolicyDefinition.PERMISSION_GRANT(packageName, permission),
                        enforcingAdmin,
                        caller.getUserId());
            } else {
                mDevicePolicyEngine.setLocalPolicy(
                        PolicyDefinition.PERMISSION_GRANT(packageName, permission),
                        enforcingAdmin,
                        new IntegerPolicyValue(grantState),
                        caller.getUserId());
            }
            int newState = mInjector.binderWithCleanCallingIdentity(() ->
                    getPermissionGrantStateForUser(
                            packageName, permission, caller, caller.getUserId()));
            if (newState == grantState) {
                callback.sendResult(Bundle.EMPTY);
            } else {
                callback.sendResult(null);
            }
        } else {
            synchronized (getLockObject()) {
                long ident = mInjector.binderClearCallingIdentity();
                try {
                    boolean isPostQAdmin = getTargetSdk(caller.getPackageName(), caller.getUserId())
                            >= android.os.Build.VERSION_CODES.Q;
                    if (grantState == PERMISSION_GRANT_STATE_GRANTED
                            || grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED
                            || grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT) {
                        AdminPermissionControlParams permissionParams =
                                new AdminPermissionControlParams(packageName, permission,
                                        grantState,
                                        canAdminGrantSensorsPermissions());
                        mInjector.getPermissionControllerManager(caller.getUserHandle())
                                .setRuntimePermissionGrantStateByDeviceAdmin(
                                        caller.getPackageName(),
                                        permissionParams, mContext.getMainExecutor(),
                                        (permissionWasSet) -> {
                                            if (isPostQAdmin && !permissionWasSet) {
                                                callback.sendResult(null);
                                                return;
                                            }
                                            callback.sendResult(Bundle.EMPTY);
                                        });
                    }
                } catch (SecurityException e) {
                    Slogf.e(LOG_TAG, "Could not set permission grant state", e);

                    callback.sendResult(null);
                } finally {
                    mInjector.binderRestoreCallingIdentity(ident);
                }
            }
        }
        DevicePolicyEventLogger.createEvent(DevicePolicyEnums.SET_PERMISSION_GRANT_STATE)
                .setAdmin(caller.getPackageName())
                .setStrings(permission)
                .setInt(grantState)
                .setBoolean(/* isDelegate */ isCallerDelegate(caller))
                .write();
    }

    private static final List<String> SENSOR_PERMISSIONS = new ArrayList<>();
    {
        SENSOR_PERMISSIONS.add(Manifest.permission.ACCESS_FINE_LOCATION);
        SENSOR_PERMISSIONS.add(Manifest.permission.ACCESS_BACKGROUND_LOCATION);
        SENSOR_PERMISSIONS.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        SENSOR_PERMISSIONS.add(Manifest.permission.CAMERA);
        SENSOR_PERMISSIONS.add(Manifest.permission.RECORD_AUDIO);
        SENSOR_PERMISSIONS.add(Manifest.permission.ACTIVITY_RECOGNITION);
        SENSOR_PERMISSIONS.add(Manifest.permission.BODY_SENSORS);
        SENSOR_PERMISSIONS.add(Manifest.permission.BACKGROUND_CAMERA);
        SENSOR_PERMISSIONS.add(Manifest.permission.RECORD_BACKGROUND_AUDIO);
        SENSOR_PERMISSIONS.add(Manifest.permission.BODY_SENSORS_BACKGROUND);
    }

    private boolean canGrantPermission(CallerIdentity caller, String permission,
            String targetPackageName) {
        boolean isPostQAdmin = getTargetSdk(caller.getPackageName(), caller.getUserId())
                >= android.os.Build.VERSION_CODES.Q;
        if (!isPostQAdmin) {
            // Legacy admins assume that they cannot control pre-M apps
            if (getTargetSdk(targetPackageName, caller.getUserId())
                    < android.os.Build.VERSION_CODES.M) {
                return false;
            }
        }
        if (!isRuntimePermission(permission)) {
            return false;
        }
        return true;
    }

    private void enforcePermissionGrantStateOnFinancedDevice(
            String packageName, String permission) {
        if (!Manifest.permission.READ_PHONE_STATE.equals(permission)) {
            throw new SecurityException(permission + " cannot be used when managing a financed"
                    + " device for permission grant state");
        } else if (!mOwners.getDeviceOwnerPackageName().equals(packageName)) {
            throw new SecurityException("Device owner package is the only package that can be used"
                    + " for permission grant state when managing a financed device");
        }
    }

    @Override
    public int getPermissionGrantState(ComponentName admin, String callerPackage,
            String packageName, String permission) throws RemoteException {
        final CallerIdentity caller = getCallerIdentity(admin, callerPackage);
        if (isUnicornFlagEnabled()) {
            enforceCanQuery(MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS, caller.getPackageName(),
                    caller.getUserId());
        } else {
            Preconditions.checkCallAuthorization(isSystemUid(caller) || (caller.hasAdminComponent()
                    && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)
                    || isFinancedDeviceOwner(caller)))
                    || (caller.hasPackage() && isCallerDelegate(caller,
                    DELEGATION_PERMISSION_GRANT)));
        }

        synchronized (getLockObject()) {
            if (isFinancedDeviceOwner(caller)) {
                enforcePermissionGrantStateOnFinancedDevice(packageName, permission);
            }
            return mInjector.binderWithCleanCallingIdentity(() -> getPermissionGrantStateForUser(
                    packageName, permission, caller, caller.getUserId()));
        }
    }

    private int getPermissionGrantStateForUser(
            String packageName, String permission, CallerIdentity caller, int userId)
            throws RemoteException {
        int granted;
        if (getTargetSdk(caller.getPackageName(), caller.getUserId())
                < android.os.Build.VERSION_CODES.Q) {
            // The per-Q behavior was to not check the app-ops state.
            granted = mIPackageManager.checkPermission(permission, packageName, userId);
        } else {
            try (var snapshot = mInjector.getPackageManagerLocal().withUnfilteredSnapshot()) {
                var packageState = snapshot.getPackageStates().get(packageName);
                if (packageState == null) {
                    Slog.w(LOG_TAG, "Can't get permission state for missing package "
                            + packageName);
                    return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
                } else if (!packageState.getUserStateOrDefault(userId).isInstalled()) {
                    Slog.w(LOG_TAG, "Can't get permission state for uninstalled package "
                            + packageName);
                    return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
                } else {
                    if (PermissionChecker.checkPermissionForPreflight(mContext, permission,
                            PermissionChecker.PID_UNKNOWN,
                            UserHandle.getUid(userId, packageState.getAppId()), packageName)
                            != PermissionChecker.PERMISSION_GRANTED) {
                        granted = PackageManager.PERMISSION_DENIED;
                    } else {
                        granted = PackageManager.PERMISSION_GRANTED;
                    }

                }
            }
        }
        int permFlags = mInjector.getPackageManager().getPermissionFlags(
                permission, packageName, UserHandle.of(userId));
        if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
                != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
            // Not controlled by policy
            return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
        } else {
            // Policy controlled so return result based on permission grant state
            return granted == PackageManager.PERMISSION_GRANTED
                    ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
                    : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
        }
    }

    boolean isPackageInstalledForUser(String packageName, int userHandle) {
        return mInjector.binderWithCleanCallingIdentity(() -> {
            try {
                PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
                        userHandle);
                return (pi != null) && (pi.applicationInfo.flags != 0);
            } catch (RemoteException re) {
                throw new RuntimeException("Package manager has died", re);
            }
        });
    }

    private boolean isRuntimePermission(String permissionName) {
        try {
            final PackageManager packageManager = mInjector.getPackageManager();
            PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0);
            return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
                    == PermissionInfo.PROTECTION_DANGEROUS;
        } catch (NameNotFoundException e) {
            return false;
        }
    }

    @Override
    public boolean isProvisioningAllowed(String action, String packageName) {
        Objects.requireNonNull(packageName);
        final CallerIdentity caller = getCallerIdentity();
        final long ident = mInjector.binderClearCallingIdentity();
        try {
            final List<String> callerUidPackageNames = Arrays.asList(
                    mInjector.getPackageManager().getPackagesForUid(caller.getUid()));
            Preconditions.checkArgument(callerUidPackageNames.contains(packageName),
                    "Caller uid doesn't match the one for the provided package.");

            return checkProvisioningPreconditionSkipPermission(action, packageName, caller.getUserId())
                    == STATUS_OK;
        } finally {
            mInjector.binderRestoreCallingIdentity(ident);
        }
    }

    @Override
    public int checkProvisioningPrecondition(String action, String packageName) {
        Objects.requireNonNull(packageName, "packageName is null");
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));

        long originalId = mInjector.binderClearCallingIdentity();
        try {
            return checkProvisioningPreconditionSkipPermission(
                    action, packageName, caller.getUserId());
        } finally {
            mInjector.binderRestoreCallingIdentity(originalId);
        }

    }
    private int checkProvisioningPreconditionSkipPermission(String action,
            String packageName, int userId) {
        if (!mHasFeature) {
            logMissingFeatureAction("Cannot check provisioning for action " + action);
            return STATUS_DEVICE_ADMIN_NOT_SUPPORTED;
        }
        if (!isProvisioningAllowed()) {
            return STATUS_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS;
        }
        final int code = checkProvisioningPreConditionSkipPermissionNoLog(
                action, packageName, userId);
        if (code != STATUS_OK) {
            Slogf.d(LOG_TAG, "checkProvisioningPreCondition(" + action + ", " + packageName
                    + ") failed: "
                    + computeProvisioningErrorString(code, mInjector.userHandleGetCallingUserId()));
        }
        return code;
    }

    /**
     *  Checks if provisioning is allowed during regular usage (non-developer/CTS). This could
     *  return {@code false} if the device has an overlaid config value set to false. If not set,
     *  the default is true.
     */
    private boolean isProvisioningAllowed() {
        boolean isDeveloperMode = isDeveloperMode(mContext);
        boolean isProvisioningAllowedForNormalUsers = SystemProperties.getBoolean(
                ALLOW_USER_PROVISIONING_KEY, /* defValue= */ true);

        return isDeveloperMode || isProvisioningAllowedForNormalUsers;
    }

    private static boolean isDeveloperMode(Context context) {
        return Global.getInt(context.getContentResolver(), Global.ADB_ENABLED, 0) > 0;
    }

    private int checkProvisioningPreConditionSkipPermissionNoLog(String action,
            String packageName, int userId) {
        if (action != null) {
            switch (action) {
                case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE:
                    return checkManagedProfileProvisioningPreCondition(packageName, userId);
                case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE:
                case DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE:
                    return checkDeviceOwnerProvisioningPreCondition(userId);
            }
        }
        throw new IllegalArgumentException("Unknown provisioning action " + action);
    }

    /**
     * The device owner can only be set before the setup phase of the primary user has completed,
     * except for adb command if no accounts or additional users are present on the device.
     */
    private int checkDeviceOwnerProvisioningPreConditionLocked(@Nullable ComponentName owner,
            @UserIdInt int deviceOwnerUserId, @UserIdInt int callingUserId, boolean isAdb,
            boolean hasIncompatibleAccountsOrNonAdb) {
        if (mOwners.hasDeviceOwner()) {
            return STATUS_HAS_DEVICE_OWNER;
        }
        if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
            return STATUS_USER_HAS_PROFILE_OWNER;
        }

        if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
            return STATUS_USER_NOT_RUNNING;
        }

        boolean isHeadlessSystemUserMode = mInjector.userManagerIsHeadlessSystemUserMode();

        if (isHeadlessSystemUserMode) {
            if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
                Slogf.e(LOG_TAG, "In headless system user mode, "
                        + "device owner can only be set on headless system user.");
                return STATUS_NOT_SYSTEM_USER;
            }

            if (owner != null) {
                DeviceAdminInfo adminInfo = findAdmin(
                        owner, deviceOwnerUserId, /* throwForMissingPermission= */ false);

                if (adminInfo.getHeadlessDeviceOwnerMode()
                        != HEADLESS_DEVICE_OWNER_MODE_AFFILIATED) {
                    return STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED;
                }
            }
        }

        if (isAdb) {
            // If shell command runs after user setup completed check device status. Otherwise, OK.
            if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
                // DO can be setup only if there are no users which are neither created by default
                // nor marked as FOR_TESTING

                if (nonTestNonPrecreatedUsersExist()) {
                    return STATUS_NONSYSTEM_USER_EXISTS;
                }

                int currentForegroundUser = getCurrentForegroundUserId();
                if (callingUserId != currentForegroundUser
                        && mInjector.userManagerIsHeadlessSystemUserMode()
                        && currentForegroundUser == UserHandle.USER_SYSTEM) {
                    Slogf.wtf(LOG_TAG, "In headless system user mode, "
                            + "current user cannot be system user when setting device owner");
                    return STATUS_SYSTEM_USER;
                }
                if (hasIncompatibleAccountsOrNonAdb) {
                    return STATUS_ACCOUNTS_NOT_EMPTY;
                }
            }
            return STATUS_OK;
        } else {
            // DO has to be user 0
            if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
                return STATUS_NOT_SYSTEM_USER;
            }
            // Only provision DO before setup wizard completes
            if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
                return STATUS_USER_SETUP_COMPLETED;
            }
            return STATUS_OK;
        }
    }

    /**
     * True if there are any users on the device which were not setup by default (1 usually, 2 for
     * devices with a headless system user) and also are not marked as FOR_TESTING.
     */
    private boolean nonTestNonPrecreatedUsersExist() {
        int allowedUsers = UserManager.isHeadlessSystemUserMode() ? 2 : 1;
        return mUserManagerInternal.getUsers(/* excludeDying= */ true).stream()
                .filter(u -> !u.isForTesting())
                .count() > allowedUsers;
    }

    private int checkDeviceOwnerProvisioningPreCondition(@UserIdInt int callingUserId) {
        synchronized (getLockObject()) {
            final int deviceOwnerUserId = mInjector.userManagerIsHeadlessSystemUserMode()
                    ? UserHandle.USER_SYSTEM
                    : callingUserId;
            Slogf.i(LOG_TAG, "Calling user %d, device owner will be set on user %d",
                    callingUserId, deviceOwnerUserId);
            // hasIncompatibleAccountsOrNonAdb doesn't matter since the caller is not adb.
            return checkDeviceOwnerProvisioningPreConditionLocked(/* owner unknown */ null,
                    deviceOwnerUserId, callingUserId, /* isAdb= */ false,
                    /* hasIncompatibleAccountsOrNonAdb=*/ true);
        }
    }

    private int checkManagedProfileProvisioningPreCondition(String packageName,
            @UserIdInt int callingUserId) {
        if (!hasFeatureManagedUsers()) {
            return STATUS_MANAGED_USERS_NOT_SUPPORTED;
        }
        if (getProfileOwnerAsUser(callingUserId) != null) {
            // Managed user cannot have a managed profile.
            return STATUS_USER_HAS_PROFILE_OWNER;
        }

        final long ident = mInjector.binderClearCallingIdentity();
        try {
            final UserHandle callingUserHandle = UserHandle.of(callingUserId);
            final boolean hasDeviceOwner;
            synchronized (getLockObject()) {
                hasDeviceOwner = getDeviceOwnerAdminLocked() != null;
            }

            final boolean addingProfileRestricted = mUserManager.hasUserRestriction(
                    UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserHandle);

            if (mUserManager.getUserInfo(callingUserId).isProfile()) {
                Slogf.i(LOG_TAG, "Calling user %d is a profile, cannot add another.",
                        callingUserId);
                // The check is called from inside a managed profile. A managed profile cannot
                // be provisioned from within another managed profile.
                return STATUS_CANNOT_ADD_MANAGED_PROFILE;
            }

            // If there's a device owner, the restriction on adding a managed profile must be set.
            if (hasDeviceOwner && !addingProfileRestricted) {
                Slogf.wtf(LOG_TAG, "Has a device owner but no restriction on adding a profile.");
            }

            // Do not allow adding a managed profile if there's a restriction.
            if (addingProfileRestricted) {
                Slogf.i(LOG_TAG, "Adding a profile is restricted: User %s Has device owner? %b",
                        callingUserHandle, hasDeviceOwner);
                return STATUS_CANNOT_ADD_MANAGED_PROFILE;
            }

            // Bail out if we are trying to provision a work profile but one already exists.
            if (!mUserManager.canAddMoreManagedProfiles(
                    callingUserId, /* allowedToRemoveOne= */ false)) {
                Slogf.i(LOG_TAG, "Cannot add more managed profiles.");
                return STATUS_CANNOT_ADD_MANAGED_PROFILE;
            }
        } finally {
            mInjector.binderRestoreCallingIdentity(ident);
        }
        return STATUS_OK;
    }

    private void checkIsDeviceOwner(CallerIdentity caller) {
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller), caller.getUid()
                + " is not device owner");
    }

    /**
     * Return device owner or profile owner set on a given user.
     */
    private @Nullable ComponentName getOwnerComponent(int userId) {
        synchronized (getLockObject()) {
            if (mOwners.getDeviceOwnerUserId() == userId) {
                return mOwners.getDeviceOwnerComponent();
            }
            if (mOwners.hasProfileOwner(userId)) {
                return mOwners.getProfileOwnerComponent(userId);
            }
        }
        return null;
    }

    private boolean hasFeatureManagedUsers() {
        try {
            return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
        } catch (RemoteException e) {
            return false;
        }
    }

    @Override
    public String getWifiMacAddress(ComponentName admin, String callerPackageName) {
//        if (!isPermissionCheckFlagEnabled()) {
            Objects.requireNonNull(admin, "ComponentName is null");
//        }

        final CallerIdentity caller = getCallerIdentity(admin, callerPackageName);
//        if (isPermissionCheckFlagEnabled()) {
//            enforcePermission(MANAGE_DEVICE_POLICY_WIFI, UserHandle.USER_ALL);
//        } else {
            Preconditions.checkCallAuthorization(
                    isDefaultDeviceOwner(caller)
                            || isProfileOwnerOfOrganizationOwnedDevice(caller));
//        }

        return mInjector.binderWithCleanCallingIdentity(() -> {
            String[] macAddresses = mInjector.getWifiManager().getFactoryMacAddresses();
            if (macAddresses == null) {
                return null;
            }
            DevicePolicyEventLogger
                    .createEvent(DevicePolicyEnums.GET_WIFI_MAC_ADDRESS)
                    .setAdmin(caller.getPackageName())
                    .write();
            return macAddresses.length > 0 ? macAddresses[0] : null;
        });
    }

    /**
     * Returns the target sdk version number that the given packageName was built for
     * in the given user.
     */
    private int getTargetSdk(String packageName, int userId) {
        final ApplicationInfo ai;
        try {
            ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
            return ai == null ? 0 : ai.targetSdkVersion;
        } catch (RemoteException e) {
            // Shouldn't happen
            Slogf.wtf(LOG_TAG, "Error getting application info", e);
            return 0;
        }
    }

    @Override
    public boolean isManagedProfile(ComponentName admin) {
        Objects.requireNonNull(admin, "ComponentName is null");

        final CallerIdentity caller = getCallerIdentity(admin);
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || isProfileOwner(caller));

        return isManagedProfile(caller.getUserId());
    }

    @Override
    public void reboot(ComponentName admin) {
        Objects.requireNonNull(admin, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(admin);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REBOOT);
        mInjector.binderWithCleanCallingIdentity(() -> {
            // Make sure there are no ongoing calls on the device.
            if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
                throw new IllegalStateException("Cannot be called with ongoing call on the device");
            }
            DevicePolicyEventLogger
                    .createEvent(DevicePolicyEnums.REBOOT)
                    .setAdmin(admin)
                    .write();
            mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
        });
    }

    @Override
    public void setShortSupportMessage(@Nullable ComponentName who, String callerPackageName,
            CharSequence message) {
        if (!mHasFeature) {
            return;
        }
        CallerIdentity caller;
        ActiveAdmin admin;

        message = truncateIfLonger(message, MAX_SHORT_SUPPORT_MESSAGE_LENGTH);

        if (isPermissionCheckFlagEnabled()) {
            caller = getCallerIdentity(who, callerPackageName);
            EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                    who,
                    MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE,
                    caller.getPackageName(),
                    caller.getUserId());
            admin = enforcingAdmin.getActiveAdmin();
        } else {
            caller = getCallerIdentity(who);
            Objects.requireNonNull(who, "ComponentName is null");
            synchronized (getLockObject()) {
                admin = getActiveAdminForUidLocked(who, caller.getUid());
            }
        }

        synchronized (getLockObject()) {
            if (!TextUtils.equals(admin.shortSupportMessage, message)) {
                admin.shortSupportMessage = message;
                saveSettingsLocked(caller.getUserId());
            }
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_SHORT_SUPPORT_MESSAGE)
                .setAdmin(caller.getPackageName())
                .write();
    }

    @Override
    public CharSequence getShortSupportMessage(@Nullable ComponentName who,
            String callerPackageName) {
        if (!mHasFeature) {
            return null;
        }
        CallerIdentity caller;
        ActiveAdmin admin;

        if (isPermissionCheckFlagEnabled()) {
            caller = getCallerIdentity(who, callerPackageName);
            EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                    who,
                    MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE,
                    caller.getPackageName(),
                    caller.getUserId());
            admin = enforcingAdmin.getActiveAdmin();
        } else {
            caller = getCallerIdentity(who);
            Objects.requireNonNull(who, "ComponentName is null");
            synchronized (getLockObject()) {
                admin = getActiveAdminForUidLocked(who, caller.getUid());
            }
        }
        return admin.shortSupportMessage;
    }

    @Override
    public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
        if (!mHasFeature) {
            return;
        }

        message = truncateIfLonger(message, MAX_LONG_SUPPORT_MESSAGE_LENGTH);

        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        synchronized (getLockObject()) {
            ActiveAdmin admin = getActiveAdminForUidLocked(who, caller.getUid());
            if (!TextUtils.equals(admin.longSupportMessage, message)) {
                admin.longSupportMessage = message;
                saveSettingsLocked(caller.getUserId());
            }
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_LONG_SUPPORT_MESSAGE)
                .setAdmin(who)
                .write();
    }

    @Override
    public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
        if (!mHasFeature) {
            return null;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        synchronized (getLockObject()) {
            ActiveAdmin admin = getActiveAdminForUidLocked(who, caller.getUid());
            return admin.longSupportMessage;
        }
    }

    @Override
    public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
        if (!mHasFeature) {
            return null;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
                String.format(NOT_SYSTEM_CALLER_MSG, "query support message for user"));

        synchronized (getLockObject()) {
            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
            if (admin != null) {
                return admin.shortSupportMessage;
            }
        }
        return null;
    }

    @Override
    public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
        if (!mHasFeature) {
            return null;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
                String.format(NOT_SYSTEM_CALLER_MSG, "query support message for user"));

        synchronized (getLockObject()) {
            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
            if (admin != null) {
                return admin.longSupportMessage;
            }
        }
        return null;
    }

    @Override
    public void setOrganizationColor(@NonNull ComponentName who, int color) {
        if (!mHasFeature) {
            return;
        }
        Objects.requireNonNull(who, "ComponentName is null");

        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallingUser(isManagedProfile(caller.getUserId()));
        Preconditions.checkCallAuthorization(isProfileOwner(caller));

        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
            admin.organizationColor = color;
            saveSettingsLocked(caller.getUserId());
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_ORGANIZATION_COLOR)
                .setAdmin(caller.getComponentName())
                .write();
    }

    @Override
    public void setOrganizationColorForUser(int color, int userId) {
        if (!mHasFeature) {
            return;
        }
        Preconditions.checkArgumentNonnegative(userId, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId));
        Preconditions.checkCallAuthorization(canManageUsers(caller));
        Preconditions.checkCallAuthorization(isManagedProfile(userId), "You can not "
                + "set organization color outside a managed profile, userId = %d", userId);

        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
            admin.organizationColor = color;
            saveSettingsLocked(userId);
        }
    }

    @Override
    public int getOrganizationColor(@NonNull ComponentName who) {
        if (!mHasFeature) {
            return ActiveAdmin.DEF_ORGANIZATION_COLOR;
        }
        Objects.requireNonNull(who, "ComponentName is null");

        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallingUser(isManagedProfile(caller.getUserId()));
        Preconditions.checkCallAuthorization(isProfileOwner(caller));

        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
            return admin.organizationColor;
        }
    }

    @Override
    public int getOrganizationColorForUser(int userHandle) {
        if (!mHasFeature) {
            return ActiveAdmin.DEF_ORGANIZATION_COLOR;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
        Preconditions.checkCallAuthorization(isManagedProfile(userHandle), "You can "
                + "not get organization color outside a managed profile, userId = %d", userHandle);

        synchronized (getLockObject()) {
            ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
            return (profileOwner != null)
                    ? profileOwner.organizationColor
                    : ActiveAdmin.DEF_ORGANIZATION_COLOR;
        }
    }

    @Override
    public void setOrganizationName(@Nullable ComponentName who, String callerPackageName,
            CharSequence text) {
        if (!mHasFeature) {
            return;
        }
        CallerIdentity caller = getCallerIdentity(who);
        ActiveAdmin admin = null;

        if (isPermissionCheckFlagEnabled()) {
            EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                    who,
                    MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY,
                    caller.getPackageName(),
                    caller.getUserId());
            admin = enforcingAdmin.getActiveAdmin();
        } else {
            Objects.requireNonNull(who, "ComponentName is null");
            Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
        }

        text = truncateIfLonger(text, MAX_ORG_NAME_LENGTH);

        synchronized (getLockObject()) {
            if (!isPermissionCheckFlagEnabled()) {
                admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
            }
            if (!TextUtils.equals(admin.organizationName, text)) {
                admin.organizationName = (text == null || text.length() == 0)
                        ? null : text.toString();
                saveSettingsLocked(caller.getUserId());
            }
        }
    }

    @Override
    public CharSequence getOrganizationName(@Nullable ComponentName who, String callerPackageName) {
        if (!mHasFeature) {
            return null;
        }
        CallerIdentity caller = getCallerIdentity(who);
        ActiveAdmin admin;

        if (isPermissionCheckFlagEnabled()) {
            EnforcingAdmin enforcingAdmin = enforceCanQueryAndGetEnforcingAdmin(
                    who,
                    MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY,
                    caller.getPackageName(),
                    caller.getUserId());
            admin = enforcingAdmin.getActiveAdmin();
        } else {
            Objects.requireNonNull(who, "ComponentName is null");
            Preconditions.checkCallingUser(isManagedProfile(caller.getUserId()));
            Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));

            synchronized (getLockObject()) {
                admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
            }
        }

        return admin.organizationName;
    }

    /**
     * This API is cached: invalidate with invalidateBinderCaches().
     */
    @Override
    public CharSequence getDeviceOwnerOrganizationName() {
        if (!mHasFeature) {
            return null;
        }
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
                || canManageUsers(caller) || isFinancedDeviceOwner(caller));
        synchronized (getLockObject()) {
            final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
            return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName;
        }
    }

    /**
     * This API is cached: invalidate with invalidateBinderCaches().
     */
    @Override
    public CharSequence getOrganizationNameForUser(int userHandle) {
        if (!mHasFeature) {
            return null;
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
        Preconditions.checkCallAuthorization(canManageUsers(caller));
        Preconditions.checkCallAuthorization(isManagedProfile(userHandle),
                "You can not get organization name outside a managed profile, userId = %d",
                userHandle);

        synchronized (getLockObject()) {
            ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
            return (profileOwner != null)
                    ? profileOwner.organizationName
                    : null;
        }
    }

    @Override
    public List<String> setMeteredDataDisabledPackages(ComponentName who, List<String> packageNames) {
        Objects.requireNonNull(who);
        Objects.requireNonNull(packageNames);
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || isProfileOwner(caller),
                "Admin %s does not own the profile", caller.getComponentName());

        if (!mHasFeature) {
            return packageNames;
        }
        return mInjector.binderWithCleanCallingIdentity(() -> {
            final List<String> excludedPkgs = removeInvalidPkgsForMeteredDataRestriction(
                    caller.getUserId(), packageNames);

            synchronized (getLockObject()) {
                final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
                admin.meteredDisabledPackages = packageNames;
                saveSettingsLocked(caller.getUserId());
            }
            pushMeteredDisabledPackages(caller.getUserId());
            return excludedPkgs;
        });
    }

    private List<String> removeInvalidPkgsForMeteredDataRestriction(
            int userId, List<String> pkgNames) {
        synchronized (getLockObject()) {
            final Set<String> activeAdmins = getActiveAdminPackagesLocked(userId);
            final List<String> excludedPkgs = new ArrayList<>();
            for (int i = pkgNames.size() - 1; i >= 0; --i) {
                final String pkgName = pkgNames.get(i);
                // If the package is an active admin, don't restrict it.
                if (activeAdmins.contains(pkgName)) {
                    excludedPkgs.add(pkgName);
                    continue;
                }
                // If the package doesn't exist, don't restrict it.
                try {
                    if (!mInjector.getIPackageManager().isPackageAvailable(pkgName, userId)) {
                        excludedPkgs.add(pkgName);
                    }
                } catch (RemoteException e) {
                    // Should not happen
                }
            }
            pkgNames.removeAll(excludedPkgs);
            return excludedPkgs;
        }
    }

    @Override
    public List<String> getMeteredDataDisabledPackages(ComponentName who) {
        Objects.requireNonNull(who);

        if (!mHasFeature) {
            return new ArrayList<>();
        }
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || isProfileOwner(caller),
                "Admin %s does not own the profile", caller.getComponentName());

        synchronized (getLockObject()) {
            final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
            return admin.meteredDisabledPackages == null
                    ? new ArrayList<>() : admin.meteredDisabledPackages;
        }
    }

    @Override
    public boolean isMeteredDataDisabledPackageForUser(ComponentName who,
            String packageName, int userId) {
        Objects.requireNonNull(who);

        if (!mHasFeature) {
            return false;
        }
        Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
                String.format(NOT_SYSTEM_CALLER_MSG, "query restricted pkgs for a specific user"));

        synchronized (getLockObject()) {
            final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId);
            if (admin != null && admin.meteredDisabledPackages != null) {
                return admin.meteredDisabledPackages.contains(packageName);
            }
        }
        return false;
    }

    @Override
    public void setProfileOwnerOnOrganizationOwnedDevice(ComponentName who, int userId,
            boolean isProfileOwnerOnOrganizationOwnedDevice) {
        if (!mHasFeature) {
            return;
        }
        // As the caller is the system, it must specify the component name of the profile owner
        // as a safety check.
        Objects.requireNonNull(who);

        final CallerIdentity caller = getCallerIdentity();
        // Only adb or system apps with the right permission can mark a profile owner on
        // organization-owned device.
        if (!(isAdb(caller) || hasCallingPermission(permission.MARK_DEVICE_ORGANIZATION_OWNED)
                || hasCallingPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS))) {
            throw new SecurityException(
                    "Only the system can mark a profile owner of organization-owned device.");
        }
        // Only a test admin can be unmarked as a profile owner on an organization-owned device.
        synchronized (getLockObject()) {
            if (!isProfileOwnerOnOrganizationOwnedDevice && !isAdminTestOnlyLocked(who, userId)) {
                throw new SecurityException("Only a test admin can be unmarked as a "
                        + "profile owner of organization-owned device.");
            }
        }

        if (isAdb(caller)) {
            if (hasIncompatibleAccountsOrNonAdbNoLock(caller, userId, who)) {
                throw new SecurityException(
                        "Can only be called from ADB if the device has no accounts.");
            }
        } else {
            if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
                throw new IllegalStateException(
                        "Cannot mark profile owner as managing an organization-owned device after"
                                + " set-up");
            }
        }

        // Grant access under lock.
        synchronized (getLockObject()) {
            setProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(who, userId,
                    isProfileOwnerOnOrganizationOwnedDevice);
        }
    }

    @GuardedBy("getLockObject()")
    private void setProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(
            ComponentName who, int userId, boolean isProfileOwnerOnOrganizationOwnedDevice) {
        // Make sure that the user has a profile owner and that the specified
        // component is the profile owner of that user.
        if (!isProfileOwner(who, userId)) {
            throw new IllegalArgumentException(String.format(
                    "Component %s is not a Profile Owner of user %d",
                    who.flattenToString(), userId));
        }

        Slogf.i(LOG_TAG, "%s %s as profile owner on organization-owned device for user %d",
                isProfileOwnerOnOrganizationOwnedDevice ? "Marking" : "Unmarking",
                who.flattenToString(), userId);

        // First, set restriction on removing the profile.
        mInjector.binderWithCleanCallingIdentity(() -> {
            // Clear restriction as user.
            final UserHandle parentUser = mUserManager.getProfileParent(UserHandle.of(userId));
            if (parentUser == null) {
                throw new IllegalStateException(String.format("User %d is not a profile", userId));
            }

            mUserManager.setUserRestriction(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
                    isProfileOwnerOnOrganizationOwnedDevice,
                    parentUser);
            mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER,
                    isProfileOwnerOnOrganizationOwnedDevice,
                    parentUser);
        });

        // setProfileOwnerOfOrganizationOwnedDevice will trigger writing of the profile owner
        // data, no need to do it manually.
        mOwners.setProfileOwnerOfOrganizationOwnedDevice(userId,
                isProfileOwnerOnOrganizationOwnedDevice);
    }

    private void pushMeteredDisabledPackages(int userId) {
        wtfIfInLock();
        mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackages(
                getMeteredDisabledPackages(userId), userId);
    }

    private Set<String> getMeteredDisabledPackages(int userId) {
        synchronized (getLockObject()) {
            final Set<String> restrictedPkgs = new ArraySet<>();
            final ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userId);
            if (admin != null && admin.meteredDisabledPackages != null) {
                restrictedPkgs.addAll(admin.meteredDisabledPackages);
            }

            return restrictedPkgs;
        }
    }

    @Override
    public void setAffiliationIds(ComponentName admin, List<String> ids) {
        if (!mHasFeature) {
            return;
        }
        if (ids == null) {
            throw new IllegalArgumentException("ids must not be null");
        }
        for (String id : ids) {
            Preconditions.checkArgument(!TextUtils.isEmpty(id), "ids must not have empty string");
            enforceMaxStringLength(id, "affiliation id");
        }

        final Set<String> affiliationIds = new ArraySet<>(ids);
        final CallerIdentity caller = getCallerIdentity(admin);
        Preconditions.checkCallAuthorization(
                isProfileOwner(caller) || isDefaultDeviceOwner(caller));
        final int callingUserId = caller.getUserId();

        synchronized (getLockObject()) {
            getUserData(callingUserId).mAffiliationIds = affiliationIds;
            saveSettingsLocked(callingUserId);
            mStateCache.setHasAffiliationWithDevice(callingUserId,
                    isUserAffiliatedWithDeviceLocked(callingUserId));
            if (callingUserId == UserHandle.USER_SYSTEM) {
                resetAffiliationCacheLocked();
            } else if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin,
                    callingUserId)) {
                // Affiliation ids specified by the device owner are additionally stored in
                // UserHandle.USER_SYSTEM's DevicePolicyData.
                getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
                mStateCache.setHasAffiliationWithDevice(UserHandle.USER_SYSTEM, true);
                saveSettingsLocked(UserHandle.USER_SYSTEM);
            }

            // Affiliation status for any user, not just the calling user, might have changed.
            // The device owner user will still be affiliated after changing its affiliation ids,
            // but as a result of that other users might become affiliated or un-affiliated.
            maybePauseDeviceWideLoggingLocked();
            maybeResumeDeviceWideLoggingLocked();
            maybeClearLockTaskPolicyLocked();
            updateAdminCanGrantSensorsPermissionCache(callingUserId);
        }
    }

    private void resetAffiliationCacheLocked() {
        mInjector.binderWithCleanCallingIdentity(() -> {
            for (UserInfo user : mUserManager.getUsers()) {
                mStateCache.setHasAffiliationWithDevice(user.id,
                        isUserAffiliatedWithDeviceLocked(user.id));
            }
        });
    }

    @Override
    public List<String> getAffiliationIds(ComponentName admin) {
        if (!mHasFeature) {
            return Collections.emptyList();
        }

        Objects.requireNonNull(admin);
        final CallerIdentity caller = getCallerIdentity(admin);
        Preconditions.checkCallAuthorization(
                isProfileOwner(caller) || isDefaultDeviceOwner(caller));

        synchronized (getLockObject()) {
            return new ArrayList<String>(getUserData(caller.getUserId()).mAffiliationIds);
        }
    }

    @Override
    public boolean isCallingUserAffiliated() {
        if (!mHasFeature) {
            return false;
        }

        synchronized (getLockObject()) {
            return isUserAffiliatedWithDeviceLocked(mInjector.userHandleGetCallingUserId());
        }
    }

    @Override
    public boolean isAffiliatedUser(@UserIdInt int userId) {
        if (!mHasFeature) {
            return false;
        }
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));

        return isUserAffiliatedWithDevice(userId);
    }

    private boolean isUserAffiliatedWithDevice(@UserIdInt int userId) {
        synchronized (getLockObject()) {
            return isUserAffiliatedWithDeviceLocked(userId);
        }
    }

    private boolean isUserAffiliatedWithDeviceLocked(@UserIdInt int userId) {
        if (!mOwners.hasDeviceOwner()) {
            return false;
        }
        if (userId == UserHandle.USER_SYSTEM) {
            // The system user is always affiliated in a DO device,
            // even if in headless system user mode.
            return true;
        }
        if (userId == mOwners.getDeviceOwnerUserId()) {
            // The user that the DO is installed on is always affiliated with the device.
            return true;
        }

        final ComponentName profileOwner = getProfileOwnerAsUser(userId);
        if (profileOwner == null) {
            return false;
        }

        final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds;
        final Set<String> deviceAffiliationIds =
                getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
        for (String id : userAffiliationIds) {
            if (deviceAffiliationIds.contains(id)) {
                return true;
            }
        }
        return false;
    }

    private boolean areAllUsersAffiliatedWithDeviceLocked() {
        return mInjector.binderWithCleanCallingIdentity(() -> {
            final List<UserInfo> userInfos = mUserManager.getAliveUsers();
            for (int i = 0; i < userInfos.size(); i++) {
                int userId = userInfos.get(i).id;
                if (!isUserAffiliatedWithDeviceLocked(userId)) {
                    Slogf.d(LOG_TAG, "User id " + userId + " not affiliated.");
                    return false;
                }
            }
            return true;
        });
    }

    private @UserIdInt int getSecurityLoggingEnabledUser() {
        synchronized (getLockObject()) {
            if (mOwners.hasDeviceOwner()) {
                return UserHandle.USER_ALL;
            }
        }
        // TODO: Add check for permission-based
        return getOrganizationOwnedProfileUserId();
    }

    @Override
    public void setSecurityLoggingEnabled(ComponentName admin, String packageName,
            boolean enabled) {
        if (!mHasFeature) {
            return;
        }
        final CallerIdentity caller = getCallerIdentity(admin, packageName);

        synchronized (getLockObject()) {
            if (isPermissionCheckFlagEnabled()) {
                enforcePermission(MANAGE_DEVICE_POLICY_SECURITY_LOGGING, caller.getPackageName(),
                        UserHandle.USER_ALL);
            } else {
                if (admin != null) {
                    Preconditions.checkCallAuthorization(
                            isProfileOwnerOfOrganizationOwnedDevice(caller)
                                    || isDefaultDeviceOwner(caller));
                } else {
                    // A delegate app passes a null admin component, which is expected
                    Preconditions.checkCallAuthorization(
                            isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING));
                }
            }

            if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
                return;
            }
            mInjector.securityLogSetLoggingEnabledProperty(enabled);
            if (enabled) {
                mSecurityLogMonitor.start(getSecurityLoggingEnabledUser());
                maybePauseDeviceWideLoggingLocked();
            } else {
                mSecurityLogMonitor.stop();
            }
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_SECURITY_LOGGING_ENABLED)
                .setAdmin(caller.getPackageName())
                .setBoolean(enabled)
                .write();
    }

    @Override
    public boolean isSecurityLoggingEnabled(ComponentName admin, String packageName) {
        if (!mHasFeature) {
            return false;
        }

        synchronized (getLockObject()) {
            if (!isSystemUid(getCallerIdentity())) {
                final CallerIdentity caller = getCallerIdentity(admin, packageName);
                if (isPermissionCheckFlagEnabled()) {
                    enforcePermission(MANAGE_DEVICE_POLICY_SECURITY_LOGGING,
                            caller.getPackageName(), UserHandle.USER_ALL);
                } else {
                    if (admin != null) {
                        Preconditions.checkCallAuthorization(
                                isProfileOwnerOfOrganizationOwnedDevice(caller)
                                        || isDefaultDeviceOwner(caller));
                    } else {
                        // A delegate app passes a null admin component, which is expected
                        Preconditions.checkCallAuthorization(
                                isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING));
                    }
                }
            }
            return mInjector.securityLogGetLoggingEnabledProperty();
        }
    }

    private void recordSecurityLogRetrievalTime() {
        synchronized (getLockObject()) {
            final long currentTime = System.currentTimeMillis();
            DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
            if (currentTime > policyData.mLastSecurityLogRetrievalTime) {
                policyData.mLastSecurityLogRetrievalTime = currentTime;
                saveSettingsLocked(UserHandle.USER_SYSTEM);
            }
        }
    }

    @Override
    public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin,
            String packageName) {
        if (!mHasFeature) {
            return null;
        }

        final CallerIdentity caller = getCallerIdentity(admin, packageName);
        if (isPermissionCheckFlagEnabled()) {
            Preconditions.checkCallAuthorization(isOrganizationOwnedDeviceWithManagedProfile()
                    || areAllUsersAffiliatedWithDeviceLocked());
            enforcePermission(MANAGE_DEVICE_POLICY_SECURITY_LOGGING, caller.getPackageName(),
                    UserHandle.USER_ALL);
        } else {
            if (admin != null) {
                Preconditions.checkCallAuthorization(
                        isProfileOwnerOfOrganizationOwnedDevice(caller)
                                || isDefaultDeviceOwner(caller));
            } else {
                // A delegate app passes a null admin component, which is expected
                Preconditions.checkCallAuthorization(
                        isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING));
            }

            Preconditions.checkCallAuthorization(isOrganizationOwnedDeviceWithManagedProfile()
                    || areAllUsersAffiliatedWithDeviceLocked());
        }

        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.RETRIEVE_PRE_REBOOT_SECURITY_LOGS)
                .setAdmin(caller.getPackageName())
                .write();

        if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)
                || !mInjector.securityLogGetLoggingEnabledProperty()) {
            return null;
        }

        recordSecurityLogRetrievalTime();
        ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
        try {
            SecurityLog.readPreviousEvents(output);
            int enabledUser = getSecurityLoggingEnabledUser();
            if (enabledUser != UserHandle.USER_ALL) {
                SecurityLog.redactEvents(output, enabledUser);
            }
            return new ParceledListSlice<SecurityEvent>(output);
        } catch (IOException e) {
            Slogf.w(LOG_TAG, "Fail to read previous events" , e);
            return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
        }
    }

    @Override
    public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin,
            String packageName) {
        if (!mHasFeature) {
            return null;
        }

        final CallerIdentity caller = getCallerIdentity(admin, packageName);
        if (isPermissionCheckFlagEnabled()) {
            Preconditions.checkCallAuthorization(isOrganizationOwnedDeviceWithManagedProfile()
                    || areAllUsersAffiliatedWithDeviceLocked());

            enforcePermission(MANAGE_DEVICE_POLICY_SECURITY_LOGGING, caller.getPackageName(),
                    UserHandle.USER_ALL);
        } else {
            if (admin != null) {
                Preconditions.checkCallAuthorization(
                        isProfileOwnerOfOrganizationOwnedDevice(caller)
                        || isDefaultDeviceOwner(caller));
            } else {
                // A delegate app passes a null admin component, which is expected
                Preconditions.checkCallAuthorization(
                        isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING));
            }
            Preconditions.checkCallAuthorization(isOrganizationOwnedDeviceWithManagedProfile()
                    || areAllUsersAffiliatedWithDeviceLocked());
        }

        if (!mInjector.securityLogGetLoggingEnabledProperty()) {
            return null;
        }

        recordSecurityLogRetrievalTime();

        List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.RETRIEVE_SECURITY_LOGS)
                .setAdmin(caller.getPackageName())
                .write();
        return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
    }

    @Override
    public long forceSecurityLogs() {
        Preconditions.checkCallAuthorization(isAdb(getCallerIdentity())
                        || hasCallingOrSelfPermission(permission.FORCE_DEVICE_POLICY_MANAGER_LOGS),
                "Caller must be shell or hold FORCE_DEVICE_POLICY_MANAGER_LOGS to call "
                        + "forceSecurityLogs");
        if (!mInjector.securityLogGetLoggingEnabledProperty()) {
            throw new IllegalStateException("logging is not available");
        }
        return mSecurityLogMonitor.forceLogs();
    }

    @Override
    public boolean isUninstallInQueue(final String packageName) {
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS));

        UserPackage packageUserPair = UserPackage.of(caller.getUserId(), packageName);
        synchronized (getLockObject()) {
            return mPackagesToRemove.contains(packageUserPair);
        }
    }

    @Override
    public void uninstallPackageWithActiveAdmins(final String packageName) {
        Preconditions.checkArgument(!TextUtils.isEmpty(packageName));

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS));

        final int userId = caller.getUserId();
        enforceUserUnlocked(userId);

        final ComponentName profileOwner = getProfileOwnerAsUser(userId);
        if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
            throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
        }

        final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
        if (getDeviceOwnerUserId() == userId && deviceOwner != null
                && packageName.equals(deviceOwner.getPackageName())) {
            throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
        }

        final UserPackage packageUserPair = UserPackage.of(userId, packageName);
        synchronized (getLockObject()) {
            mPackagesToRemove.add(packageUserPair);
        }

        // All active admins on the user.
        final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);

        // Active admins in the target package.
        final List<ComponentName> packageActiveAdmins = new ArrayList<>();
        if (allActiveAdmins != null) {
            for (ComponentName activeAdmin : allActiveAdmins) {
                if (packageName.equals(activeAdmin.getPackageName())) {
                    packageActiveAdmins.add(activeAdmin);
                    removeActiveAdmin(activeAdmin, userId);
                }
            }
        }
        if (packageActiveAdmins.size() == 0) {
            startUninstallIntent(packageName, userId);
        } else {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    for (ComponentName activeAdmin : packageActiveAdmins) {
                        removeAdminArtifacts(activeAdmin, userId);
                    }
                    startUninstallIntent(packageName, userId);
                }
            }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
        }
    }

    @Override
    public boolean isDeviceProvisioned() {
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(canManageUsers(caller));

        synchronized (getLockObject()) {
            return getUserDataUnchecked(UserHandle.USER_SYSTEM).mUserSetupComplete;
        }
    }

    private boolean isCurrentUserDemo() {
        if (UserManager.isDeviceInDemoMode(mContext)) {
            final int userId = mInjector.userHandleGetCallingUserId();
            return mInjector.binderWithCleanCallingIdentity(
                    () -> mUserManager.getUserInfo(userId).isDemo());
        }
        return false;
    }

    private void removePackageIfRequired(final String packageName, final int userId) {
        if (!packageHasActiveAdmins(packageName, userId)) {
            // Will not do anything if uninstall was not requested or was already started.
            startUninstallIntent(packageName, userId);
        }
    }

    private void startUninstallIntent(final String packageName, final int userId) {
        final UserPackage packageUserPair = UserPackage.of(userId, packageName);
        synchronized (getLockObject()) {
            if (!mPackagesToRemove.contains(packageUserPair)) {
                // Do nothing if uninstall was not requested or was already started.
                return;
            }
            mPackagesToRemove.remove(packageUserPair);
        }
        if (!isPackageInstalledForUser(packageName, userId)) {
            // Package does not exist. Nothing to do.
            return;
        }

        try { // force stop the package before uninstalling
            mInjector.getIActivityManager().forceStopPackage(packageName, userId);
        } catch (RemoteException re) {
            Slogf.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
        }
        final Uri packageURI = Uri.parse("package:" + packageName);
        final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
        uninstallIntent.setFlags(FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
    }

    /**
     * Removes the admin from the policy. Ideally called after the admin's
     * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
     *
     * @param adminReceiver The admin to remove
     * @param userHandle The user for which this admin has to be removed.
     */
    private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
        synchronized (getLockObject()) {
            final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
            if (admin == null) {
                return;
            }
            final DevicePolicyData policy = getUserData(userHandle);
            final boolean doProxyCleanup = admin.info.usesPolicy(
                    DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
            policy.mAdminList.remove(admin);
            policy.mAdminMap.remove(adminReceiver);
            policy.validatePasswordOwner();
            if (doProxyCleanup) {
                resetGlobalProxyLocked(policy);
            }
            pushActiveAdminPackagesLocked(userHandle);
            saveSettingsLocked(userHandle);
            updateMaximumTimeToLockLocked(userHandle);

            Slogf.d(LOG_TAG,
                    "Removing device admin " + adminReceiver + " from user " + userHandle);
            logStackTrace("removeAdminArtifacts");

            policy.mRemovingAdmins.remove(adminReceiver);
            Slogf.d(LOG_TAG, "Current state of DevicePolicyData#mRemovingAdmins for user "
                    + userHandle + ": " + policy.mRemovingAdmins);

            Slogf.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
        }
        pushMeteredDisabledPackages(userHandle);
    }

    @Override
    public void setDeviceProvisioningConfigApplied() {
        Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));

        synchronized (getLockObject()) {
            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
            policy.mDeviceProvisioningConfigApplied = true;
            saveSettingsLocked(UserHandle.USER_SYSTEM);
        }
    }

    @Override
    public boolean isDeviceProvisioningConfigApplied() {
        Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));

        synchronized (getLockObject()) {
            final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
            return policy.mDeviceProvisioningConfigApplied;
        }
    }

    /**
     * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE.
     *
     * It's added for testing only. Please use this API carefully if it's used by other system app
     * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system
     * apps.
     */
    @Override
    public void forceUpdateUserSetupComplete(@UserIdInt int userId) {
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));

        boolean isUserCompleted = mInjector.settingsSecureGetIntForUser(
                Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0;
        DevicePolicyData policy = getUserData(userId);
        policy.mUserSetupComplete = isUserCompleted;
        mStateCache.setDeviceProvisioned(isUserCompleted);
        synchronized (getLockObject()) {
            saveSettingsLocked(userId);
        }
    }

    @Override
    public void setBackupServiceEnabled(ComponentName admin, boolean enabled) {
        if (!mHasFeature) {
            return;
        }
        Objects.requireNonNull(admin, "ComponentName is null");

        final CallerIdentity caller = getCallerIdentity(admin);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
                || isProfileOwner(caller) || isFinancedDeviceOwner(caller));

        toggleBackupServiceActive(caller.getUserId(), enabled);
    }

    @Override
    public boolean isBackupServiceEnabled(ComponentName admin) {
        if (!mHasFeature) {
            return true;
        }
        Objects.requireNonNull(admin, "ComponentName is null");

        final CallerIdentity caller = getCallerIdentity(admin);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
                || isProfileOwner(caller) || isFinancedDeviceOwner(caller));

        return mInjector.binderWithCleanCallingIdentity(() -> {
            synchronized (getLockObject()) {
                try {
                    IBackupManager ibm = mInjector.getIBackupManager();
                    return ibm != null && ibm.isBackupServiceActive(caller.getUserId());
                } catch (RemoteException e) {
                    throw new IllegalStateException("Failed requesting backup service state.", e);
                }
            }
        });
    }

    @Override
    public boolean bindDeviceAdminServiceAsUser(
            @NonNull ComponentName admin, @NonNull IApplicationThread caller,
            @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent,
            @NonNull IServiceConnection connection, long flags, @UserIdInt int targetUserId) {
        if (!mHasFeature) {
            return false;
        }
        Objects.requireNonNull(admin);
        Objects.requireNonNull(caller);
        Objects.requireNonNull(serviceIntent);
        Preconditions.checkArgument(
                serviceIntent.getComponent() != null || serviceIntent.getPackage() != null,
                "Service intent must be explicit (with a package name or component): "
                        + serviceIntent);
        Objects.requireNonNull(connection);
        Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId,
                "target user id must be different from the calling user id");

        if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) {
            throw new SecurityException("Not allowed to bind to target user id");
        }

        final String targetPackage;
        synchronized (getLockObject()) {
            targetPackage = getOwnerPackageNameForUserLocked(targetUserId);
        }

        final long callingIdentity = mInjector.binderClearCallingIdentity();
        try {
            // Validate and sanitize the incoming service intent.
            final Intent sanitizedIntent =
                    createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId);
            if (sanitizedIntent == null) {
                // Fail, cannot lookup the target service.
                return false;
            }
            // Ask ActivityManager to bind it. Notice that we are binding the service with the
            // caller app instead of DevicePolicyManagerService.
            return mInjector.getIActivityManager().bindService(
                    caller, activtiyToken, serviceIntent,
                    serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
                    connection, flags, mContext.getOpPackageName(),
                    targetUserId) != 0;
        } catch (RemoteException ex) {
            // Same process, should not happen.
        } finally {
            mInjector.binderRestoreCallingIdentity(callingIdentity);
        }

        // Failed to bind.
        return false;
    }

    @Override
    public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
        if (!mHasFeature) {
            return Collections.emptyList();
        }
        Objects.requireNonNull(admin);
        final CallerIdentity caller = getCallerIdentity(admin);
        Preconditions.checkCallAuthorization(
                isProfileOwner(caller) || isDefaultDeviceOwner(caller));

        synchronized (getLockObject()) {
            final int callingUserId = caller.getUserId();
            return mInjector.binderWithCleanCallingIdentity(() -> {
                ArrayList<UserHandle> targetUsers = new ArrayList<>();
                if (!isDeviceOwner(admin, callingUserId)) {
                    // Profile owners can only bind to the device owner.
                    if (canUserBindToDeviceOwnerLocked(callingUserId)) {
                        targetUsers.add(UserHandle.of(mOwners.getDeviceOwnerUserId()));
                    }
                } else {
                    // Caller is the device owner: Look for profile owners that it can bind to.
                    final List<UserInfo> userInfos = mUserManager.getAliveUsers();
                    for (int i = 0; i < userInfos.size(); i++) {
                        final int userId = userInfos.get(i).id;
                        if (userId != callingUserId && canUserBindToDeviceOwnerLocked(userId)) {
                            targetUsers.add(UserHandle.of(userId));
                        }
                    }
                }

                return targetUsers;
            });
        }
    }

    private boolean canUserBindToDeviceOwnerLocked(int userId) {
        // There has to be a device owner, under another user id.
        if (!mOwners.hasDeviceOwner() || userId == mOwners.getDeviceOwnerUserId()) {
            return false;
        }

        // The user must have a profile owner that belongs to the same package as the device owner.
        if (!mOwners.hasProfileOwner(userId) || !TextUtils.equals(
                mOwners.getDeviceOwnerPackageName(), mOwners.getProfileOwnerPackage(userId))) {
            return false;
        }

        // The user must be affiliated.
        return isUserAffiliatedWithDeviceLocked(userId);
    }

    private boolean hasIncompatibleAccountsOnAnyUser() {
        if (mHasIncompatibleAccounts == null) {
            // Hasn't loaded for the first time yet - assume the worst
            return true;
        }

        for (boolean hasIncompatible : mHasIncompatibleAccounts.values()) {
            if (hasIncompatible) {
                return true;
            }
        }

        return false;
    }

    private boolean hasIncompatibleAccounts(int userId) {
        return mHasIncompatibleAccounts == null ? true
                : mHasIncompatibleAccounts.getOrDefault(userId, /* default= */ false);
    }

    /**
     * Return true if a given user has any accounts that'll prevent installing a device or profile
     * owner {@code owner}.
     * - If the user has no accounts, then return false.
     * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
     * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
     *   ..._DISALLOWED, return true.
     * - Otherwise return false.
     *
     * If the caller is *not* ADB, it also returns true.  The returned value shouldn't be used
     * when the caller is not ADB.
     *
     * DO NOT CALL IT WITH THE DPMS LOCK HELD.
     */
    private boolean hasIncompatibleAccountsOrNonAdbNoLock(CallerIdentity caller,
            int userId, @Nullable ComponentName owner) {
        if (!isAdb(caller)) {
            return true;
        }
        wtfIfInLock();

        return mInjector.binderWithCleanCallingIdentity(() -> {
            AccountManager am =
                    mContext.createContextAsUser(UserHandle.of(userId), /* flags= */ 0)
                            .getSystemService(AccountManager.class);
            Account[] accounts = am.getAccounts();
            if (accounts.length == 0) {
                return false;
            }
            synchronized (getLockObject()) {
                if (owner == null || !isAdminTestOnlyLocked(owner, userId)) {
                    Slogf.w(LOG_TAG,
                            "Non test-only owner can't be installed with existing accounts.");
                    return true;
                }
            }

            boolean compatible = !hasIncompatibleAccounts(userId);
            if (compatible) {
                Slogf.w(LOG_TAG, "All accounts are compatible");
            } else {
                Slogf.e(LOG_TAG, "Found incompatible accounts");
            }
            return !compatible;
        });
    }

    ThreadPoolExecutor calculateHasIncompatibleAccountsExecutor = new ThreadPoolExecutor(
            1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());

    @Override
    public void calculateHasIncompatibleAccounts() {
        if (calculateHasIncompatibleAccountsExecutor.getQueue().size() > 1) {
            return;
        }
        new CalculateHasIncompatibleAccountsTask().executeOnExecutor(
                calculateHasIncompatibleAccountsExecutor, null);
    }

    @Nullable
    private volatile Map<Integer, Boolean> mHasIncompatibleAccounts;

    class CalculateHasIncompatibleAccountsTask extends AsyncTask<
            Void, Void, Map<Integer, Boolean>> {
        private static final String[] FEATURE_ALLOW =
                {DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED};
        private static final String[] FEATURE_DISALLOW =
                {DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED};

        @Override
        protected Map<Integer, Boolean> doInBackground(Void... args) {
            List<UserInfo> users = mUserManagerInternal.getUsers(/* excludeDying= */ true);
            Map<Integer, Boolean> results = new HashMap<>();
            for (UserInfo userInfo : users) {
                results.put(userInfo.id, userHasIncompatibleAccounts(userInfo.id));
            }

            return results;
        }

        private boolean userHasIncompatibleAccounts(int id) {
            AccountManager am = mContext.createContextAsUser(UserHandle.of(id), /* flags= */ 0)
                    .getSystemService(AccountManager.class);
            Account[] accounts = am.getAccounts();

            for (Account account : accounts) {
                if (hasAccountFeatures(am, account, FEATURE_DISALLOW)) {
                    return true;
                }
                if (!hasAccountFeatures(am, account, FEATURE_ALLOW)) {
                    return true;
                }
            }

            return false;
        }

        @Override
        protected void onPostExecute(Map<Integer, Boolean> results) {
            mHasIncompatibleAccounts = Collections.unmodifiableMap(results);

            Slogf.i(LOG_TAG, "Finished calculating hasIncompatibleAccountsTask");
        }

        private static boolean hasAccountFeatures(AccountManager am, Account account,
                String[] features) {
            try {
                return am.hasFeatures(account, features, null, null)
                        .getResult(30, TimeUnit.SECONDS);
            } catch (Exception e) {
                Slogf.w(LOG_TAG, "Failed to get account feature", e);
                return false;
            }
        }
    };

    private boolean isAdb(CallerIdentity caller) {
        return isShellUid(caller) || isRootUid(caller);
    }

    @Override
    public void setNetworkLoggingEnabled(@Nullable ComponentName admin,
            @NonNull String packageName, boolean enabled) {
        if (!mHasFeature) {
            return;
        }
        final CallerIdentity caller = getCallerIdentity(admin, packageName);
        final boolean isManagedProfileOwner = isProfileOwner(caller)
                && isManagedProfile(caller.getUserId());
        Preconditions.checkCallAuthorization((caller.hasAdminComponent()
                && (isDefaultDeviceOwner(caller) || isManagedProfileOwner))
                || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_NETWORK_LOGGING)));

        synchronized (getLockObject()) {
            if (enabled == isNetworkLoggingEnabledInternalLocked()) {
                // already in the requested state
                return;
            }
            final ActiveAdmin activeAdmin = getDeviceOrProfileOwnerAdminLocked(caller.getUserId());
            activeAdmin.isNetworkLoggingEnabled = enabled;
            if (!enabled) {
                activeAdmin.numNetworkLoggingNotifications = 0;
                activeAdmin.lastNetworkLoggingNotificationTimeMs = 0;
            }
            saveSettingsLocked(caller.getUserId());
            setNetworkLoggingActiveInternal(enabled);

            DevicePolicyEventLogger
                    .createEvent(DevicePolicyEnums.SET_NETWORK_LOGGING_ENABLED)
                    .setAdmin(caller.getPackageName())
                    .setBoolean(/* isDelegate */ admin == null)
                    .setInt(enabled ? 1 : 0)
                    .setStrings(isManagedProfileOwner
                            ? LOG_TAG_PROFILE_OWNER : LOG_TAG_DEVICE_OWNER)
                    .write();
        }
    }

    private void setNetworkLoggingActiveInternal(boolean active) {
        mInjector.binderWithCleanCallingIdentity(() -> {
            boolean shouldSendNotification = false;
            synchronized (getLockObject()) {
                if (active) {
                    if (mNetworkLogger == null) {
                        final int affectedUserId = getNetworkLoggingAffectedUser();
                        mNetworkLogger = new NetworkLogger(this,
                                mInjector.getPackageManagerInternal(),
                                affectedUserId == UserHandle.USER_SYSTEM
                                        ? UserHandle.USER_ALL : affectedUserId);
                    }
                    if (!mNetworkLogger.startNetworkLogging()) {
                        mNetworkLogger = null;
                        Slogf.wtf(LOG_TAG, "Network logging could not be started due to the logging"
                                + " service not being available yet.");
                    }
                    maybePauseDeviceWideLoggingLocked();
                    shouldSendNotification = shouldSendNetworkLoggingNotificationLocked();
                } else {
                    if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) {
                        Slogf.wtf(LOG_TAG, "Network logging could not be stopped due to the logging"
                                + " service not being available yet.");
                    }
                    mNetworkLogger = null;
                }
            }
            if (active) {
                if (shouldSendNotification) {
                    mHandler.post(() -> handleSendNetworkLoggingNotification());
                }
            } else {
                mHandler.post(() -> handleCancelNetworkLoggingNotification());
            }
        });
    }

    private @UserIdInt int getNetworkLoggingAffectedUser() {
        synchronized (getLockObject()) {
            if (mOwners.hasDeviceOwner()) {
                return mOwners.getDeviceOwnerUserId();
            } else {
                return mInjector.binderWithCleanCallingIdentity(
                        () -> getManagedUserId());
            }
        }
    }

    private ActiveAdmin getNetworkLoggingControllingAdminLocked() {
        int affectedUserId = getNetworkLoggingAffectedUser();
        if (affectedUserId < 0) {
            return null;
        }
        return getDeviceOrProfileOwnerAdminLocked(affectedUserId);
    }

    @Override
    public long forceNetworkLogs() {
        Preconditions.checkCallAuthorization(isAdb(getCallerIdentity())
                || hasCallingOrSelfPermission(permission.FORCE_DEVICE_POLICY_MANAGER_LOGS),
                "Caller must be shell or hold FORCE_DEVICE_POLICY_MANAGER_LOGS to call "
                        + "forceNetworkLogs");
        synchronized (getLockObject()) {
            if (!isNetworkLoggingEnabledInternalLocked()) {
                throw new IllegalStateException("logging is not available");
            }
            if (mNetworkLogger != null) {
                return mInjector.binderWithCleanCallingIdentity(
                        () -> mNetworkLogger.forceBatchFinalization());
            }
            return 0;
        }
    }

    /** Pauses security and network logging if there are unaffiliated users on the device */
    @GuardedBy("getLockObject()")
    private void maybePauseDeviceWideLoggingLocked() {
        if (!areAllUsersAffiliatedWithDeviceLocked()) {
            if (mOwners.hasDeviceOwner()) {
                Slogf.i(LOG_TAG, "There are unaffiliated users, network logging will be "
                        + "paused if enabled.");
                if (mNetworkLogger != null) {
                    mNetworkLogger.pause();
                }
            }
            // TODO: We need to also enable this when someone is managing using permission
            if (!isOrganizationOwnedDeviceWithManagedProfile()) {
                Slogf.i(LOG_TAG,
                        "Not org-owned managed profile device, security logging will be "
                                + "paused if enabled.");
                mSecurityLogMonitor.pause();
            }
        }
    }

    /** Resumes security and network logging (if they are enabled) if all users are affiliated */
    @GuardedBy("getLockObject()")
    private void maybeResumeDeviceWideLoggingLocked() {
        boolean allUsersAffiliated = areAllUsersAffiliatedWithDeviceLocked();
        boolean orgOwnedProfileDevice = isOrganizationOwnedDeviceWithManagedProfile();
        mInjector.binderWithCleanCallingIdentity(() -> {
            if (allUsersAffiliated || orgOwnedProfileDevice) {
                mSecurityLogMonitor.resume();
            }
            // If there is no device owner, then per-user network logging may be enabled for the
            // managed profile. In which case, all users do not need to be affiliated.
            if (allUsersAffiliated || !mOwners.hasDeviceOwner()) {
                if (mNetworkLogger != null) {
                    mNetworkLogger.resume();
                }
            }
        });
    }

    /** Deletes any security and network logs that might have been collected so far */
    @GuardedBy("getLockObject()")
    private void discardDeviceWideLogsLocked() {
        mSecurityLogMonitor.discardLogs();
        if (mNetworkLogger != null) {
            mNetworkLogger.discardLogs();
        }
        // TODO: We should discard pre-boot security logs here too, as otherwise those
        // logs (which might contain data from the user just removed) will be
        // available after next boot.
    }

    /**
     * This API is cached: invalidate with invalidateBinderCaches().
     */
    @Override
    public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin,
            @NonNull String packageName) {
        if (!mHasFeature) {
            return false;
        }
        final CallerIdentity caller = getCallerIdentity(admin, packageName);
        Preconditions.checkCallAuthorization((caller.hasAdminComponent()
                &&  (isDefaultDeviceOwner(caller)
                || (isProfileOwner(caller) && isManagedProfile(caller.getUserId()))))
                || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_NETWORK_LOGGING))
                || hasCallingOrSelfPermission(permission.MANAGE_USERS));

        synchronized (getLockObject()) {
            return isNetworkLoggingEnabledInternalLocked();
        }
    }

    private boolean isNetworkLoggingEnabledInternalLocked() {
        ActiveAdmin activeAdmin = getNetworkLoggingControllingAdminLocked();
        return (activeAdmin != null) && activeAdmin.isNetworkLoggingEnabled;
    }

    /*
     * A maximum of 1200 events are returned, and the total marshalled size is in the order of
     * 100kB, so returning a List instead of ParceledListSlice is acceptable.
     * Ideally this would be done with ParceledList, however it only supports homogeneous types.
     *
     * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH
     */
    @Override
    public List<NetworkEvent> retrieveNetworkLogs(@Nullable ComponentName admin,
            @NonNull String packageName, long batchToken) {
        if (!mHasFeature) {
            return null;
        }
        final CallerIdentity caller = getCallerIdentity(admin, packageName);
        final boolean isManagedProfileOwner = isProfileOwner(caller)
                && isManagedProfile(caller.getUserId());
        Preconditions.checkCallAuthorization((caller.hasAdminComponent()
                &&  (isDefaultDeviceOwner(caller) || isManagedProfileOwner))
                || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_NETWORK_LOGGING)));
        if (mOwners.hasDeviceOwner()) {
            checkAllUsersAreAffiliatedWithDevice();
        }

        synchronized (getLockObject()) {
            if (mNetworkLogger == null || !isNetworkLoggingEnabledInternalLocked()) {
                return null;
            }
            DevicePolicyEventLogger
                    .createEvent(DevicePolicyEnums.RETRIEVE_NETWORK_LOGS)
                    .setAdmin(caller.getPackageName())
                    .setBoolean(/* isDelegate */ admin == null)
                    .setStrings(isManagedProfileOwner
                            ? LOG_TAG_PROFILE_OWNER : LOG_TAG_DEVICE_OWNER)
                    .write();

            final long currentTime = System.currentTimeMillis();
            DevicePolicyData policyData = getUserData(caller.getUserId());
            if (currentTime > policyData.mLastNetworkLogsRetrievalTime) {
                policyData.mLastNetworkLogsRetrievalTime = currentTime;
                saveSettingsLocked(caller.getUserId());
            }
            return mNetworkLogger.retrieveLogs(batchToken);
        }
    }

    /**
     * Returns whether it's time to post another network logging notification. When returning true,
     * this method has the side-effect of updating the recorded last network logging notification
     * time to now.
     */
    private boolean shouldSendNetworkLoggingNotificationLocked() {
        ensureLocked();
        // Send a network logging notification if the admin is a device owner, not profile owner.
        final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
        if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) {
            return false;
        }
        if (deviceOwner.numNetworkLoggingNotifications
                >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
            return false;
        }
        final long now = System.currentTimeMillis();
        if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) {
            return false;
        }
        deviceOwner.numNetworkLoggingNotifications++;
        if (deviceOwner.numNetworkLoggingNotifications
                >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
            deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
        } else {
            deviceOwner.lastNetworkLoggingNotificationTimeMs = now;
        }
        saveSettingsLocked(deviceOwner.getUserHandle().getIdentifier());
        return true;
    }

    private void handleSendNetworkLoggingNotification() {
        final PackageManagerInternal pm = mInjector.getPackageManagerInternal();
        final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG);
        intent.setPackage(pm.getSystemUiServiceComponent().getPackageName());
        mNetworkLoggingNotificationUserId = getCurrentForegroundUserId();
        // Simple notification clicks are immutable
        final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent,
                PendingIntent.FLAG_IMMUTABLE, UserHandle.CURRENT);

        final String title = getNetworkLoggingTitle();
        final String text = getNetworkLoggingText();
        Notification notification =
                new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
                .setSmallIcon(R.drawable.ic_info_outline)
                .setContentTitle(title)
                .setContentText(text)
                .setTicker(title)
                .setShowWhen(true)
                .setContentIntent(pendingIntent)
                .setStyle(new Notification.BigTextStyle().bigText(text))
                .build();
        Slogf.i(LOG_TAG, "Sending network logging notification to user %d",
                mNetworkLoggingNotificationUserId);
        mInjector.getNotificationManager().notifyAsUser(/* tag= */ null,
                SystemMessage.NOTE_NETWORK_LOGGING, notification,
                UserHandle.of(mNetworkLoggingNotificationUserId));
    }

    private String getNetworkLoggingTitle() {
        return getUpdatableString(
                NETWORK_LOGGING_TITLE, R.string.network_logging_notification_title);
    }

    private String getNetworkLoggingText() {
        return getUpdatableString(
                NETWORK_LOGGING_MESSAGE, R.string.network_logging_notification_text);
    }

    private void handleCancelNetworkLoggingNotification() {
        if (mNetworkLoggingNotificationUserId == UserHandle.USER_NULL) {
            // Happens when setNetworkLoggingActive(false) is called before called with true
            Slogf.d(LOG_TAG, "Not cancelling network logging notification for USER_NULL");
            return;
        }

        Slogf.i(LOG_TAG, "Cancelling network logging notification for user %d",
                mNetworkLoggingNotificationUserId);
        mInjector.getNotificationManager().cancelAsUser(/* tag= */ null,
                SystemMessage.NOTE_NETWORK_LOGGING,
                UserHandle.of(mNetworkLoggingNotificationUserId));
        mNetworkLoggingNotificationUserId = UserHandle.USER_NULL;
    }

    /**
     * Return the package name of owner in a given user.
     */
    private String getOwnerPackageNameForUserLocked(int userId) {
        return mOwners.getDeviceOwnerUserId() == userId
                ? mOwners.getDeviceOwnerPackageName()
                : mOwners.getProfileOwnerPackage(userId);
    }

    /**
     * @param rawIntent Original service intent specified by caller. It must be explicit.
     * @param expectedPackageName The expected package name of the resolved service.
     * @return Intent that have component explicitly set. {@code null} if no service is resolved
     *     with the given intent.
     * @throws SecurityException if the intent is resolved to an invalid service.
     */
    private Intent createCrossUserServiceIntent(
            @NonNull Intent rawIntent, @NonNull String expectedPackageName,
            @UserIdInt int targetUserId) throws RemoteException, SecurityException {
        ResolveInfo info = mIPackageManager.resolveService(
                rawIntent,
                rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
                0,  // flags
                targetUserId);
        if (info == null || info.serviceInfo == null) {
            Slogf.e(LOG_TAG, "Fail to look up the service: %s or user %d is not running", rawIntent,
                    targetUserId);
            return null;
        }
        if (!expectedPackageName.equals(info.serviceInfo.packageName)) {
            throw new SecurityException("Only allow to bind service in " + expectedPackageName);
        }
        // STOPSHIP(b/37624960): Remove info.serviceInfo.exported before release.
        if (info.serviceInfo.exported && !BIND_DEVICE_ADMIN.equals(info.serviceInfo.permission)) {
            throw new SecurityException(
                    "Service must be protected by BIND_DEVICE_ADMIN permission");
        }
        // It is the system server to bind the service, it would be extremely dangerous if it
        // can be exploited to bind any service. Set the component explicitly to make sure we
        // do not bind anything accidentally.
        rawIntent.setComponent(info.serviceInfo.getComponentName());
        return rawIntent;
    }

    @Override
    public long getLastSecurityLogRetrievalTime() {
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || canManageUsers(caller));
        return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime;
     }

    @Override
    public long getLastBugReportRequestTime() {
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || canManageUsers(caller));
        return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime;
     }

    @Override
    public long getLastNetworkLogRetrievalTime() {
        final CallerIdentity caller = getCallerIdentity();

        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
                || (isProfileOwner(caller) && isManagedProfile(caller.getUserId()))
                || canManageUsers(caller));
        final int affectedUserId = getNetworkLoggingAffectedUser();
        return affectedUserId >= 0 ? getUserData(affectedUserId).mLastNetworkLogsRetrievalTime : -1;
    }

    @Override
    public boolean setResetPasswordToken(ComponentName admin, String callerPackageName,
            byte[] token) {
        if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
            return false;
        }
        if (token == null || token.length < 32) {
            throw new IllegalArgumentException("token must be at least 32-byte long");
        }
        CallerIdentity caller;
        if (isUnicornFlagEnabled()) {
            caller = getCallerIdentity(admin, callerPackageName);
        } else {
            caller = getCallerIdentity(admin);
        }
        final int userId = caller.getUserId();

        if (isUnicornFlagEnabled()) {
            EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                    admin,
                    MANAGE_DEVICE_POLICY_RESET_PASSWORD,
                    caller.getPackageName(),
                    userId);
            Long currentTokenHandle = mDevicePolicyEngine.getLocalPolicySetByAdmin(
                    PolicyDefinition.RESET_PASSWORD_TOKEN,
                    enforcingAdmin,
                    userId);
            long tokenHandle = addEscrowToken(
                    token, currentTokenHandle == null ? 0 : currentTokenHandle, userId);
            if (tokenHandle == 0) {
                return false;
            }
            mDevicePolicyEngine.setLocalPolicy(
                    PolicyDefinition.RESET_PASSWORD_TOKEN,
                    enforcingAdmin,
                    new LongPolicyValue(tokenHandle),
                    userId);
            return true;
        } else {
            Objects.requireNonNull(admin, "ComponentName is null");
            Preconditions.checkCallAuthorization(
                    isProfileOwner(caller) || isDefaultDeviceOwner(caller));
            synchronized (getLockObject()) {
                DevicePolicyData policy = getUserData(userId);
                policy.mPasswordTokenHandle = addEscrowToken(
                        token, policy.mPasswordTokenHandle, userId);
                saveSettingsLocked(userId);
                return policy.mPasswordTokenHandle != 0;
            }
        }
    }

    private long addEscrowToken(byte[] token, long currentPasswordTokenHandle, int userId) {
        resetEscrowToken(currentPasswordTokenHandle, userId);
        return mInjector.binderWithCleanCallingIdentity(() -> mLockPatternUtils.addEscrowToken(
                token, userId, /* EscrowTokenStateChangeCallback= */ null));
    }

    private boolean resetEscrowToken(long tokenHandle, int userId) {
        return mInjector.binderWithCleanCallingIdentity(() -> {
            if (tokenHandle != 0) {
                return mLockPatternUtils.removeEscrowToken(tokenHandle, userId);
            }
            return false;
        });
    }

    @Override
    public boolean clearResetPasswordToken(ComponentName admin, String callerPackageName) {
        if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
            return false;
        }
        CallerIdentity caller;
        if (isUnicornFlagEnabled()) {
            caller = getCallerIdentity(admin, callerPackageName);
        } else {
            caller = getCallerIdentity(admin);
        }
        final int userId = caller.getUserId();
        boolean result = false;

        if (isUnicornFlagEnabled()) {
            EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                    admin,
                    MANAGE_DEVICE_POLICY_RESET_PASSWORD,
                    caller.getPackageName(),
                    userId);
            Long currentTokenHandle = mDevicePolicyEngine.getLocalPolicySetByAdmin(
                    PolicyDefinition.RESET_PASSWORD_TOKEN,
                    enforcingAdmin,
                    userId);
            if (currentTokenHandle != null) {
                result = resetEscrowToken(currentTokenHandle, userId);
                mDevicePolicyEngine.removeLocalPolicy(
                        PolicyDefinition.RESET_PASSWORD_TOKEN,
                        enforcingAdmin,
                        userId);
            }
        } else {
            Objects.requireNonNull(admin, "ComponentName is null");
            Preconditions.checkCallAuthorization(
                    isProfileOwner(caller) || isDefaultDeviceOwner(caller));
            synchronized (getLockObject()) {
                DevicePolicyData policy = getUserData(userId);
                if (policy.mPasswordTokenHandle != 0) {
                    result = resetEscrowToken(policy.mPasswordTokenHandle, userId);
                    policy.mPasswordTokenHandle = 0;
                    saveSettingsLocked(userId);
                }
            }
        }
        return result;
    }

    @Override
    public boolean isResetPasswordTokenActive(ComponentName admin, String callerPackageName) {
        if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
            return false;
        }
        CallerIdentity caller;
        if (isUnicornFlagEnabled()) {
            caller = getCallerIdentity(admin, callerPackageName);
        } else {
            caller = getCallerIdentity(admin);
        }
        int userId = caller.getUserId();

        if (isUnicornFlagEnabled()) {
            EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                    admin,
                    MANAGE_DEVICE_POLICY_RESET_PASSWORD,
                    caller.getPackageName(),
                    userId);
            Long currentTokenHandle = mDevicePolicyEngine.getLocalPolicySetByAdmin(
                    PolicyDefinition.RESET_PASSWORD_TOKEN,
                    enforcingAdmin,
                    userId);
            return isResetPasswordTokenActiveForUserLocked(
                    currentTokenHandle == null ? 0 : currentTokenHandle, userId);
        } else {
            Objects.requireNonNull(admin, "ComponentName is null");
            Preconditions.checkCallAuthorization(
                    isProfileOwner(caller) || isDefaultDeviceOwner(caller));
            synchronized (getLockObject()) {
                DevicePolicyData policy = getUserData(userId);
                return isResetPasswordTokenActiveForUserLocked(policy.mPasswordTokenHandle, userId);
            }
        }
    }

    private boolean isResetPasswordTokenActiveForUserLocked(
            long passwordTokenHandle, int userHandle) {
        if (passwordTokenHandle != 0) {
            return mInjector.binderWithCleanCallingIdentity(() ->
                    mLockPatternUtils.isEscrowTokenActive(passwordTokenHandle, userHandle));
        }
        return false;
    }

    @Override
    public boolean resetPasswordWithToken(ComponentName admin, String callerPackageName,
            String passwordOrNull, byte[] token,
            int flags) {
        if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
            return false;
        }
        Objects.requireNonNull(token);

        CallerIdentity caller;
        if (isUnicornFlagEnabled()) {
            caller = getCallerIdentity(admin, callerPackageName);
        } else {
            caller = getCallerIdentity(admin);
        }

        int userId = caller.getUserId();
        boolean result = false;
        final String password = passwordOrNull != null ? passwordOrNull : "";

        if (isUnicornFlagEnabled()) {
            EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                    admin,
                    MANAGE_DEVICE_POLICY_RESET_PASSWORD,
                    caller.getPackageName(),
                    userId);
            Long currentTokenHandle = mDevicePolicyEngine.getLocalPolicySetByAdmin(
                    PolicyDefinition.RESET_PASSWORD_TOKEN,
                    enforcingAdmin,
                    userId);
            if (currentTokenHandle != null && currentTokenHandle != 0) {
                result = resetPasswordInternal(password, currentTokenHandle, token, flags, caller);
            } else {
                Slogf.w(LOG_TAG, "No saved token handle");
            }
        } else {
            Objects.requireNonNull(admin, "ComponentName is null");
            Preconditions.checkCallAuthorization(
                    isProfileOwner(caller) || isDefaultDeviceOwner(caller));
            synchronized (getLockObject()) {
                DevicePolicyData policy = getUserData(userId);
                if (policy.mPasswordTokenHandle != 0) {
                    result = resetPasswordInternal(
                            password, policy.mPasswordTokenHandle, token, flags, caller);
                } else {
                    Slogf.w(LOG_TAG, "No saved token handle");
                }
            }
        }

        if (result) {
            if (isUnicornFlagEnabled()) {
                DevicePolicyEventLogger
                        .createEvent(DevicePolicyEnums.RESET_PASSWORD_WITH_TOKEN)
                        .setAdmin(callerPackageName)
                        .write();
            } else {
                DevicePolicyEventLogger
                        .createEvent(DevicePolicyEnums.RESET_PASSWORD_WITH_TOKEN)
                        .setAdmin(caller.getComponentName())
                        .write();
            }
        }
        return result;
    }

    @Override
    public boolean isCurrentInputMethodSetByOwner() {
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
                || isProfileOwner(caller) || canQueryAdminPolicy(caller) || isSystemUid(caller),
                "Only profile owner, device owner, a caller with QUERY_ADMIN_POLICY "
                        + "permission or system may call this method.");
        return getUserData(caller.getUserId()).mCurrentInputMethodSet;
    }

    @Override
    public StringParceledListSlice getOwnerInstalledCaCerts(@NonNull UserHandle user) {
        final int userId = user.getIdentifier();
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(
                (isProfileOwner(caller) || isDefaultDeviceOwner(caller) || canQueryAdminPolicy(
                        caller)) && hasFullCrossUsersPermission(caller, userId));

        synchronized (getLockObject()) {
            return new StringParceledListSlice(
                    new ArrayList<>(getUserData(userId).mOwnerInstalledCaCerts));
        }
    }

    @Override
    public void clearApplicationUserData(ComponentName admin, String packageName,
            IPackageDataObserver callback) {
        Objects.requireNonNull(admin, "ComponentName is null");
        Objects.requireNonNull(packageName, "packageName is null");
        Objects.requireNonNull(callback, "callback is null");

        final CallerIdentity caller = getCallerIdentity(admin);
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || isProfileOwner(caller));
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_CLEAR_APPLICATION_USER_DATA);

        long ident = mInjector.binderClearCallingIdentity();
        try {
            ActivityManager.getService().clearApplicationUserData(packageName, false, callback,
                    caller.getUserId());
        } catch(RemoteException re) {
            // Same process, should not happen.
        } catch (SecurityException se) {
            // This can happen e.g. for device admin packages, do not throw out the exception,
            // because callers have no means to know beforehand for which packages this might
            // happen. If so, we send back that removal failed.
            Slogf.w(LOG_TAG, "Not allowed to clear application user data for package "
                    + packageName, se);
            try {
                callback.onRemoveCompleted(packageName, false);
            } catch (RemoteException re) {
                // Caller is no longer available, ignore
            }
        } finally {
            mInjector.binderRestoreCallingIdentity(ident);
        }
    }

    @Override
    public void setLogoutEnabled(ComponentName admin, boolean enabled) {
        if (!mHasFeature) {
            return;
        }
        Objects.requireNonNull(admin, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(admin);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_LOGOUT_ENABLED);

        synchronized (getLockObject()) {
            ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
            if (deviceOwner.isLogoutEnabled == enabled) {
                // already in the requested state
                return;
            }
            deviceOwner.isLogoutEnabled = enabled;
            saveSettingsLocked(caller.getUserId());
        }
    }

    @Override
    public boolean isLogoutEnabled() {
        if (!mHasFeature) {
            return false;
        }
        synchronized (getLockObject()) {
            ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
            return (deviceOwner != null) && deviceOwner.isLogoutEnabled;
        }
    }

    @Override
    public List<String> getDisallowedSystemApps(ComponentName admin, int userId,
            String provisioningAction) throws RemoteException {
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));

        return new ArrayList<>(
                mOverlayPackagesProvider.getNonRequiredApps(admin, userId, provisioningAction));
    }

    @Override
    public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target,
            @Nullable PersistableBundle bundle) {
        if (!mHasFeature) {
            return;
        }
        Objects.requireNonNull(admin, "ComponentName is null");
        Objects.requireNonNull(target, "Target cannot be null.");
        Preconditions.checkArgument(!admin.equals(target),
                "Provided administrator and target are the same object.");
        Preconditions.checkArgument(!admin.getPackageName().equals(target.getPackageName()),
                "Provided administrator and target have the same package name.");
        if (bundle != null) {
            enforceMaxStringLength(bundle, "bundle");
        }

        final CallerIdentity caller = getCallerIdentity(admin);
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || isProfileOwner(caller));

        final int callingUserId = caller.getUserId();
        final DevicePolicyData policy = getUserData(callingUserId);
        final DeviceAdminInfo incomingDeviceInfo = findAdmin(target, callingUserId,
                /* throwForMissingPermission= */ true);
        checkActiveAdminPrecondition(target, incomingDeviceInfo, policy);
        Preconditions.checkArgument(incomingDeviceInfo.supportsTransferOwnership(),
                "Provided target does not support ownership transfer.");

        final long id = mInjector.binderClearCallingIdentity();
        String ownerType = null;
        try {
            synchronized (getLockObject()) {
                /*
                * We must ensure the whole process is atomic to prevent the device from ending up
                * in an invalid state (e.g. no active admin). This could happen if the device
                * is rebooted or work mode is turned off mid-transfer.
                * In order to guarantee atomicity, we:
                *
                * 1. Save an atomic journal file describing the transfer process
                * 2. Perform the transfer itself
                * 3. Delete the journal file
                *
                * That way if the journal file exists on device boot, we know that the transfer
                * must be reverted back to the original administrator. This logic is implemented in
                * revertTransferOwnershipIfNecessaryLocked.
                * */
                if (bundle == null) {
                    bundle = new PersistableBundle();
                }
                if (isProfileOwner(caller)) {
                    ownerType = ADMIN_TYPE_PROFILE_OWNER;
                    prepareTransfer(admin, target, bundle, callingUserId,
                            ADMIN_TYPE_PROFILE_OWNER);
                    transferProfileOwnershipLocked(admin, target, callingUserId);
                    sendProfileOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE,
                            getTransferOwnershipAdminExtras(bundle), callingUserId);
                    postTransfer(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, callingUserId);
                    if (isUserAffiliatedWithDeviceLocked(callingUserId)) {
                        notifyAffiliatedProfileTransferOwnershipComplete(callingUserId);
                    }
                } else if (isDefaultDeviceOwner(caller)) {
                    ownerType = ADMIN_TYPE_DEVICE_OWNER;
                    prepareTransfer(admin, target, bundle, callingUserId,
                            ADMIN_TYPE_DEVICE_OWNER);
                    transferDeviceOwnershipLocked(admin, target, callingUserId);
                    sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE,
                            getTransferOwnershipAdminExtras(bundle));
                    postTransfer(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, callingUserId);
                }
            }
        } finally {
            mInjector.binderRestoreCallingIdentity(id);
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.TRANSFER_OWNERSHIP)
                .setAdmin(admin)
                .setStrings(target.getPackageName(), ownerType)
                .write();
    }

    private void prepareTransfer(ComponentName admin, ComponentName target,
            PersistableBundle bundle, int callingUserId, String adminType) {
        saveTransferOwnershipBundleLocked(bundle, callingUserId);
        mTransferOwnershipMetadataManager.saveMetadataFile(
                new TransferOwnershipMetadataManager.Metadata(admin, target,
                        callingUserId, adminType));
    }

    private void postTransfer(String broadcast, int callingUserId) {
        deleteTransferOwnershipMetadataFileLocked();
        sendOwnerChangedBroadcast(broadcast, callingUserId);
    }

    private void notifyAffiliatedProfileTransferOwnershipComplete(int callingUserId) {
        final Bundle extras = new Bundle();
        extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(callingUserId));
        sendDeviceOwnerCommand(
                DeviceAdminReceiver.ACTION_AFFILIATED_PROFILE_TRANSFER_OWNERSHIP_COMPLETE, extras);
    }

    /**
     * Transfers the profile owner for user with id profileOwnerUserId from admin to target.
     */
    private void transferProfileOwnershipLocked(ComponentName admin, ComponentName target,
            int profileOwnerUserId) {
        transferActiveAdminUncheckedLocked(target, admin, profileOwnerUserId);
        mOwners.transferProfileOwner(target, profileOwnerUserId);
        Slogf.i(LOG_TAG, "Profile owner set: " + target + " on user " + profileOwnerUserId);
        mOwners.writeProfileOwner(profileOwnerUserId);
        mDeviceAdminServiceController.startServiceForAdmin(
                target.getPackageName(), profileOwnerUserId, "transfer-profile-owner");
    }

    /**
     * Transfers the device owner for user with id userId from admin to target.
     */
    private void transferDeviceOwnershipLocked(ComponentName admin, ComponentName target, int userId) {
        transferActiveAdminUncheckedLocked(target, admin, userId);
        mOwners.transferDeviceOwnership(target);
        Slogf.i(LOG_TAG, "Device owner set: " + target + " on user " + userId);
        mOwners.writeDeviceOwner();
        mDeviceAdminServiceController.startServiceForAdmin(
                target.getPackageName(), userId, "transfer-device-owner");
    }

    private Bundle getTransferOwnershipAdminExtras(PersistableBundle bundle) {
        Bundle extras = new Bundle();
        if (bundle != null) {
            extras.putParcelable(EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE, bundle);
        }
        return extras;
    }

    @Override
    public void setStartUserSessionMessage(
            ComponentName admin, CharSequence startUserSessionMessage) {
        if (!mHasFeature) {
            return;
        }
        Objects.requireNonNull(admin, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(admin);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));

        final String startUserSessionMessageString =
                startUserSessionMessage != null ? startUserSessionMessage.toString() : null;

        synchronized (getLockObject()) {
            final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
            if (TextUtils.equals(deviceOwner.startUserSessionMessage, startUserSessionMessage)) {
                return;
            }
            deviceOwner.startUserSessionMessage = startUserSessionMessageString;
            saveSettingsLocked(caller.getUserId());
        }

        mInjector.getActivityManagerInternal()
                .setSwitchingFromSystemUserMessage(startUserSessionMessageString);
    }

    @Override
    public void setEndUserSessionMessage(ComponentName admin, CharSequence endUserSessionMessage) {
        if (!mHasFeature) {
            return;
        }
        Objects.requireNonNull(admin, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(admin);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));

        final String endUserSessionMessageString =
                endUserSessionMessage != null ? endUserSessionMessage.toString() : null;

        synchronized (getLockObject()) {
            final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
            if (TextUtils.equals(deviceOwner.endUserSessionMessage, endUserSessionMessage)) {
                return;
            }
            deviceOwner.endUserSessionMessage = endUserSessionMessageString;
            saveSettingsLocked(caller.getUserId());
        }

        mInjector.getActivityManagerInternal()
                .setSwitchingToSystemUserMessage(endUserSessionMessageString);
    }

    @Override
    public String getStartUserSessionMessage(ComponentName admin) {
        if (!mHasFeature) {
            return null;
        }
        Objects.requireNonNull(admin, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(admin);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));

        synchronized (getLockObject()) {
            final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
            return deviceOwner.startUserSessionMessage;
        }
    }

    @Override
    public String getEndUserSessionMessage(ComponentName admin) {
        if (!mHasFeature) {
            return null;
        }
        Objects.requireNonNull(admin, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(admin);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));

        synchronized (getLockObject()) {
            final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
            return deviceOwner.endUserSessionMessage;
        }
    }

    private void deleteTransferOwnershipMetadataFileLocked() {
        mTransferOwnershipMetadataManager.deleteMetadataFile();
    }

    @Override
    @Nullable
    public PersistableBundle getTransferOwnershipBundle() {
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(
                isProfileOwner(caller) || isDefaultDeviceOwner(caller));

        synchronized (getLockObject()) {
            final int callingUserId = caller.getUserId();
            final File bundleFile = new File(
                    mPathProvider.getUserSystemDirectory(callingUserId),
                    TRANSFER_OWNERSHIP_PARAMETERS_XML);
            if (!bundleFile.exists()) {
                return null;
            }
            try (FileInputStream stream = new FileInputStream(bundleFile)) {
                TypedXmlPullParser parser = Xml.resolvePullParser(stream);
                parser.next();
                return PersistableBundle.restoreFromXml(parser);
            } catch (IOException | XmlPullParserException | IllegalArgumentException e) {
                Slogf.e(LOG_TAG, "Caught exception while trying to load the "
                        + "owner transfer parameters from file " + bundleFile, e);
                return null;
            }
        }
    }

    @Override
    public int addOverrideApn(@NonNull ComponentName who, @NonNull ApnSetting apnSetting) {
        if (!mHasFeature || !mHasTelephonyFeature) {
            return -1;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        Objects.requireNonNull(apnSetting, "ApnSetting is null in addOverrideApn");
        final CallerIdentity caller = getCallerIdentity(who);
        if (apnSetting.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) {
            Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
                    || isManagedProfileOwner(caller));
        } else {
            Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
        }

        TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
        if (tm != null) {
            return mInjector.binderWithCleanCallingIdentity(
                    () -> tm.addDevicePolicyOverrideApn(mContext, apnSetting));
        } else {
            Slogf.w(LOG_TAG, "TelephonyManager is null when trying to add override apn");
            return INVALID_APN_ID;
        }
    }

    @Override
    public boolean updateOverrideApn(@NonNull ComponentName who, int apnId,
            @NonNull ApnSetting apnSetting) {
        if (!mHasFeature || !mHasTelephonyFeature) {
            return false;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        Objects.requireNonNull(apnSetting, "ApnSetting is null in updateOverrideApn");
        final CallerIdentity caller = getCallerIdentity(who);
        ApnSetting apn = getApnSetting(apnId);
        if (apn != null && apn.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE
                && apnSetting.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) {
            Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
                    || isManagedProfileOwner(caller));
        } else {
            Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
        }

        if (apnId < 0) {
            return false;
        }
        TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
        if (tm != null) {
            return mInjector.binderWithCleanCallingIdentity(
                    () -> tm.modifyDevicePolicyOverrideApn(mContext, apnId, apnSetting));
        } else {
            Slogf.w(LOG_TAG, "TelephonyManager is null when trying to modify override apn");
            return false;
        }
    }

    @Override
    public boolean removeOverrideApn(@NonNull ComponentName who, int apnId) {
        if (!mHasFeature || !mHasTelephonyFeature) {
            return false;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        ApnSetting apn = getApnSetting(apnId);
        if (apn != null && apn.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) {
            Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
                    || isManagedProfileOwner(caller));
        } else {
            Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
        }
        return removeOverrideApnUnchecked(apnId);
    }

    private boolean removeOverrideApnUnchecked(int apnId) {
        if(apnId < 0) {
            return false;
        }
        int numDeleted = mInjector.binderWithCleanCallingIdentity(
                () -> mContext.getContentResolver().delete(
                        Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)), null, null));
        return numDeleted > 0;
    }

    private ApnSetting getApnSetting(int apnId) {
        if (apnId < 0) {
            return null;
        }
        ApnSetting apnSetting = null;
        Cursor cursor = mInjector.binderWithCleanCallingIdentity(
                () -> mContext.getContentResolver().query(
                        Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)), null, null, null,
                        Telephony.Carriers.DEFAULT_SORT_ORDER));
        if (cursor != null) {
            while (cursor.moveToNext()) {
                apnSetting = ApnSetting.makeApnSetting(cursor);
                if (apnSetting != null) {
                    break;
                }
            }
            cursor.close();
        }
        return apnSetting;
    }

    @Override
    public List<ApnSetting> getOverrideApns(@NonNull ComponentName who) {
        if (!mHasFeature || !mHasTelephonyFeature) {
            return Collections.emptyList();
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
                || isManagedProfileOwner(caller));
        List<ApnSetting> apnSettings = getOverrideApnsUnchecked();
        if (isProfileOwner(caller)) {
            List<ApnSetting> apnSettingList = new ArrayList<>();
            for (ApnSetting apnSetting : apnSettings) {
                if (apnSetting.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) {
                    apnSettingList.add(apnSetting);
                }
            }
            return apnSettingList;
        } else {
            return apnSettings;
        }
    }

    private List<ApnSetting> getOverrideApnsUnchecked() {
        TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
        if (tm != null) {
            return mInjector.binderWithCleanCallingIdentity(
                    () -> tm.getDevicePolicyOverrideApns(mContext));
        }
        Slogf.w(LOG_TAG, "TelephonyManager is null when trying to get override apns");
        return Collections.emptyList();
    }

    @Override
    public void setOverrideApnsEnabled(@NonNull ComponentName who, boolean enabled) {
        if (!mHasFeature || !mHasTelephonyFeature) {
            return;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_OVERRIDE_APNS_ENABLED);

        setOverrideApnsEnabledUnchecked(enabled);
    }

    private void setOverrideApnsEnabledUnchecked(boolean enabled) {
        ContentValues value = new ContentValues();
        value.put(ENFORCE_KEY, enabled);
        mInjector.binderWithCleanCallingIdentity(() -> mContext.getContentResolver().update(
                    ENFORCE_MANAGED_URI, value, null, null));
    }

    @Override
    public boolean isOverrideApnEnabled(@NonNull ComponentName who) {
        if (!mHasFeature || !mHasTelephonyFeature) {
            return false;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));

        Cursor enforceCursor = mInjector.binderWithCleanCallingIdentity(
                () -> mContext.getContentResolver().query(
                        ENFORCE_MANAGED_URI, null, null, null, null));

        if (enforceCursor == null) {
            return false;
        }
        try {
            if (enforceCursor.moveToFirst()) {
                return enforceCursor.getInt(enforceCursor.getColumnIndex(ENFORCE_KEY)) == 1;
            }
        } catch (IllegalArgumentException e) {
            Slogf.e(LOG_TAG, "Cursor returned from ENFORCE_MANAGED_URI doesn't contain "
                    + "correct info.", e);
        } finally {
            enforceCursor.close();
        }
        return false;
    }

    @VisibleForTesting
    void saveTransferOwnershipBundleLocked(PersistableBundle bundle, int userId) {
        final File parametersFile = new File(
                mPathProvider.getUserSystemDirectory(userId),
                TRANSFER_OWNERSHIP_PARAMETERS_XML);
        final AtomicFile atomicFile = new AtomicFile(parametersFile);
        FileOutputStream stream = null;
        try {
            stream = atomicFile.startWrite();
            final TypedXmlSerializer serializer = Xml.resolveSerializer(stream);
            serializer.startDocument(null, true);
            serializer.startTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE);
            bundle.saveToXml(serializer);
            serializer.endTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE);
            serializer.endDocument();
            atomicFile.finishWrite(stream);
        } catch (IOException | XmlPullParserException e) {
            Slogf.e(LOG_TAG, "Caught exception while trying to save the "
                    + "owner transfer parameters to file " + parametersFile, e);
            parametersFile.delete();
            atomicFile.failWrite(stream);
        }
    }

    void deleteTransferOwnershipBundleLocked(int userId) {
        final File parametersFile = new File(mPathProvider.getUserSystemDirectory(userId),
                TRANSFER_OWNERSHIP_PARAMETERS_XML);
        parametersFile.delete();
    }

    private void logPasswordQualitySetIfSecurityLogEnabled(ComponentName who, int userId,
            boolean parent, PasswordPolicy passwordPolicy) {
        if (SecurityLog.isLoggingEnabled()) {
            final int affectedUserId = parent ? getProfileParentId(userId) : userId;
            SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_COMPLEXITY_SET, who.getPackageName(),
                    userId, affectedUserId, passwordPolicy.length, passwordPolicy.quality,
                    passwordPolicy.letters, passwordPolicy.nonLetter, passwordPolicy.numeric,
                    passwordPolicy.upperCase, passwordPolicy.lowerCase, passwordPolicy.symbols);
        }
    }

    private static String getManagedProvisioningPackage(Context context) {
        return context.getResources().getString(R.string.config_managed_provisioning_package);
    }

    private void putPrivateDnsSettings(int mode, @Nullable String host) {
        // Set Private DNS settings using system permissions, as apps cannot write
        // to global settings.
        mInjector.binderWithCleanCallingIdentity(() -> {
            ConnectivitySettingsManager.setPrivateDnsMode(mContext, mode);
            ConnectivitySettingsManager.setPrivateDnsHostname(mContext, host);
        });
    }

    @Override
    public int setGlobalPrivateDns(@NonNull ComponentName who, int mode, String privateDnsHost) {
        if (!mHasFeature) {
            return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
        checkAllUsersAreAffiliatedWithDevice();
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_GLOBAL_PRIVATE_DNS);

        switch (mode) {
            case PRIVATE_DNS_MODE_OPPORTUNISTIC:
                if (!TextUtils.isEmpty(privateDnsHost)) {
                    throw new IllegalArgumentException(
                            "Host provided for opportunistic mode, but is not needed.");
                }
                putPrivateDnsSettings(ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC,
                        null);
                return PRIVATE_DNS_SET_NO_ERROR;
            case PRIVATE_DNS_MODE_PROVIDER_HOSTNAME:
                if (TextUtils.isEmpty(privateDnsHost)
                        || !NetworkUtilsInternal.isWeaklyValidatedHostname(privateDnsHost)) {
                    throw new IllegalArgumentException(
                            String.format("Provided hostname %s is not valid", privateDnsHost));
                }

                // Connectivity check will have been performed in the DevicePolicyManager before
                // the call here.
                putPrivateDnsSettings(
                        ConnectivitySettingsManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME,
                        privateDnsHost);
                return PRIVATE_DNS_SET_NO_ERROR;
            default:
                throw new IllegalArgumentException(
                        String.format("Provided mode, %d, is not a valid mode.", mode));
        }
    }

    @Override
    public int getGlobalPrivateDnsMode(@NonNull ComponentName who) {
        if (!mHasFeature) {
            return PRIVATE_DNS_MODE_UNKNOWN;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));

        final int currentMode = ConnectivitySettingsManager.getPrivateDnsMode(mContext);
        switch (currentMode) {
            case ConnectivitySettingsManager.PRIVATE_DNS_MODE_OFF:
                return PRIVATE_DNS_MODE_OFF;
            case ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC:
                return PRIVATE_DNS_MODE_OPPORTUNISTIC;
            case ConnectivitySettingsManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME:
                return PRIVATE_DNS_MODE_PROVIDER_HOSTNAME;
        }

        return PRIVATE_DNS_MODE_UNKNOWN;
    }

    @Override
    public String getGlobalPrivateDnsHost(@NonNull ComponentName who) {
        if (!mHasFeature) {
            return null;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
        return mInjector.settingsGlobalGetString(PRIVATE_DNS_SPECIFIER);
    }

    @Override
    public void installUpdateFromFile(ComponentName admin, String callerPackageName,
            ParcelFileDescriptor updateFileDescriptor, StartInstallingUpdateCallback callback) {
        if (!isPermissionCheckFlagEnabled()) {
            Objects.requireNonNull(admin, "ComponentName is null");
        }

        CallerIdentity caller;
        if (isPermissionCheckFlagEnabled()) {
            caller = getCallerIdentity(admin, callerPackageName);
            enforcePermission(MANAGE_DEVICE_POLICY_SYSTEM_UPDATES, caller.getPackageName(),
                    UserHandle.USER_ALL);
        } else {
            caller = getCallerIdentity(admin);
            Preconditions.checkCallAuthorization(
                    isDefaultDeviceOwner(caller)
                            || isProfileOwnerOfOrganizationOwnedDevice(caller));
        }
        checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_INSTALL_SYSTEM_UPDATE);

        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.INSTALL_SYSTEM_UPDATE)
                .setAdmin(caller.getPackageName())
                .setBoolean(isDeviceAB())
                .write();

        mInjector.binderWithCleanCallingIdentity(() -> {
            UpdateInstaller updateInstaller;
            if (isDeviceAB()) {
                updateInstaller = new AbUpdateInstaller(
                        mContext, updateFileDescriptor, callback, mInjector, mConstants);
            } else {
                updateInstaller = new NonAbUpdateInstaller(
                        mContext, updateFileDescriptor, callback, mInjector, mConstants);
            }
            updateInstaller.startInstallUpdate();
        });
    }

    private boolean isDeviceAB() {
        return "true".equalsIgnoreCase(android.os.SystemProperties
                .get(AB_DEVICE_KEY, ""));
    }

    @Override
    public void setCrossProfileCalendarPackages(ComponentName who, List<String> packageNames) {
        if (!mHasFeature) {
            return;
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isProfileOwner(caller));

        synchronized (getLockObject()) {
            final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
            admin.mCrossProfileCalendarPackages = packageNames;
            saveSettingsLocked(caller.getUserId());
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CALENDAR_PACKAGES)
                .setAdmin(who)
                .setStrings(packageNames == null ? null
                        : packageNames.toArray(new String[packageNames.size()]))
                .write();
    }

    @Override
    public List<String> getCrossProfileCalendarPackages(ComponentName who) {
        if (!mHasFeature) {
            return Collections.emptyList();
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isProfileOwner(caller));

        synchronized (getLockObject()) {
            final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
            return admin.mCrossProfileCalendarPackages;
        }
    }

    @Override
    public boolean isPackageAllowedToAccessCalendarForUser(String packageName,
            @UserIdInt int userId) {
        if (!mHasFeature) {
            return false;
        }
        Preconditions.checkStringNotEmpty(packageName, "Package name is null or empty");
        Preconditions.checkArgumentNonnegative(userId, "Invalid userId");

        final int packageUid;
        try (var snapshot = mInjector.getPackageManagerLocal().withUnfilteredSnapshot()) {
            var packageState = snapshot.getPackageStates().get(packageName);
            if (packageState == null) {
                Slogf.w(LOG_TAG, "Couldn't find package %s in user %d", packageName,
                        userId);
                return false;
            } else if (!packageState.getUserStateOrDefault(userId).isInstalled()) {
                Slogf.w(LOG_TAG, "Couldn't find installed package %s in user %d", packageName,
                        userId);
                return false;
            } else {
                packageUid = UserHandle.getUid(userId, packageState.getAppId());
            }
        }
        final CallerIdentity caller = getCallerIdentity();
        if (caller.getUid() != packageUid) {
            Preconditions.checkCallAuthorization(
                    hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS)
                            || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS_FULL));
        }

        synchronized (getLockObject()) {
            if (mInjector.settingsSecureGetIntForUser(
                    Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED, 0, userId) == 0) {
                return false;
            }
            final ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
            if (admin != null) {
                if (admin.mCrossProfileCalendarPackages == null) {
                    return true;
                }
                return admin.mCrossProfileCalendarPackages.contains(packageName);
            }
        }
        return false;
    }

    @Override
    public List<String> getCrossProfileCalendarPackagesForUser(int userHandle) {
        if (!mHasFeature) {
            return Collections.emptyList();
        }
        Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS)
                        || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS_FULL));

        synchronized (getLockObject()) {
            final ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
            if (admin != null) {
                return admin.mCrossProfileCalendarPackages;
            }
        }
        return Collections.emptyList();
    }

    @Override
    public void setCrossProfilePackages(ComponentName who, List<String> packageNames) {
        if (!mHasFeature) {
            return;
        }

        Objects.requireNonNull(who, "ComponentName is null");
        Objects.requireNonNull(packageNames, "Package names is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isProfileOwner(caller));

        final List<String> previousCrossProfilePackages;
        synchronized (getLockObject()) {
            final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
            previousCrossProfilePackages = admin.mCrossProfilePackages;
            if (packageNames.equals(previousCrossProfilePackages)) {
                return;
            }
            admin.mCrossProfilePackages = packageNames;
            saveSettingsLocked(caller.getUserId());
        }
        logSetCrossProfilePackages(who, packageNames);
        final CrossProfileApps crossProfileApps =
                mContext.createContextAsUser(
                        caller.getUserHandle(), /* flags= */ 0)
                        .getSystemService(CrossProfileApps.class);
        mInjector.binderWithCleanCallingIdentity(
        () -> crossProfileApps.resetInteractAcrossProfilesAppOps(
                        previousCrossProfilePackages, new HashSet<>(packageNames)));
    }

    private void logSetCrossProfilePackages(ComponentName who, List<String> packageNames) {
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_PACKAGES)
                .setAdmin(who)
                .setStrings(packageNames.toArray(new String[packageNames.size()]))
                .write();
    }

    @Override
    public List<String> getCrossProfilePackages(ComponentName who) {
        if (!mHasFeature) {
            return Collections.emptyList();
        }
        Objects.requireNonNull(who, "ComponentName is null");
        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isProfileOwner(caller));

        synchronized (getLockObject()) {
            final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
            return admin.mCrossProfilePackages;
        }
    }

    @Override
    public List<String> getAllCrossProfilePackages(int userId) {
        if (!mHasFeature) {
            return Collections.emptyList();
        }
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(
                isSystemUid(caller) || isRootUid(caller) || hasCallingPermission(
                        permission.INTERACT_ACROSS_USERS) || hasCallingPermission(
                        permission.INTERACT_ACROSS_USERS_FULL) || hasPermissionForPreflight(
                                                caller, permission.INTERACT_ACROSS_PROFILES));

        synchronized (getLockObject()) {
            final List<ActiveAdmin> admins = getProfileOwnerAdminsForProfileGroup(userId);
            final List<String> packages = getCrossProfilePackagesForAdmins(admins);

            packages.addAll(getDefaultCrossProfilePackages());

            return packages;
        }
    }

    private List<String> getCrossProfilePackagesForAdmins(List<ActiveAdmin> admins) {
        final List<String> packages = new ArrayList<>();
        for (int i = 0; i < admins.size(); i++) {
            packages.addAll(admins.get(i).mCrossProfilePackages);
        }
        return packages;
    }

    @Override
    public List<String> getDefaultCrossProfilePackages() {
        Set<String> crossProfilePackages = new HashSet<>();

        Collections.addAll(crossProfilePackages, mContext.getResources()
                .getStringArray(R.array.cross_profile_apps));
        Collections.addAll(crossProfilePackages, mContext.getResources()
                .getStringArray(R.array.vendor_cross_profile_apps));

        return new ArrayList<>(crossProfilePackages);
    }

    private List<ActiveAdmin> getProfileOwnerAdminsForProfileGroup(int userId) {
        synchronized (getLockObject()) {
            final List<ActiveAdmin> admins = new ArrayList<>();
            int[] users = mUserManager.getProfileIdsWithDisabled(userId);
            for (int i = 0; i < users.length; i++) {
                final ComponentName componentName = getProfileOwnerAsUser(users[i]);
                if (componentName != null) {
                    ActiveAdmin admin = getActiveAdminUncheckedLocked(componentName, users[i]);
                    if (admin != null) {
                        admins.add(admin);
                    }
                }
            }
            return admins;
        }
    }

    @Override
    public boolean isManagedKiosk() {
        if (!mHasFeature) {
            return false;
        }
        Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())
                || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));

        long id = mInjector.binderClearCallingIdentity();
        try {
            return isManagedKioskInternal();
        } catch (RemoteException e) {
            throw new IllegalStateException(e);
        } finally {
            mInjector.binderRestoreCallingIdentity(id);
        }
    }

    private boolean isUnattendedManagedKioskUnchecked() {
        try {
            return isManagedKioskInternal()
                    && getPowerManagerInternal().wasDeviceIdleFor(UNATTENDED_MANAGED_KIOSK_MS);
        } catch (RemoteException e) {
            throw new IllegalStateException(e);
        }
    }

    @Override
    public boolean isUnattendedManagedKiosk() {
        if (!mHasFeature) {
            return false;
        }
        Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())
                || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));

        return mInjector.binderWithCleanCallingIdentity(() -> isUnattendedManagedKioskUnchecked());
    }

    /**
     * Returns whether the device is currently being used as a publicly-accessible dedicated device.
     * Assumes that feature checks and permission checks have already been performed, and that the
     * calling identity has been cleared.
     */
    private boolean isManagedKioskInternal() throws RemoteException {
        return mOwners.hasDeviceOwner()
                && mInjector.getIActivityManager().getLockTaskModeState()
                        == ActivityManager.LOCK_TASK_MODE_LOCKED
                && !isLockTaskFeatureEnabled(DevicePolicyManager.LOCK_TASK_FEATURE_SYSTEM_INFO)
                && !deviceHasKeyguard()
                && !inEphemeralUserSession();
    }

    private boolean isLockTaskFeatureEnabled(int lockTaskFeature) throws RemoteException {
        LockTaskPolicy policy = mDevicePolicyEngine.getResolvedPolicy(
                PolicyDefinition.LOCK_TASK, getCurrentForegroundUserId());
        int lockTaskFeatures = policy == null
                // We default on the power button menu, in order to be consistent with pre-P
                // behaviour.
                ? DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS
                : policy.getFlags();
        return (lockTaskFeatures & lockTaskFeature) == lockTaskFeature;
    }

    private boolean deviceHasKeyguard() {
        for (UserInfo userInfo : mUserManager.getUsers()) {
            if (mLockPatternUtils.isSecure(userInfo.id)) {
                return true;
            }
        }
        return false;
    }

    private boolean inEphemeralUserSession() {
        for (UserInfo userInfo : mUserManager.getUsers()) {
            if (mInjector.getUserManager().isUserEphemeral(userInfo.id)) {
                return true;
            }
        }
        return false;
    }

    private PowerManagerInternal getPowerManagerInternal() {
        return mInjector.getPowerManagerInternal();
    }

    @Override
    public boolean startViewCalendarEventInManagedProfile(String packageName, long eventId,
            long start, long end, boolean allDay, int flags) {
        if (!mHasFeature) {
            return false;
        }
        Preconditions.checkStringNotEmpty(packageName, "Package name is empty");

        final CallerIdentity caller = getCallerIdentity();
        if (!isCallingFromPackage(packageName, caller.getUid())) {
            throw new SecurityException("Input package name doesn't align with actual "
                    + "calling package.");
        }
        return mInjector.binderWithCleanCallingIdentity(() -> {
            final int workProfileUserId = getManagedUserId(caller.getUserId());
            if (workProfileUserId < 0) {
                return false;
            }
            if (!isPackageAllowedToAccessCalendarForUser(packageName, workProfileUserId)) {
                Slogf.d(LOG_TAG, "Package %s is not allowed to access cross-profile calendar APIs",
                        packageName);
                return false;
            }
            final Intent intent = new Intent(
                    CalendarContract.ACTION_VIEW_MANAGED_PROFILE_CALENDAR_EVENT);
            intent.setPackage(packageName);
            intent.putExtra(CalendarContract.EXTRA_EVENT_ID, eventId);
            intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, start);
            intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, end);
            intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, allDay);
            intent.setFlags(flags);
            try {
                mContext.startActivityAsUser(intent, UserHandle.of(workProfileUserId));
            } catch (ActivityNotFoundException e) {
                Slogf.e(LOG_TAG, "View event activity not found", e);
                return false;
            }
            return true;
        });
    }

    @Override
    public void setApplicationExemptions(String callerPackage, String packageName,
            int[] exemptions) {
        if (!mHasFeature) {
            return;
        }
        Preconditions.checkStringNotEmpty(packageName, "Package name cannot be empty.");
        Objects.requireNonNull(exemptions, "Application exemptions must not be null.");
        Preconditions.checkArgument(areApplicationExemptionsValid(exemptions),
                "Invalid application exemption constant found in application exemptions set.");
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(permission.MANAGE_DEVICE_POLICY_APP_EXEMPTIONS));

        final CallerIdentity caller = getCallerIdentity(callerPackage);
        final ApplicationInfo packageInfo;
        packageInfo = getPackageInfoWithNullCheck(packageName, caller);

        for (Map.Entry<Integer, String> entry :
                APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.entrySet()) {
            int currentMode = mInjector.getAppOpsManager().unsafeCheckOpNoThrow(
                    entry.getValue(), packageInfo.uid, packageInfo.packageName);
            int newMode = ArrayUtils.contains(exemptions, entry.getKey())
                    ? MODE_ALLOWED : MODE_DEFAULT;
            mInjector.binderWithCleanCallingIdentity(() -> {
                if (currentMode != newMode) {
                    mInjector.getAppOpsManager()
                            .setMode(entry.getValue(),
                                    packageInfo.uid,
                                    packageName,
                                    newMode);
                }
            });
        }
        String[] appOpExemptions = new String[exemptions.length];
        for (int i = 0; i < exemptions.length; i++) {
            appOpExemptions[i] = APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.get(exemptions[i]);
        }
        DevicePolicyEventLogger
            .createEvent(DevicePolicyEnums.SET_APPLICATION_EXEMPTIONS)
            .setAdmin(caller.getPackageName())
            .setStrings(packageName, appOpExemptions)
            .write();
    }

    @Override
    public int[] getApplicationExemptions(String packageName) {
        if (!mHasFeature) {
            return new int[0];
        }
        Preconditions.checkStringNotEmpty(packageName, "Package name cannot be empty.");
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(permission.MANAGE_DEVICE_POLICY_APP_EXEMPTIONS));

        final CallerIdentity caller = getCallerIdentity();
        final ApplicationInfo packageInfo;
        packageInfo = getPackageInfoWithNullCheck(packageName, caller);

        IntArray appliedExemptions = new IntArray(0);
        for (Map.Entry<Integer, String> entry :
                APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.entrySet()) {
            if (mInjector.getAppOpsManager().unsafeCheckOpNoThrow(
                    entry.getValue(), packageInfo.uid, packageInfo.packageName) == MODE_ALLOWED) {
                appliedExemptions.add(entry.getKey());
            }
        }
        return appliedExemptions.toArray();
    }

    private ApplicationInfo getPackageInfoWithNullCheck(String packageName, CallerIdentity caller) {
        final ApplicationInfo packageInfo =
                mInjector.getPackageManagerInternal().getApplicationInfo(
                        packageName,
                        /* flags= */ 0,
                        caller.getUid(),
                        caller.getUserId());
        if (packageInfo == null) {
            throw new ServiceSpecificException(
                    DevicePolicyManager.ERROR_PACKAGE_NAME_NOT_FOUND,
                    "Package name not found.");
        }
        return packageInfo;
    }

    private boolean areApplicationExemptionsValid(int[] exemptions) {
        for (int exemption : exemptions) {
            if (!APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.containsKey(exemption)) {
                return false;
            }
        }
        return true;
    }

    private boolean isCallingFromPackage(String packageName, int callingUid) {
        try (var snapshot = mInjector.getPackageManagerLocal().withUnfilteredSnapshot()) {
            var packageState = snapshot.getPackageStates().get(packageName);
            var userId = UserHandle.getUserId(callingUid);
            if (packageState == null) {
                Slogf.d(LOG_TAG, "Calling UID " + callingUid + " not found");
                return false;
            } else if (!packageState.getUserStateOrDefault(userId).isInstalled()) {
                Slogf.d(LOG_TAG, "Calling UID " + callingUid + " not installed");
                return false;
            } else {
                return callingUid == UserHandle.getUid(userId, packageState.getAppId());
            }
        }
    }

    private DevicePolicyConstants loadConstants() {
        return DevicePolicyConstants.loadFromString(
                mInjector.settingsGlobalGetString(Global.DEVICE_POLICY_CONSTANTS));
    }

    @Override
    public void setUserControlDisabledPackages(ComponentName who, String callerPackageName,
            List<String> packages) {
        Objects.requireNonNull(packages, "packages is null");
        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
        checkCanExecuteOrThrowUnsafe(
                DevicePolicyManager.OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES);

        EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                who,
                MANAGE_DEVICE_POLICY_APPS_CONTROL,
                caller.getPackageName(),
                caller.getUserId());
        Binder.withCleanCallingIdentity(() -> {
            if (packages.isEmpty()) {
                removeUserControlDisabledPackages(caller, enforcingAdmin);
            } else {
                addUserControlDisabledPackages(caller, enforcingAdmin, new HashSet<>(packages));
            }
        });

        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_USER_CONTROL_DISABLED_PACKAGES)
                .setAdmin(caller.getPackageName())
                .setStrings(packages.toArray(new String[packages.size()]))
                .write();
    }

    private void addUserControlDisabledPackages(CallerIdentity caller,
            EnforcingAdmin enforcingAdmin, Set<String> packages) {
        if (isDeviceOwner(caller)) {
            mDevicePolicyEngine.setGlobalPolicy(
                    PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
                    enforcingAdmin,
                    new StringSetPolicyValue(packages));
        } else {
            mDevicePolicyEngine.setLocalPolicy(
                    PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
                    enforcingAdmin,
                    new StringSetPolicyValue(packages),
                    caller.getUserId());
        }
    }

    private void removeUserControlDisabledPackages(CallerIdentity caller,
            EnforcingAdmin enforcingAdmin) {
        if (isDeviceOwner(caller)) {
            mDevicePolicyEngine.removeGlobalPolicy(
                    PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
                    enforcingAdmin);
        } else {
            mDevicePolicyEngine.removeLocalPolicy(
                    PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
                    enforcingAdmin,
                    caller.getUserId());
        }
    }

    @Override
    public List<String> getUserControlDisabledPackages(ComponentName who,
            String callerPackageName) {
        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
        enforceCanQuery(
                MANAGE_DEVICE_POLICY_APPS_CONTROL,
                caller.getPackageName(),
                caller.getUserId());
        // This retrieves the policy for the calling user only, DOs for example can't know
        // what's enforced globally or on another user.
        Set<String> packages = mDevicePolicyEngine.getResolvedPolicy(
                PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
                caller.getUserId());
        return packages == null ? Collections.emptyList() : packages.stream().toList();
    }

    @Override
    public void setCommonCriteriaModeEnabled(ComponentName who, String callerPackageName,
            boolean enabled) {
        CallerIdentity caller;
        if (isPermissionCheckFlagEnabled()) {
            caller = getCallerIdentity(who, callerPackageName);
        } else {
            caller = getCallerIdentity(who);
        }
        final ActiveAdmin admin;

        if (isPermissionCheckFlagEnabled()) {
            EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                    who,
                    MANAGE_DEVICE_POLICY_COMMON_CRITERIA_MODE,
                    caller.getPackageName(),
                    caller.getUserId());
            admin = enforcingAdmin.getActiveAdmin();
        } else {
            Objects.requireNonNull(who, "ComponentName is null");
            Preconditions.checkCallAuthorization(
                    isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller),
                    "Common Criteria mode can only be controlled by a device owner or "
                            + "a profile owner on an organization-owned device.");
            synchronized (getLockObject()) {
                admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
            }
        }
        synchronized (getLockObject()) {
            admin.mCommonCriteriaMode = enabled;
            saveSettingsLocked(caller.getUserId());
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_COMMON_CRITERIA_MODE)
                .setAdmin(caller.getPackageName())
                .setBoolean(enabled)
                .write();
    }

    @Override
    public boolean isCommonCriteriaModeEnabled(ComponentName who) {
        if (who != null) {
            final CallerIdentity caller = getCallerIdentity(who);
            Preconditions.checkCallAuthorization(
                    isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller),
                    "Common Criteria mode can only be controlled by a device owner or "
                            + "a profile owner on an organization-owned device.");

            synchronized (getLockObject()) {
                final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
                return admin.mCommonCriteriaMode;
            }
        }

        // Return aggregated state if caller is not admin (who == null).
        synchronized (getLockObject()) {
            // Only DO or COPE PO can turn on CC mode, so take a shortcut here and only look at
            // their ActiveAdmin, instead of iterating through all admins.
            ActiveAdmin admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();

            return admin != null ? admin.mCommonCriteriaMode : false;
        }
    }

    @Override
    public @PersonalAppsSuspensionReason int getPersonalAppsSuspendedReasons(ComponentName who) {
        Objects.requireNonNull(who, "ComponentName is null");

        final CallerIdentity caller = getCallerIdentity(who);
        // DO shouldn't be able to use this method.
        Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));

        synchronized (getLockObject()) {
            final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
            final long deadline = admin.mProfileOffDeadline;
            final int result = makeSuspensionReasons(admin.mSuspendPersonalApps,
                    deadline != 0 && mInjector.systemCurrentTimeMillis() > deadline);
            Slogf.d(LOG_TAG, "getPersonalAppsSuspendedReasons user: %d; result: %d",
                    mInjector.userHandleGetCallingUserId(), result);
            return result;
        }
    }

    private @PersonalAppsSuspensionReason int makeSuspensionReasons(
            boolean explicit, boolean timeout) {
        int result = PERSONAL_APPS_NOT_SUSPENDED;
        if (explicit) {
            result |= PERSONAL_APPS_SUSPENDED_EXPLICITLY;
        }
        if (timeout) {
            result |= PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT;
        }
        return result;
    }

    @Override
    public void setPersonalAppsSuspended(ComponentName who, boolean suspended) {
        Objects.requireNonNull(who, "ComponentName is null");

        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
        Preconditions.checkState(canHandleCheckPolicyComplianceIntent(caller));

        final int callingUserId = caller.getUserId();
        synchronized (getLockObject()) {
            final ActiveAdmin admin = getProfileOwnerLocked(callingUserId);
            boolean shouldSaveSettings = false;
            if (admin.mSuspendPersonalApps != suspended) {
                admin.mSuspendPersonalApps = suspended;
                shouldSaveSettings = true;
            }
            if (admin.mProfileOffDeadline != 0) {
                admin.mProfileOffDeadline = 0;
                shouldSaveSettings = true;
            }
            if (shouldSaveSettings) {
                saveSettingsLocked(callingUserId);
            }
        }

        mInjector.binderWithCleanCallingIdentity(() -> updatePersonalAppsSuspension(
                callingUserId));

        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_PERSONAL_APPS_SUSPENDED)
                .setAdmin(caller.getComponentName())
                .setBoolean(suspended)
                .write();
    }

    /** Starts an activity to check policy compliance or request compliance acknowledgement. */
    private void triggerPolicyComplianceCheckIfNeeded(int profileUserId, boolean suspended) {
        synchronized (getLockObject()) {
            final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(profileUserId);
            if (profileOwner == null) {
                Slogf.wtf(LOG_TAG, "Profile owner not found for compliance check");
                return;
            }
            if (suspended) {
                // If suspended, DPC will need to show an activity.
                final Intent intent = new Intent(ACTION_CHECK_POLICY_COMPLIANCE);
                intent.setPackage(profileOwner.info.getPackageName());
                mContext.startActivityAsUser(intent, UserHandle.of(profileUserId));
            } else if (profileOwner.mProfileOffDeadline > 0) {
                // If not suspended, but deadline set, DPC needs to acknowledge compliance so that
                // the deadline can be reset.
                sendAdminCommandLocked(profileOwner, ACTION_COMPLIANCE_ACKNOWLEDGEMENT_REQUIRED,
                        /* adminExtras= */ null, /* receiver= */ null, /* inForeground = */ true);
            }
        }
    }

    /**
     * Checks whether personal apps should be suspended according to the policy and applies the
     * change if needed.
     */
    private boolean updatePersonalAppsSuspension(int profileUserId) {
        final boolean shouldSuspend;
        synchronized (getLockObject()) {
            final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(profileUserId);
            if (profileOwner != null) {
                // Profile is considered "off" when it is either not running or is running locked
                // or is in quiet mode, i.e. when the admin cannot sync policies or show UI.
                boolean profileUserOff =
                        !mUserManagerInternal.isUserUnlockingOrUnlocked(profileUserId)
                        || mUserManager.isQuietModeEnabled(UserHandle.of(profileUserId));
                final int notificationState = updateProfileOffDeadlineLocked(
                        profileUserId, profileOwner, profileUserOff);
                final boolean suspendedExplicitly = profileOwner.mSuspendPersonalApps;
                final boolean suspendedByTimeout = profileOwner.mProfileOffDeadline == -1;
                Slogf.d(LOG_TAG,
                        "Personal apps suspended explicitly: %b, by timeout: %b, notification: %d",
                        suspendedExplicitly, suspendedByTimeout, notificationState);
                updateProfileOffDeadlineNotificationLocked(
                        profileUserId, profileOwner, notificationState);
                shouldSuspend = suspendedExplicitly || suspendedByTimeout;
            } else {
                shouldSuspend = false;
            }
        }

        final int parentUserId = getProfileParentId(profileUserId);
        suspendPersonalAppsInternal(parentUserId, profileUserId, shouldSuspend);
        return shouldSuspend;
    }

    /**
     * Checks work profile time off policy, scheduling personal apps suspension via alarm if
     * necessary.
     * @return notification state
     */
    private int updateProfileOffDeadlineLocked(
            int profileUserId, ActiveAdmin profileOwner, boolean off) {
        final long now = mInjector.systemCurrentTimeMillis();
        if (profileOwner.mProfileOffDeadline != 0 && now > profileOwner.mProfileOffDeadline) {
            Slogf.i(LOG_TAG, "Profile off deadline has been reached, off: " + off);
            if (profileOwner.mProfileOffDeadline != -1) {
                // Move the deadline far to the past so that it cannot be rolled back by TZ change.
                profileOwner.mProfileOffDeadline = -1;
                saveSettingsLocked(profileUserId);
            }
            return off ? PROFILE_OFF_NOTIFICATION_SUSPENDED : PROFILE_OFF_NOTIFICATION_NONE;
        }
        boolean shouldSaveSettings = false;
        if (profileOwner.mSuspendPersonalApps) {
            // When explicit suspension is active, deadline shouldn't be set.
            if (profileOwner.mProfileOffDeadline != 0) {
                profileOwner.mProfileOffDeadline = 0;
                shouldSaveSettings = true;
            }
        } else if (profileOwner.mProfileOffDeadline != 0
                && (profileOwner.mProfileMaximumTimeOffMillis == 0)) {
            // There is a deadline but either there is no policy -> clear
            // the deadline.
            Slogf.i(LOG_TAG, "Profile off deadline is reset to zero");
            profileOwner.mProfileOffDeadline = 0;
            shouldSaveSettings = true;
        } else if (profileOwner.mProfileOffDeadline == 0
                && (profileOwner.mProfileMaximumTimeOffMillis != 0 && off)) {
            // There profile is locked and there is a policy, but the deadline is not set -> set the
            // deadline.
            Slogf.i(LOG_TAG, "Profile off deadline is set.");
            profileOwner.mProfileOffDeadline = now + profileOwner.mProfileMaximumTimeOffMillis;
            shouldSaveSettings = true;
        }

        if (shouldSaveSettings) {
            saveSettingsLocked(profileUserId);
        }

        final long alarmTime;
        final int notificationState;
        if (!off || profileOwner.mProfileOffDeadline == 0) {
            alarmTime = 0;
            notificationState = PROFILE_OFF_NOTIFICATION_NONE;
        } else if (profileOwner.mProfileOffDeadline - now < MANAGED_PROFILE_OFF_WARNING_PERIOD) {
            // The deadline is close, upon the alarm personal apps should be suspended.
            alarmTime = profileOwner.mProfileOffDeadline;
            notificationState = PROFILE_OFF_NOTIFICATION_WARNING;
        } else {
            // The deadline is quite far, upon the alarm we should warn the user first, so the
            // alarm is scheduled earlier than the actual deadline.
            alarmTime = profileOwner.mProfileOffDeadline - MANAGED_PROFILE_OFF_WARNING_PERIOD;
            notificationState = PROFILE_OFF_NOTIFICATION_NONE;
        }

        final AlarmManager am = mInjector.getAlarmManager();
        final Intent intent = new Intent(ACTION_PROFILE_OFF_DEADLINE);
        intent.setPackage(mContext.getPackageName());
        // Broadcast alarms sent by system are immutable
        final PendingIntent pi = mInjector.pendingIntentGetBroadcast(
                mContext, REQUEST_PROFILE_OFF_DEADLINE, intent,
                PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT
                        | PendingIntent.FLAG_IMMUTABLE);

        if (alarmTime == 0) {
            Slogf.i(LOG_TAG, "Profile off deadline alarm is removed.");
            am.cancel(pi);
        } else {
            Slogf.i(LOG_TAG, "Profile off deadline alarm is set.");
            am.set(AlarmManager.RTC, alarmTime, pi);
        }

        return notificationState;
    }

    private void suspendPersonalAppsInternal(
            int parentUserId, int profileUserId, boolean suspended) {
        if (getUserData(parentUserId).mAppsSuspended == suspended) {
            return;
        }
        Slogf.i(LOG_TAG, "%s personal apps for user %d", suspended ? "Suspending" : "Unsuspending",
                parentUserId);

        // TODO(b/280602237): migrate properly
        ActiveAdmin profileOwner = getProfileOwnerAdminLocked(profileUserId);
        if (profileOwner != null) {
            EnforcingAdmin admin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
                    profileOwner.info.getComponent(),
                    profileUserId,
                    profileOwner);
            mDevicePolicyEngine.setLocalPolicy(
                    PolicyDefinition.PERSONAL_APPS_SUSPENDED,
                    admin,
                    new BooleanPolicyValue(suspended),
                    parentUserId);
        }

        synchronized (getLockObject()) {
            getUserData(parentUserId).mAppsSuspended = suspended;
            saveSettingsLocked(parentUserId);
        }
    }

    private void suspendPersonalAppsInPackageManager(int userId) {
        mInjector.binderWithCleanCallingIdentity(() -> {
            final String[] appsToSuspend = mInjector.getPersonalAppsForSuspension(userId);
            final String[] failedApps = mInjector.getPackageManagerInternal()
                    .setPackagesSuspendedByAdmin(userId, appsToSuspend, true);
            if (!ArrayUtils.isEmpty(failedApps)) {
                Slogf.wtf(LOG_TAG, "Failed to suspend apps: " + String.join(",", failedApps));
            }
        });
    }

    private void notifyIfManagedSubscriptionsAreUnavailable(
            UserHandle managedProfile, boolean managedProfileAvailable) {
        if (!isManagedProfile(managedProfile.getIdentifier())) {
            Slog.wtf(
                    LOG_TAG,
                    "Expected managed profile when notified of profile availability change.");
        }
        if (getManagedSubscriptionsPolicy().getPolicyType()
                != ManagedSubscriptionsPolicy.TYPE_ALL_MANAGED_SUBSCRIPTIONS) {
            // There may be a subscription in the personal profile, in which case calls and
            // texts may still be available. No need to notify the user.
            return;
        }
        if (managedProfileAvailable) {
            // When quiet mode is switched off calls and texts then become available to the user,
            // so no need to keep showing the notification.
            mInjector
                    .getNotificationManager()
                    .cancel(SystemMessage.NOTE_ALL_MANAGED_SUBSCRIPTIONS_AND_MANAGED_PROFILE_OFF);
            return;
        }
        final Intent intent = new Intent(ACTION_TURN_PROFILE_ON_NOTIFICATION);
        intent.putExtra(Intent.EXTRA_USER_HANDLE, managedProfile.getIdentifier());
        final PendingIntent pendingIntent =
                mInjector.pendingIntentGetBroadcast(
                        mContext,
                        /* requestCode= */ 0,
                        intent,
                        PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
        final Notification.Action turnProfileOnButton =
                new Notification.Action.Builder(
                        /* icon= */ null, getUnpauseWorkAppsButtonText(), pendingIntent)
                        .build();

        final Bundle extras = new Bundle();
        extras.putString(
                Notification.EXTRA_SUBSTITUTE_APP_NAME, getWorkProfileContentDescription());
        final Notification notification =
                new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
                        .setSmallIcon(R.drawable.ic_phone_disabled)
                        .setContentTitle(getUnpauseWorkAppsForTelephonyTitle())
                        .setContentText(getUnpauseWorkAppsForTelephonyText())
                        .setStyle(new Notification.BigTextStyle().bigText(
                                getUnpauseWorkAppsForTelephonyText()))
                        .addAction(turnProfileOnButton)
                        .addExtras(extras)
                        .setOngoing(false)
                        .setShowWhen(true)
                        .setAutoCancel(true)
                        .build();

        mInjector
                .getNotificationManager()
                .notifyAsUser(
                        /* tag= */ null,
                        SystemMessage.NOTE_ALL_MANAGED_SUBSCRIPTIONS_AND_MANAGED_PROFILE_OFF,
                        notification,
                        UserHandle.of(getProfileParentId(managedProfile.getIdentifier())));
    }

    private String getUnpauseWorkAppsButtonText() {
        return getUpdatableString(
                WORK_PROFILE_TELEPHONY_PAUSED_TURN_ON_BUTTON,
                R.string.work_profile_telephony_paused_turn_on_button);
    }

    private String getUnpauseWorkAppsForTelephonyTitle() {
        return getUpdatableString(
                WORK_PROFILE_TELEPHONY_PAUSED_TITLE, R.string.work_profile_telephony_paused_title);
    }

    private String getUnpauseWorkAppsForTelephonyText() {
        return getUpdatableString(
                WORK_PROFILE_TELEPHONY_PAUSED_BODY,
                R.string.work_profile_telephony_paused_text);
    }

    @GuardedBy("getLockObject()")
    private void updateProfileOffDeadlineNotificationLocked(
            int profileUserId, ActiveAdmin profileOwner, int notificationState) {
        if (notificationState == PROFILE_OFF_NOTIFICATION_NONE) {
            mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PERSONAL_APPS_SUSPENDED);
            return;
        }

        final Intent intent = new Intent(ACTION_TURN_PROFILE_ON_NOTIFICATION);
        intent.setPackage(mContext.getPackageName());
        intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);

        // Simple notification action button clicks are immutable
        final PendingIntent pendingIntent = mInjector.pendingIntentGetBroadcast(mContext,
                0 /* requestCode */, intent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        final Notification.Action turnProfileOnButton = new Notification.Action.Builder(
                /* icon= */ null, getPersonalAppSuspensionButtonText(), pendingIntent).build();

        final String text;
        final boolean ongoing;
        if (notificationState == PROFILE_OFF_NOTIFICATION_WARNING) {
            // Round to the closest integer number of days.
            final int maxDays = (int)
                    ((profileOwner.mProfileMaximumTimeOffMillis + MS_PER_DAY / 2) / MS_PER_DAY);
            final String date = DateUtils.formatDateTime(
                    mContext, profileOwner.mProfileOffDeadline, DateUtils.FORMAT_SHOW_DATE);
            final String time = DateUtils.formatDateTime(
                    mContext, profileOwner.mProfileOffDeadline, DateUtils.FORMAT_SHOW_TIME);
            text = getPersonalAppSuspensionSoonText(date, time, maxDays);
            ongoing = false;
        } else {
            text = getPersonalAppSuspensionText();
            ongoing = true;
        }
        final int color = mContext.getColor(R.color.personal_apps_suspension_notification_color);
        final Bundle extras = new Bundle();
        // TODO: Create a separate string for this.
        extras.putString(
                Notification.EXTRA_SUBSTITUTE_APP_NAME, getWorkProfileContentDescription());

        final Notification notification =
                new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
                        .setSmallIcon(R.drawable.ic_corp_badge_no_background)
                        .setOngoing(ongoing)
                        .setAutoCancel(false)
                        .setContentTitle(getPersonalAppSuspensionTitle())
                        .setContentText(text)
                        .setStyle(new Notification.BigTextStyle().bigText(text))
                        .setColor(color)
                        .addAction(turnProfileOnButton)
                        .addExtras(extras)
                        .build();

        mHandler.post(() -> mInjector.getNotificationManager().notifyAsUser(
                null, SystemMessage.NOTE_PERSONAL_APPS_SUSPENDED, notification,
                UserHandle.of(getProfileParentId(profileUserId))));
    }

    private String getPersonalAppSuspensionButtonText() {
        return getUpdatableString(
                PERSONAL_APP_SUSPENSION_TURN_ON_PROFILE,
                R.string.personal_apps_suspended_turn_profile_on);
    }

    private String getPersonalAppSuspensionTitle() {
        return getUpdatableString(
                PERSONAL_APP_SUSPENSION_TITLE, R.string.personal_apps_suspension_title);
    }

    private String getPersonalAppSuspensionText() {
        return getUpdatableString(
                PERSONAL_APP_SUSPENSION_MESSAGE, R.string.personal_apps_suspension_text);
    }

    private String getPersonalAppSuspensionSoonText(String date, String time, int maxDays) {
        return getUpdatableString(
                PERSONAL_APP_SUSPENSION_SOON_MESSAGE, R.string.personal_apps_suspension_soon_text,
                date, time, maxDays);
    }

    private String getWorkProfileContentDescription() {
        return getUpdatableString(
                NOTIFICATION_WORK_PROFILE_CONTENT_DESCRIPTION,
                R.string.notification_work_profile_content_description);
    }

    @Override
    public void setManagedProfileMaximumTimeOff(ComponentName who, long timeoutMillis) {
        Objects.requireNonNull(who, "ComponentName is null");
        Preconditions.checkArgumentNonnegative(timeoutMillis, "Timeout must be non-negative.");

        final CallerIdentity caller = getCallerIdentity(who);
        // DO shouldn't be able to use this method.
        Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
        Preconditions.checkState(canHandleCheckPolicyComplianceIntent(caller));

        final int userId = caller.getUserId();
        synchronized (getLockObject()) {
            final ActiveAdmin admin = getProfileOwnerLocked(userId);

            // Ensure the timeout is long enough to avoid having bad user experience.
            if (timeoutMillis > 0 && timeoutMillis < MANAGED_PROFILE_MAXIMUM_TIME_OFF_THRESHOLD
                    && !isAdminTestOnlyLocked(who, userId)) {
                timeoutMillis = MANAGED_PROFILE_MAXIMUM_TIME_OFF_THRESHOLD;
            }
            if (admin.mProfileMaximumTimeOffMillis == timeoutMillis) {
                return;
            }
            admin.mProfileMaximumTimeOffMillis = timeoutMillis;
            saveSettingsLocked(userId);
        }

        mInjector.binderWithCleanCallingIdentity(
                () -> updatePersonalAppsSuspension(userId));

        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_MANAGED_PROFILE_MAXIMUM_TIME_OFF)
                .setAdmin(caller.getComponentName())
                .setTimePeriod(timeoutMillis)
                .write();
    }

    private boolean canHandleCheckPolicyComplianceIntent(CallerIdentity caller) {
        mInjector.binderWithCleanCallingIdentity(() -> {
            final Intent intent = new Intent(DevicePolicyManager.ACTION_CHECK_POLICY_COMPLIANCE);
            intent.setPackage(caller.getPackageName());
            final List<ResolveInfo> handlers =
                    mInjector.getPackageManager().queryIntentActivitiesAsUser(intent, /* flags= */
                            0, caller.getUserId());
            return !handlers.isEmpty();
        });
        return true;
    }

    @Override
    public long getManagedProfileMaximumTimeOff(ComponentName who) {
        Objects.requireNonNull(who, "ComponentName is null");

        final CallerIdentity caller = getCallerIdentity(who);
        Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));

        synchronized (getLockObject()) {
            final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
            return admin.mProfileMaximumTimeOffMillis;
        }
    }

    @Override
    public void acknowledgeDeviceCompliant() {
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
        enforceUserUnlocked(caller.getUserId());

        synchronized (getLockObject()) {
            final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
            if (admin.mProfileOffDeadline > 0) {
                admin.mProfileOffDeadline = 0;
                saveSettingsLocked(caller.getUserId());
            }
        }
    }

    @Override
    public boolean isComplianceAcknowledgementRequired() {
        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
        enforceUserUnlocked(caller.getUserId());

        synchronized (getLockObject()) {
            final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
            return admin.mProfileOffDeadline != 0;
        }
    }

    @Override
    public boolean canProfileOwnerResetPasswordWhenLocked(int userId) {
        Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
                String.format(NOT_SYSTEM_CALLER_MSG,
                        "call canProfileOwnerResetPasswordWhenLocked"));
        synchronized (getLockObject()) {
            final ActiveAdmin poAdmin = getProfileOwnerAdminLocked(userId);
            DevicePolicyData policy = getUserData(userId);
            if (poAdmin == null
                    || getEncryptionStatus() != ENCRYPTION_STATUS_ACTIVE_PER_USER
                    || !isResetPasswordTokenActiveForUserLocked(
                            policy.mPasswordTokenHandle, userId)) {
                return false;
            }
            final ApplicationInfo poAppInfo;
            try {
                poAppInfo = mIPackageManager.getApplicationInfo(
                        poAdmin.info.getPackageName(), 0 /* flags */, userId);
            } catch (RemoteException e) {
                Slogf.e(LOG_TAG, "Failed to query PO app info", e);
                return false;
            }
            if (poAppInfo == null) {
                Slogf.wtf(LOG_TAG, "Cannot find AppInfo for profile owner");
                return false;
            }
            if (!poAppInfo.isEncryptionAware()) {
                return false;
            }
            Slogf.d(LOG_TAG, "PO should be able to reset password from direct boot");
            return true;
        }
    }

    @Override
    public String getEnrollmentSpecificId(String callerPackage) {
        if (!mHasFeature) {
            return "";
        }

        final CallerIdentity caller = getCallerIdentity(callerPackage);
        Preconditions.checkCallAuthorization(
                isDefaultDeviceOwner(caller) || isProfileOwner(caller)
                        || isCallerDelegate(caller, DELEGATION_CERT_INSTALL));

        synchronized (getLockObject()) {
            final ActiveAdmin requiredAdmin = getDeviceOrProfileOwnerAdminLocked(
                    caller.getUserId());
            final String esid = requiredAdmin.mEnrollmentSpecificId;
            return esid != null ? esid : "";
        }
    }

    @Override
    public void setOrganizationIdForUser(
            @NonNull String callerPackage, @NonNull String organizationId, int userId) {
        if (!mHasFeature) {
            return;
        }
        Objects.requireNonNull(callerPackage);

        final CallerIdentity caller = getCallerIdentity(callerPackage);
        // Only the DPC can set this ID.
        Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) || isProfileOwner(caller),
                "Only a Device Owner or Profile Owner may set the Enterprise ID.");
        // Empty enterprise ID must not be provided in calls to this method.
        Preconditions.checkArgument(!TextUtils.isEmpty(organizationId),
                "Enterprise ID may not be empty.");

        Slogf.i(LOG_TAG, "Setting Enterprise ID to %s for user %d", organizationId, userId);

        synchronized (mESIDInitilizationLock) {
            if (mEsidCalculator == null) {
                mInjector.binderWithCleanCallingIdentity(() -> {
                    mEsidCalculator = mInjector.newEnterpriseSpecificIdCalculator();
                });
            }
        }

        final String ownerPackage;
        synchronized (getLockObject()) {
            final ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId);
            // As the caller is the system, it must specify the component name of the profile owner
            // as a safety check.
            Preconditions.checkCallAuthorization(
                    owner != null && owner.getUserHandle().getIdentifier() == userId,
                    String.format("The Profile Owner or Device Owner may only set the Enterprise ID"
                            + " on its own user, called on user %d but owner user is %d", userId,
                            owner.getUserHandle().getIdentifier()));
            ownerPackage = owner.info.getPackageName();
            Preconditions.checkState(
                    TextUtils.isEmpty(owner.mOrganizationId) || owner.mOrganizationId.equals(
                            organizationId),
                    "The organization ID has been previously set to a different value and cannot "
                            + "be changed");
            final String dpcPackage = owner.info.getPackageName();
            final String esid = mEsidCalculator.calculateEnterpriseId(dpcPackage,
                    organizationId);
            owner.mOrganizationId = organizationId;
            owner.mEnrollmentSpecificId = esid;
            saveSettingsLocked(userId);
        }

        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_ORGANIZATION_ID)
                .setAdmin(ownerPackage)
                .setBoolean(isManagedProfile(userId))
                .write();
    }

    @Override
    public void clearOrganizationIdForUser(int userHandle) {
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));

        synchronized (getLockObject()) {
            final ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userHandle);
            owner.mOrganizationId = null;
            owner.mEnrollmentSpecificId = null;
            saveSettingsLocked(userHandle);
        }
    }

    @Override
    public UserHandle createAndProvisionManagedProfile(
            @NonNull ManagedProfileProvisioningParams provisioningParams,
            @NonNull String callerPackage) {
        Objects.requireNonNull(provisioningParams, "provisioningParams is null");
        Objects.requireNonNull(callerPackage, "callerPackage is null");

        final ComponentName admin = provisioningParams.getProfileAdminComponentName();
        Objects.requireNonNull(admin, "admin is null");

        final CallerIdentity caller = getCallerIdentity(callerPackage);
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));

        provisioningParams.logParams(callerPackage);

        UserInfo userInfo = null;
        final long identity = Binder.clearCallingIdentity();
        try {
            final int result = checkProvisioningPreconditionSkipPermission(
                    ACTION_PROVISION_MANAGED_PROFILE, admin.getPackageName(), caller.getUserId());
            if (result != STATUS_OK) {
                throw new ServiceSpecificException(
                        ERROR_PRE_CONDITION_FAILED,
                        "Provisioning preconditions failed with result: " + result);
            }

            final long startTime = SystemClock.elapsedRealtime();

            onCreateAndProvisionManagedProfileStarted(provisioningParams);

            final Set<String> nonRequiredApps = provisioningParams.isLeaveAllSystemAppsEnabled()
                    ? Collections.emptySet()
                    : mOverlayPackagesProvider.getNonRequiredApps(
                            admin, caller.getUserId(), ACTION_PROVISION_MANAGED_PROFILE);
            if (nonRequiredApps.isEmpty()) {
                Slogf.i(LOG_TAG, "No disallowed packages for the managed profile.");
            } else {
                for (String packageName : nonRequiredApps) {
                    Slogf.i(LOG_TAG, "Disallowed package [" + packageName + "]");
                }
            }

            userInfo = mUserManager.createProfileForUserEvenWhenDisallowed(
                    provisioningParams.getProfileName(),
                    UserManager.USER_TYPE_PROFILE_MANAGED,
                    UserInfo.FLAG_DISABLED,
                    caller.getUserId(),
                    nonRequiredApps.toArray(new String[nonRequiredApps.size()]));
            if (userInfo == null) {
                throw new ServiceSpecificException(
                        ERROR_PROFILE_CREATION_FAILED,
                        "Error creating profile, createProfileForUserEvenWhenDisallowed "
                                + "returned null.");
            }
            resetInteractAcrossProfilesAppOps(caller.getUserId());
            logEventDuration(
                    DevicePolicyEnums.PLATFORM_PROVISIONING_CREATE_PROFILE_MS,
                    startTime,
                    callerPackage);

            maybeInstallDevicePolicyManagementRoleHolderInUser(userInfo.id);

            installExistingAdminPackage(userInfo.id, admin.getPackageName());
            if (!enableAdminAndSetProfileOwner(userInfo.id, caller.getUserId(), admin)) {
                throw new ServiceSpecificException(
                        ERROR_SETTING_PROFILE_OWNER_FAILED,
                        "Error setting profile owner.");
            }
            setUserSetupComplete(userInfo.id);

            startProfileForSetup(userInfo.id, callerPackage);
            maybeMigrateAccount(
                    userInfo.id, caller.getUserId(), provisioningParams.getAccountToMigrate(),
                    provisioningParams.isKeepingAccountOnMigration(), callerPackage);

            if (provisioningParams.isOrganizationOwnedProvisioning()) {
                synchronized (getLockObject()) {
                    setProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(admin, userInfo.id,
                            true);
                }
            }

            onCreateAndProvisionManagedProfileCompleted(provisioningParams);

            sendProvisioningCompletedBroadcast(
                    userInfo.id,
                    ACTION_PROVISION_MANAGED_PROFILE,
                    provisioningParams.isLeaveAllSystemAppsEnabled());

            return userInfo.getUserHandle();
        } catch (Exception e) {
            DevicePolicyEventLogger
                    .createEvent(DevicePolicyEnums.PLATFORM_PROVISIONING_ERROR)
                    .setStrings(callerPackage)
                    .write();
            // In case of any errors during provisioning, remove the newly created profile.
            if (userInfo != null) {
                mUserManager.removeUserEvenWhenDisallowed(userInfo.id);
            }
            throw e;
        } finally {
            Binder.restoreCallingIdentity(identity);
        }
    }

    @Override
    public void finalizeWorkProfileProvisioning(UserHandle managedProfileUser,
            Account migratedAccount) {
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));

        if (!isManagedProfile(managedProfileUser.getIdentifier())) {
            throw new IllegalStateException("Given user is not a managed profile");
        }
        ComponentName profileOwnerComponent =
                mOwners.getProfileOwnerComponent(managedProfileUser.getIdentifier());
        if (profileOwnerComponent == null) {
            throw new IllegalStateException("There is no profile owner on the given profile");
        }
        Intent primaryProfileSuccessIntent = new Intent(ACTION_MANAGED_PROFILE_PROVISIONED);
        primaryProfileSuccessIntent.setPackage(profileOwnerComponent.getPackageName());
        primaryProfileSuccessIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES
                | Intent.FLAG_RECEIVER_FOREGROUND);
        primaryProfileSuccessIntent.putExtra(Intent.EXTRA_USER, managedProfileUser);

        if (migratedAccount != null) {
            primaryProfileSuccessIntent.putExtra(EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE,
                    migratedAccount);
        }

        mContext.sendBroadcastAsUser(primaryProfileSuccessIntent,
                UserHandle.of(getProfileParentId(managedProfileUser.getIdentifier())));
    }

    /**
     * Callback called at the beginning of {@link #createAndProvisionManagedProfile(
     * ManagedProfileProvisioningParams, String)} after the relevant prechecks have passed.
     *
     * <p>The logic in this method blocks provisioning.
     *
     * <p>This method is meant to be overridden by OEMs.
     */
    private void onCreateAndProvisionManagedProfileStarted(
            ManagedProfileProvisioningParams provisioningParams) {}

    /**
     * Callback called at the end of {@link #createAndProvisionManagedProfile(
     * ManagedProfileProvisioningParams, String)} after all the other provisioning tasks
     * have completed successfully.
     *
     * <p>The logic in this method blocks provisioning.
     *
     * <p>This method is meant to be overridden by OEMs.
     */
    private void onCreateAndProvisionManagedProfileCompleted(
            ManagedProfileProvisioningParams provisioningParams) {}

    private void maybeInstallDevicePolicyManagementRoleHolderInUser(int targetUserId) {
        String devicePolicyManagerRoleHolderPackageName =
                getRoleHolderPackageName(mContext, RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT);
        if (devicePolicyManagerRoleHolderPackageName == null) {
            Slogf.d(LOG_TAG, "No device policy management role holder specified.");
            return;
        }
        try {
            if (mIPackageManager.isPackageAvailable(
                    devicePolicyManagerRoleHolderPackageName, targetUserId)) {
                Slogf.d(LOG_TAG, "The device policy management role holder "
                        + devicePolicyManagerRoleHolderPackageName + " is already installed in "
                        + "user " + targetUserId);
                return;
            }
            Slogf.d(LOG_TAG, "Installing the device policy management role holder "
                    + devicePolicyManagerRoleHolderPackageName + " in user " + targetUserId);
            mIPackageManager.installExistingPackageAsUser(
                    devicePolicyManagerRoleHolderPackageName,
                    targetUserId,
                    PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
                    PackageManager.INSTALL_REASON_POLICY,
                    /* whiteListedPermissions= */ null);
        } catch (RemoteException e) {
            // Does not happen, same process
        }
    }

    /**
     * If multiple packages hold the role, returns the first package in the list.
     */
    @Nullable
    private String getRoleHolderPackageName(Context context, String role) {
        return getRoleHolderPackageNameOnUser(context, role, Process.myUserHandle());
    }

    /**
     * If multiple packages hold the role, returns the first package in the list.
     */
    @Nullable
    private String getRoleHolderPackageNameOnUser(Context context, String role, UserHandle user) {
        RoleManager roleManager = context.getSystemService(RoleManager.class);

        // Calling identity needs to be cleared as this method is used in the permissions checks.
        return mInjector.binderWithCleanCallingIdentity(() -> {
            List<String> roleHolders = roleManager.getRoleHoldersAsUser(role, user);
            if (roleHolders.isEmpty()) {
                return null;
            }
            return roleHolders.get(0);
        });
    }

    private boolean isCallerDevicePolicyManagementRoleHolder(CallerIdentity caller) {
        return doesCallerHoldRole(caller, RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT);
    }

    private boolean isCallerSystemSupervisionRoleHolder(CallerIdentity caller) {
        return doesCallerHoldRole(caller, RoleManager.ROLE_SYSTEM_SUPERVISION);
    }

    /**
     * Check if the caller is holding the given role on the calling user.
     *
     * @param caller the caller you wish to check
     * @param role the name of the role to check for.
     * @return {@code true} if the caller holds the role, {@code false} otherwise.
     */
    private boolean doesCallerHoldRole(CallerIdentity caller, String role) {
        int callerUid = caller.getUid();
        String roleHolderPackageName =
                getRoleHolderPackageNameOnUser(role, caller.getUserId());
        int roleHolderUid = mInjector.getPackageManagerInternal().getPackageUid(
                roleHolderPackageName, 0, caller.getUserId());

        return callerUid == roleHolderUid;
    }

    /**
     * Return the package name of the role holder on the given user.
     *
     * <p>If the userId passed in is {@link UserHandle.USER_ALL} then every user will be checked and
     * the package name of the role holder on the first user where there is a role holder is
     * returned.
     *
     * @param role the name of the role to check for.
     * @param userId the userId to check for the role holder on.
     * @return the package name of the role holder
     */
    @Nullable
    private String getRoleHolderPackageNameOnUser(String role, int userId) {
        RoleManager roleManager = mContext.getSystemService(RoleManager.class);

        // Clear calling identity as the RoleManager APIs require privileged permissions.
        return mInjector.binderWithCleanCallingIdentity(() -> {
            List<UserInfo> users;
            // Interpret USER_ALL as meaning "any" user.
            if (userId == UserHandle.USER_ALL) {
                users = mInjector.getUserManagerInternal().getUsers(/*excludeDying=*/ true);
            } else {
                users = List.of(new UserInfo(userId, /*name=*/ null, /*flags=*/ 0));
            }
            for (UserInfo user : users) {
                List<String> roleHolders =
                        roleManager.getRoleHoldersAsUser(role, user.getUserHandle());
                if (!roleHolders.isEmpty()) {
                    return roleHolders.get(0);
                }
            }
            return null;
        });
    }

    private void resetInteractAcrossProfilesAppOps(@UserIdInt int userId) {
        mInjector.getCrossProfileApps(userId).clearInteractAcrossProfilesAppOps();
        pregrantDefaultInteractAcrossProfilesAppOps(userId);
    }

    private void pregrantDefaultInteractAcrossProfilesAppOps(@UserIdInt int userId) {
        final String op =
                AppOpsManager.permissionToOp(Manifest.permission.INTERACT_ACROSS_PROFILES);
        for (String packageName : getConfigurableDefaultCrossProfilePackages(userId)) {
            if (!appOpIsDefaultOrAllowed(userId, op, packageName)) {
                continue;
            }
            mInjector.getCrossProfileApps(userId).setInteractAcrossProfilesAppOp(
                    packageName, MODE_ALLOWED);
        }
    }

    private Set<String> getConfigurableDefaultCrossProfilePackages(@UserIdInt int userId) {
        List<String> defaultPackages = getDefaultCrossProfilePackages();
        return defaultPackages.stream().filter(
                mInjector.getCrossProfileApps(userId)::canConfigureInteractAcrossProfiles).collect(
                Collectors.toSet());
    }

    private boolean appOpIsDefaultOrAllowed(@UserIdInt int userId, String op, String packageName) {
        try {
            final int uid = mContext.createContextAsUser(UserHandle.of(userId), /* flags= */ 0).
                    getPackageManager().getPackageUid(packageName, /* flags= */ 0);
            int mode = mInjector.getAppOpsManager().unsafeCheckOpNoThrow(
                    op, uid, packageName);
            return mode == MODE_ALLOWED || mode == MODE_DEFAULT;
        } catch (NameNotFoundException e) {
            return false;
        }
    }

    private void installExistingAdminPackage(int userId, String packageName) {
        try {
            final int status = mContext.getPackageManager().installExistingPackageAsUser(
                    packageName,
                    userId);
            if (status != PackageManager.INSTALL_SUCCEEDED) {
                throw new ServiceSpecificException(
                        ERROR_ADMIN_PACKAGE_INSTALLATION_FAILED,
                        String.format("Failed to install existing package %s for user %d with "
                                        + "result code %d",
                                packageName, userId, status));
            }
        } catch (NameNotFoundException e) {
            throw new ServiceSpecificException(
                    ERROR_ADMIN_PACKAGE_INSTALLATION_FAILED,
                    String.format("Failed to install existing package %s for user %d: %s",
                            packageName, userId, e.getMessage()));
        }
    }

    private boolean enableAdminAndSetProfileOwner(
            @UserIdInt int userId, @UserIdInt int callingUserId, ComponentName adminComponent) {
        enableAndSetActiveAdmin(userId, callingUserId, adminComponent);
        return setProfileOwner(adminComponent, userId);
    }

    private void enableAndSetActiveAdmin(
            @UserIdInt int userId, @UserIdInt int callingUserId, ComponentName adminComponent) {
        final String adminPackage = adminComponent.getPackageName();
        enablePackage(adminPackage, callingUserId);
        setActiveAdmin(adminComponent, /* refreshing= */ true, userId);
    }

    private void enablePackage(String packageName, @UserIdInt int userId) {
        try {
            final int enabledSetting = mIPackageManager.getApplicationEnabledSetting(
                    packageName, userId);
            if (enabledSetting != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
                    && enabledSetting != PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
                mIPackageManager.setApplicationEnabledSetting(
                        packageName,
                        PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
                        // Device policy app may have launched ManagedProvisioning, play nice and
                        // don't kill it as a side-effect of this call.
                        PackageManager.DONT_KILL_APP,
                        userId,
                        mContext.getOpPackageName());
            }
        } catch (RemoteException e) {
            // Shouldn't happen.
            Slogf.wtf(LOG_TAG, "Error setting application enabled", e);
        }
    }

    private void setUserSetupComplete(@UserIdInt int userId) {
        Settings.Secure.putIntForUser(
                mContext.getContentResolver(), USER_SETUP_COMPLETE, 1, userId);
    }

    private void startProfileForSetup(@UserIdInt int userId, String callerPackage)
            throws IllegalStateException {
        Slogf.i(LOG_TAG, "Starting profile %d as requested by package %s", userId, callerPackage);
        final long startTime = SystemClock.elapsedRealtime();
        final UserUnlockedBlockingReceiver unlockedReceiver = new UserUnlockedBlockingReceiver(
                userId);
        mContext.registerReceiverAsUser(
                unlockedReceiver,
                new UserHandle(userId),
                new IntentFilter(Intent.ACTION_USER_UNLOCKED),
                /* broadcastPermission = */ null,
                /* scheduler= */ null);
        try {
            // Must call startProfileEvenWhenDisabled(), as profile is not enabled yet
            if (!mInjector.getActivityManagerInternal().startProfileEvenWhenDisabled(userId)) {
                throw new ServiceSpecificException(ERROR_STARTING_PROFILE_FAILED,
                        String.format("Unable to start user %d in background", userId));
            }

            if (!unlockedReceiver.waitForUserUnlocked()) {
                throw new ServiceSpecificException(ERROR_STARTING_PROFILE_FAILED,
                        String.format("Timeout whilst waiting for unlock of user %d.", userId));
            }
            logEventDuration(
                    DevicePolicyEnums.PLATFORM_PROVISIONING_START_PROFILE_MS,
                    startTime,
                    callerPackage);
        } finally {
            mContext.unregisterReceiver(unlockedReceiver);
        }
    }

    private void maybeMigrateAccount(
            @UserIdInt int targetUserId, @UserIdInt int sourceUserId, Account accountToMigrate,
            boolean keepAccountMigrated, String callerPackage) {
        final UserHandle sourceUser = UserHandle.of(sourceUserId);
        final UserHandle targetUser = UserHandle.of(targetUserId);
        if (accountToMigrate == null) {
            Slogf.d(LOG_TAG, "No account to migrate.");
            return;
        }
        if (sourceUser.equals(targetUser)) {
            Slogf.w(LOG_TAG, "sourceUser and targetUser are the same, won't migrate account.");
            return;
        }
        copyAccount(targetUser, sourceUser, accountToMigrate, callerPackage);
        if (!keepAccountMigrated) {
            removeAccount(accountToMigrate, sourceUserId);
        }
    }

    private void copyAccount(
            UserHandle targetUser, UserHandle sourceUser, Account accountToMigrate,
            String callerPackage) {
        final long startTime = SystemClock.elapsedRealtime();
        try {
            final AccountManager accountManager = mContext.getSystemService(AccountManager.class);
            final boolean copySucceeded = accountManager.copyAccountToUser(
                    accountToMigrate,
                    sourceUser,
                    targetUser,
                    /* callback= */ null, /* handler= */ null)
                    .getResult(60 * 3, TimeUnit.SECONDS);
            if (copySucceeded) {
                logCopyAccountStatus(COPY_ACCOUNT_SUCCEEDED, callerPackage);
                logEventDuration(
                        DevicePolicyEnums.PLATFORM_PROVISIONING_COPY_ACCOUNT_MS,
                        startTime,
                        callerPackage);
            } else {
                logCopyAccountStatus(COPY_ACCOUNT_FAILED, callerPackage);
                Slogf.e(LOG_TAG, "Failed to copy account to " + targetUser);
            }
        } catch (OperationCanceledException e) {
            // Account migration is not considered a critical operation.
            logCopyAccountStatus(COPY_ACCOUNT_TIMED_OUT, callerPackage);
            Slogf.e(LOG_TAG, "Exception copying account to " + targetUser, e);
        } catch (AuthenticatorException | IOException e) {
            logCopyAccountStatus(COPY_ACCOUNT_EXCEPTION, callerPackage);
            Slogf.e(LOG_TAG, "Exception copying account to " + targetUser, e);
        }
    }

    private static void logCopyAccountStatus(@CopyAccountStatus int status, String callerPackage) {
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.PLATFORM_PROVISIONING_COPY_ACCOUNT_STATUS)
                .setInt(status)
                .setStrings(callerPackage)
                .write();
    }

    private void removeAccount(Account account, @UserIdInt int sourceUserId) {
        final AccountManager accountManager = mContext.createContextAsUser(
                        UserHandle.of(sourceUserId), /* flags= */ 0)
                .getSystemService(AccountManager.class);
        try {
            final Bundle result = accountManager.removeAccount(account,
                    null, null /* callback */, null /* handler */).getResult(60, TimeUnit.SECONDS);
            if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, /* default */ false)) {
                Slogf.i(LOG_TAG, "Account removed from the primary user.");
            } else {
                // TODO(174768447): Revisit start activity logic.
                final Intent removeIntent = result.getParcelable(AccountManager.KEY_INTENT, android.content.Intent.class);
                removeIntent.addFlags(FLAG_ACTIVITY_NEW_TASK);
                if (removeIntent != null) {
                    Slogf.i(LOG_TAG, "Starting activity to remove account");
                    new Handler(Looper.getMainLooper()).post(() -> {
                        mContext.startActivity(removeIntent);
                    });
                } else {
                    Slogf.e(LOG_TAG, "Could not remove account from the primary user.");
                }
            }
        } catch (OperationCanceledException | AuthenticatorException | IOException e) {
            Slogf.e(LOG_TAG, "Exception removing account from the primary user.", e);
        }
    }

    @Override
    public void provisionFullyManagedDevice(
            @NonNull FullyManagedDeviceProvisioningParams provisioningParams,
            @NonNull String callerPackage) {
        Objects.requireNonNull(provisioningParams, "provisioningParams is null.");
        Objects.requireNonNull(callerPackage, "callerPackage is null.");

        ComponentName deviceAdmin = provisioningParams.getDeviceAdminComponentName();
        Objects.requireNonNull(deviceAdmin, "admin is null.");
        Objects.requireNonNull(provisioningParams.getOwnerName(), "owner name is null.");

        final CallerIdentity caller = getCallerIdentity();
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS)
                        || (hasCallingOrSelfPermission(permission.PROVISION_DEMO_DEVICE)
                        && provisioningParams.isDemoDevice()));

        provisioningParams.logParams(callerPackage);

        final long identity = Binder.clearCallingIdentity();
        try {
            int result = checkProvisioningPreconditionSkipPermission(
                    ACTION_PROVISION_MANAGED_DEVICE, deviceAdmin.getPackageName(),
                    caller.getUserId());
            if (result != STATUS_OK) {
                throw new ServiceSpecificException(
                        ERROR_PRE_CONDITION_FAILED,
                        "Provisioning preconditions failed with result: " + result);
            }
            onProvisionFullyManagedDeviceStarted(provisioningParams);

            // These properties are global so will apply on all users
            setTimeAndTimezone(provisioningParams.getTimeZone(), provisioningParams.getLocalTime());
            setLocale(provisioningParams.getLocale());

            int deviceOwnerUserId = UserHandle.USER_SYSTEM;
            if (!removeNonRequiredAppsForManagedDevice(
                    deviceOwnerUserId,
                    provisioningParams.isLeaveAllSystemAppsEnabled(),
                    deviceAdmin)) {
                throw new ServiceSpecificException(
                        ERROR_REMOVE_NON_REQUIRED_APPS_FAILED,
                        "PackageManager failed to remove non required apps.");
            }


            if (!setActiveAdminAndDeviceOwner(deviceOwnerUserId, deviceAdmin)) {
                throw new ServiceSpecificException(
                        ERROR_SET_DEVICE_OWNER_FAILED, "Failed to set device owner.");
            }

            disallowAddUser();
            setAdminCanGrantSensorsPermissionForUserUnchecked(
                    deviceOwnerUserId, provisioningParams.canDeviceOwnerGrantSensorsPermissions());
            setDemoDeviceStateUnchecked(deviceOwnerUserId, provisioningParams.isDemoDevice());
            onProvisionFullyManagedDeviceCompleted(provisioningParams);
            sendProvisioningCompletedBroadcast(
                    deviceOwnerUserId,
                    ACTION_PROVISION_MANAGED_DEVICE,
                    provisioningParams.isLeaveAllSystemAppsEnabled());
        } catch (Exception e) {
            DevicePolicyEventLogger
                    .createEvent(DevicePolicyEnums.PLATFORM_PROVISIONING_ERROR)
                    .setStrings(callerPackage)
                    .write();
            throw e;
        } finally {
            Binder.restoreCallingIdentity(identity);
        }
    }

    /**
     * Callback called at the beginning of {@link #provisionFullyManagedDevice(
     * FullyManagedDeviceProvisioningParams, String)} after the relevant prechecks have passed.
     *
     * <p>The logic in this method blocks provisioning.
     *
     * <p>This method is meant to be overridden by OEMs.
     */
    private void onProvisionFullyManagedDeviceStarted(
            FullyManagedDeviceProvisioningParams provisioningParams) {}

    /**
     * Callback called at the end of {@link #provisionFullyManagedDevice(
     * FullyManagedDeviceProvisioningParams, String)} after all the other provisioning tasks
     * have completed successfully.
     *
     * <p>The logic in this method blocks provisioning.
     *
     * <p>This method is meant to be overridden by OEMs.
     */
    private void onProvisionFullyManagedDeviceCompleted(
            FullyManagedDeviceProvisioningParams provisioningParams) {}

    private void setTimeAndTimezone(String timeZone, long localTime) {
        try {
            final AlarmManager alarmManager = mContext.getSystemService(AlarmManager.class);
            if (timeZone != null) {
                alarmManager.setTimeZone(timeZone);
            }
            if (localTime > 0) {
                alarmManager.setTime(localTime);
            }
        } catch (Exception e) {
            // Do not stop provisioning and ignore this error.
            Slogf.e(LOG_TAG, "Alarm manager failed to set the system time/timezone.", e);
        }
    }

    private void setLocale(Locale locale) {
        if (locale == null || locale.equals(Locale.getDefault())) {
            return;
        }
        try {
            // If locale is different from current locale this results in a configuration change,
            // which will trigger the restarting of the activity.
            LocalePicker.updateLocale(locale);
        } catch (Exception e) {
            // Do not stop provisioning and ignore this error.
            Slogf.e(LOG_TAG, "Failed to set the system locale.", e);
        }
    }

    private boolean removeNonRequiredAppsForManagedDevice(
            @UserIdInt int userId, boolean leaveAllSystemAppsEnabled, ComponentName admin) {
        Set<String> packagesToDelete = leaveAllSystemAppsEnabled
                ? Collections.emptySet()
                : mOverlayPackagesProvider.getNonRequiredApps(
                        admin, userId, ACTION_PROVISION_MANAGED_DEVICE);

        removeNonInstalledPackages(packagesToDelete, userId);
        if (packagesToDelete.isEmpty()) {
            Slogf.i(LOG_TAG, "No packages to delete on user " + userId);
            return true;
        }

        NonRequiredPackageDeleteObserver packageDeleteObserver =
                new NonRequiredPackageDeleteObserver(packagesToDelete.size());
        for (String packageName : packagesToDelete) {
            Slogf.i(LOG_TAG, "Deleting package [" + packageName + "] as user " + userId);
            mContext.getPackageManager().deletePackageAsUser(
                    packageName,
                    packageDeleteObserver,
                    PackageManager.DELETE_SYSTEM_APP,
                    userId);
        }
        Slogf.i(LOG_TAG, "Waiting for non required apps to be deleted");
        return packageDeleteObserver.awaitPackagesDeletion();
    }

    private void removeNonInstalledPackages(Set<String> packages, @UserIdInt int userId) {
        final Set<String> toBeRemoved = new HashSet<>();
        for (String packageName : packages) {
            if (!isPackageInstalledForUser(packageName, userId)) {
                toBeRemoved.add(packageName);
            }
        }
        packages.removeAll(toBeRemoved);
    }

    private void disallowAddUser() {
        if (mIsAutomotive) {
            // Auto still enables adding users due to the communal nature of those devices
            if (mInjector.userManagerIsHeadlessSystemUserMode()) {
                Slogf.i(LOG_TAG, "Not setting DISALLOW_ADD_USER on headless system user mode.");
                return;
            }
        }
        for (UserInfo userInfo : mUserManager.getUsers()) {
            UserHandle userHandle = userInfo.getUserHandle();
            if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, userHandle)) {
                mUserManager.setUserRestriction(
                        UserManager.DISALLOW_ADD_USER, /* value= */ true, userHandle);
            }
        }
    }

    private boolean setActiveAdminAndDeviceOwner(
            @UserIdInt int userId, ComponentName adminComponent) {
        enableAndSetActiveAdmin(userId, userId, adminComponent);
        // TODO(b/178187130): Directly set DO and remove the check once silent provisioning is no
        //  longer used.
        if (getDeviceOwnerComponent(/* callingUserOnly= */ true) == null) {
            return setDeviceOwner(adminComponent, userId,
                    /* setProfileOwnerOnCurrentUserIfNecessary= */ true);
        }
        return true;
    }

    private static void logEventDuration(int eventId, long startTime, String callerPackage) {
        final long duration = SystemClock.elapsedRealtime() - startTime;
        DevicePolicyEventLogger
                .createEvent(eventId)
                .setTimePeriod(duration)
                .setStrings(callerPackage)
                .write();
    }

    @Override
    public void resetDefaultCrossProfileIntentFilters(@UserIdInt int userId) {
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));

        mInjector.binderWithCleanCallingIdentity(() -> {
            try {
                final List<UserInfo> profiles = mUserManager.getProfiles(userId);
                final int numOfProfiles = profiles.size();
                if (numOfProfiles <= 1) {
                    return;
                }

                final String managedProvisioningPackageName = getManagedProvisioningPackage(
                        mContext);
                // Removes cross profile intent filters from the parent to all the profiles.
                mIPackageManager.clearCrossProfileIntentFilters(
                        userId, mContext.getOpPackageName());
                // Setting and resetting default cross profile intent filters was previously handled
                // by Managed Provisioning. For backwards compatibility, clear any intent filters
                // that were set by ManagedProvisioning.
                mIPackageManager.clearCrossProfileIntentFilters(
                        userId, managedProvisioningPackageName);

                // For each profile reset cross profile intent filters
                for (int i = 0; i < numOfProfiles; i++) {
                    UserInfo profile = profiles.get(i);
                    mIPackageManager.clearCrossProfileIntentFilters(
                            profile.id, mContext.getOpPackageName());
                    // Clear any intent filters that were set by ManagedProvisioning.
                    mIPackageManager.clearCrossProfileIntentFilters(
                            profile.id, managedProvisioningPackageName);

                    mUserManagerInternal.setDefaultCrossProfileIntentFilters(userId, profile.id);
                }
            } catch (RemoteException e) {
                // Shouldn't happen.
                Slogf.wtf(LOG_TAG, "Error resetting default cross profile intent filters", e);
            }
        });
    }

    private void setAdminCanGrantSensorsPermissionForUserUnchecked(@UserIdInt int userId,
            boolean canGrant) {
        Slogf.d(LOG_TAG, "setAdminCanGrantSensorsPermissionForUserUnchecked(%d, %b)",
                userId, canGrant);
        synchronized (getLockObject()) {
            ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId);

            Preconditions.checkState(
                    isDeviceOwner(owner) && owner.getUserHandle().getIdentifier() == userId,
                    "May only be set on a the user of a device owner.");

            owner.mAdminCanGrantSensorsPermissions = canGrant;
            mPolicyCache.setAdminCanGrantSensorsPermissions(canGrant);
            saveSettingsLocked(userId);
        }
    }

    private void setDemoDeviceStateUnchecked(@UserIdInt int userId, boolean isDemoDevice) {
        Slogf.d(LOG_TAG, "setDemoDeviceStateUnchecked(%d, %b)",
                userId, isDemoDevice);
        if (!isDemoDevice) {
            return;
        }
        synchronized (getLockObject()) {
            mInjector.settingsGlobalPutStringForUser(
                    Settings.Global.DEVICE_DEMO_MODE, Integer.toString(/* value= */ 1), userId);
        }

        setUserProvisioningState(STATE_USER_SETUP_FINALIZED, userId);
    }

    private void updateAdminCanGrantSensorsPermissionCache(@UserIdInt int userId) {
        synchronized (getLockObject()) {

            ActiveAdmin owner;
            // If the user is affiliated the device (either a DO itself, or an affiliated PO),
            // use mAdminCanGrantSensorsPermissions from the DO
            if (isUserAffiliatedWithDeviceLocked(userId)) {
                owner = getDeviceOwnerAdminLocked();
            } else {
                owner = getDeviceOrProfileOwnerAdminLocked(userId);
            }
            boolean canGrant = owner != null ? owner.mAdminCanGrantSensorsPermissions : false;
            mPolicyCache.setAdminCanGrantSensorsPermissions(canGrant);
        }
    }

    private void updateNetworkPreferenceForUser(int userId,
            List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs) {
        if (!isManagedProfile(userId) && !isDeviceOwnerUserId(userId)) {
            return;
        }
        List<ProfileNetworkPreference> preferences = new ArrayList<>();
        for (PreferentialNetworkServiceConfig preferentialNetworkServiceConfig :
                preferentialNetworkServiceConfigs) {
            ProfileNetworkPreference.Builder preferenceBuilder =
                    new ProfileNetworkPreference.Builder();
            if (preferentialNetworkServiceConfig.isEnabled()) {
                if (preferentialNetworkServiceConfig.isFallbackToDefaultConnectionAllowed()) {
                    preferenceBuilder.setPreference(PROFILE_NETWORK_PREFERENCE_ENTERPRISE);
                } else if (preferentialNetworkServiceConfig.shouldBlockNonMatchingNetworks()) {
                    preferenceBuilder.setPreference(
                            PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING);
                } else {
                    preferenceBuilder.setPreference(
                            PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK);
                }
                preferenceBuilder.setIncludedUids(
                        preferentialNetworkServiceConfig.getIncludedUids());
                preferenceBuilder.setExcludedUids(
                        preferentialNetworkServiceConfig.getExcludedUids());
                preferenceBuilder.setPreferenceEnterpriseId(
                        preferentialNetworkServiceConfig.getNetworkId());
            } else {
                preferenceBuilder.setPreference(PROFILE_NETWORK_PREFERENCE_DEFAULT);
            }


            preferences.add(preferenceBuilder.build());
        }
        Slogf.d(LOG_TAG, "updateNetworkPreferenceForUser to " + preferences);
        mInjector.binderWithCleanCallingIdentity(() ->
                mInjector.getConnectivityManager().setProfileNetworkPreferences(
                        UserHandle.of(userId), preferences,
                        null /* executor */, null /* listener */));
    }

    @Override
    public boolean canAdminGrantSensorsPermissions() {
        if (!mHasFeature) {
            return false;
        }

        return mPolicyCache.canAdminGrantSensorsPermissions();
    }

    @Override
    public void setDeviceOwnerType(@NonNull ComponentName admin,
            @DeviceOwnerType int deviceOwnerType) {
        Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
                MANAGE_PROFILE_AND_DEVICE_OWNERS));

        synchronized (getLockObject()) {
            setDeviceOwnerTypeLocked(admin, deviceOwnerType);
        }
    }

    private void setDeviceOwnerTypeLocked(ComponentName admin,
            @DeviceOwnerType int deviceOwnerType) {
        String packageName = admin.getPackageName();
        boolean isAdminTestOnly;

        verifyDeviceOwnerTypePreconditionsLocked(admin);

        isAdminTestOnly = isAdminTestOnlyLocked(admin, mOwners.getDeviceOwnerUserId());
        Preconditions.checkState(isAdminTestOnly
                        || !mOwners.isDeviceOwnerTypeSetForDeviceOwner(packageName),
                "Test only admins can only set the device owner type more than once");

        mOwners.setDeviceOwnerType(packageName, deviceOwnerType, isAdminTestOnly);
        setGlobalSettingDeviceOwnerType(deviceOwnerType);
    }

    // TODO(b/237065504): Allow mainline modules to get the device owner type. This is a workaround
    // to get the device owner type in PermissionController. See HibernationPolicy.kt.
    private void setGlobalSettingDeviceOwnerType(int deviceOwnerType) {
        mInjector.binderWithCleanCallingIdentity(
                () -> mInjector.settingsGlobalPutInt("device_owner_type", deviceOwnerType));
    }

    @Override
    @DeviceOwnerType
    public int getDeviceOwnerType(@NonNull ComponentName admin) {
        synchronized (getLockObject()) {
            verifyDeviceOwnerTypePreconditionsLocked(admin);
            return getDeviceOwnerTypeLocked(admin.getPackageName());
        }
    }

    @DeviceOwnerType
    private int getDeviceOwnerTypeLocked(String packageName) {
        return mOwners.getDeviceOwnerType(packageName);
    }

    /**
     * {@code true} is returned <b>only if</b> the caller is the device owner and the device owner
     * type is {@link DevicePolicyManager#DEVICE_OWNER_TYPE_FINANCED}. {@code false} is returned for
     * the case where the caller is not the device owner, there is no device owner, or the device
     * owner type is not {@link DevicePolicyManager#DEVICE_OWNER_TYPE_FINANCED}.
     */
    private boolean isFinancedDeviceOwner(CallerIdentity caller) {
        synchronized (getLockObject()) {
            return isDeviceOwnerLocked(caller) && getDeviceOwnerTypeLocked(
                    mOwners.getDeviceOwnerPackageName()) == DEVICE_OWNER_TYPE_FINANCED;
        }
    }

    private void verifyDeviceOwnerTypePreconditionsLocked(@NonNull ComponentName admin) {
        Preconditions.checkState(mOwners.hasDeviceOwner(), "there is no device owner");
        Preconditions.checkState(mOwners.getDeviceOwnerComponent().equals(admin),
                "admin is not the device owner");
    }

    @Override
    public void setUsbDataSignalingEnabled(String packageName, boolean enabled) {
        Objects.requireNonNull(packageName, "Admin package name must be provided");
        final CallerIdentity caller = getCallerIdentity(packageName);

        if (!policyEngineMigrationV2Enabled()) {
            Preconditions.checkCallAuthorization(
                    isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller),
                    "USB data signaling can only be controlled by a device owner or "
                            + "a profile owner on an organization-owned device.");
            Preconditions.checkState(canUsbDataSignalingBeDisabled(),
                    "USB data signaling cannot be disabled.");
        }

        synchronized (getLockObject()) {
            if (policyEngineMigrationV2Enabled()) {
                EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                        /* admin= */ null, MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING,
                        caller.getPackageName(),
                        caller.getUserId());
                Preconditions.checkState(canUsbDataSignalingBeDisabled(),
                        "USB data signaling cannot be disabled.");
                mDevicePolicyEngine.setGlobalPolicy(
                        PolicyDefinition.USB_DATA_SIGNALING,
                        enforcingAdmin,
                        new BooleanPolicyValue(enabled));
            } else {
                ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
                if (admin.mUsbDataSignalingEnabled != enabled) {
                    admin.mUsbDataSignalingEnabled = enabled;
                    saveSettingsLocked(caller.getUserId());
                    updateUsbDataSignal(mContext, isUsbDataSignalingEnabledInternalLocked());
                }
            }
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_USB_DATA_SIGNALING)
                .setAdmin(packageName)
                .setBoolean(enabled)
                .write();
    }

    static void updateUsbDataSignal(Context context, boolean value) {
        if (!canUsbDataSignalingBeDisabledInternal(context)) {
            return;
        }
        if (!Binder.withCleanCallingIdentity(
                () -> context.getSystemService(UsbManager.class).enableUsbDataSignal(value))) {
            Slogf.w(LOG_TAG, "Failed to set usb data signaling state");
        }
    }

    @Override
    public boolean isUsbDataSignalingEnabled(String packageName) {
        final CallerIdentity caller = getCallerIdentity(packageName);
        if (policyEngineMigrationV2Enabled()) {
            Boolean enabled = mDevicePolicyEngine.getResolvedPolicy(
                    PolicyDefinition.USB_DATA_SIGNALING,
                    caller.getUserId());
            return enabled == null || enabled;
        } else {
            synchronized (getLockObject()) {
                // If the caller is an admin, return the policy set by itself. Otherwise
                // return the device-wide policy.
                if (isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(
                        caller)) {
                    return getProfileOwnerOrDeviceOwnerLocked(
                            caller.getUserId()).mUsbDataSignalingEnabled;
                } else {
                    return isUsbDataSignalingEnabledInternalLocked();
                }
            }
        }
    }

    private boolean isUsbDataSignalingEnabledInternalLocked() {
        ActiveAdmin admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
        return admin == null || admin.mUsbDataSignalingEnabled;
    }

    @Override
    public boolean canUsbDataSignalingBeDisabled() {
        return canUsbDataSignalingBeDisabledInternal(mContext);
    }

    private static boolean canUsbDataSignalingBeDisabledInternal(Context context) {
        return Binder.withCleanCallingIdentity(() ->
            context.getSystemService(UsbManager.class) != null
                  && context.getSystemService(UsbManager.class).getUsbHalVersion()
                  >= UsbManager.USB_HAL_V1_3
        );
    }

    private void notifyMinimumRequiredWifiSecurityLevelChanged(int level) {
        mInjector.binderWithCleanCallingIdentity(
                () -> mInjector.getWifiManager()
                        .notifyMinimumRequiredWifiSecurityLevelChanged(level));
    }

    private void notifyWifiSsidPolicyChanged(WifiSsidPolicy policy) {
        if (policy == null) {
            // If policy doesn't limit SSIDs, no need to disconnect anything.
            return;
        }
        mInjector.binderWithCleanCallingIdentity(
                () -> mInjector.getWifiManager().notifyWifiSsidPolicyChanged(policy));
    }

    @Override
    public void setMinimumRequiredWifiSecurityLevel(String callerPackageName, int level) {
        CallerIdentity caller;
        if (isPermissionCheckFlagEnabled()) {
            caller = getCallerIdentity(callerPackageName);
        } else {
            caller = getCallerIdentity();
            Preconditions.checkCallAuthorization(
                    isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller),
                    "Wi-Fi minimum security level can only be controlled by a device owner or "
                            + "a profile owner on an organization-owned device.");
        }

        boolean valueChanged = false;
        synchronized (getLockObject()) {
            ActiveAdmin admin;
            if (isPermissionCheckFlagEnabled()) {
                admin = enforcePermissionAndGetEnforcingAdmin(/* admin= */ null,
                        MANAGE_DEVICE_POLICY_WIFI, caller.getPackageName(), caller.getUserId())
                        .getActiveAdmin();
            } else {
                admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
            }
            if (admin.mWifiMinimumSecurityLevel != level) {
                admin.mWifiMinimumSecurityLevel = level;
                saveSettingsLocked(caller.getUserId());
                valueChanged = true;
            }
        }
        if (valueChanged) notifyMinimumRequiredWifiSecurityLevelChanged(level);
    }

    @Override
    public int getMinimumRequiredWifiSecurityLevel() {
        synchronized (getLockObject()) {
            ActiveAdmin admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
            return (admin == null) ? DevicePolicyManager.WIFI_SECURITY_OPEN
                    : admin.mWifiMinimumSecurityLevel;
        }
    }

    @Override
    public WifiSsidPolicy getWifiSsidPolicy(String callerPackageName) {
        final CallerIdentity caller = getCallerIdentity();
        if (isPermissionCheckFlagEnabled()) {
            enforcePermission(MANAGE_DEVICE_POLICY_WIFI, callerPackageName,
                    caller.getUserId());
        } else {
            Preconditions.checkCallAuthorization(
                    isDefaultDeviceOwner(caller)
                            || isProfileOwnerOfOrganizationOwnedDevice(caller)
                            || canQueryAdminPolicy(caller),
                    "SSID policy can only be retrieved by a device owner or "
                            + "a profile owner on an organization-owned device or "
                            + "an app with the QUERY_ADMIN_POLICY permission.");
        }
        synchronized (getLockObject()) {
            ActiveAdmin admin;
            admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceOrSystemPermissionBasedAdminLocked();
            return admin != null ? admin.mWifiSsidPolicy : null;
        }
    }

    @Override
    public void setWifiSsidPolicy(String callerPackageName, WifiSsidPolicy policy) {
        CallerIdentity caller;

        if (isPermissionCheckFlagEnabled()) {
            caller = getCallerIdentity(callerPackageName);
        } else {
            caller = getCallerIdentity();
            Preconditions.checkCallAuthorization(
                    isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller),
                    "SSID denylist can only be controlled by a device owner or "
                            + "a profile owner on an organization-owned device.");
        }

        boolean changed = false;
        synchronized (getLockObject()) {
            ActiveAdmin admin;
            if (isPermissionCheckFlagEnabled()) {
                admin = enforcePermissionAndGetEnforcingAdmin(
                        /* admin= */ null, MANAGE_DEVICE_POLICY_WIFI,
                        caller.getPackageName(),
                        caller.getUserId()).getActiveAdmin();
            } else {
                admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
            }
            if (!Objects.equals(policy, admin.mWifiSsidPolicy)) {
                admin.mWifiSsidPolicy = policy;
                changed = true;
            }
            if (changed) saveSettingsLocked(caller.getUserId());
        }
        if (changed) {
            notifyWifiSsidPolicyChanged(policy);
        }
    }

    @Override
    public void setDrawables(@NonNull List<DevicePolicyDrawableResource> drawables) {
        Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
                android.Manifest.permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES));

        Objects.requireNonNull(drawables, "drawables must be provided.");

        mInjector.binderWithCleanCallingIdentity(() -> {
            if (mDeviceManagementResourcesProvider.updateDrawables(drawables)) {
                sendDrawableUpdatedBroadcast(
                        drawables.stream().map(s -> s.getDrawableId()).collect(
                                Collectors.toList()));
            }
        });
    }

    @Override
    public void resetDrawables(@NonNull List<String> drawableIds) {
        Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
                android.Manifest.permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES));

        Objects.requireNonNull(drawableIds, "drawableIds must be provided.");

        mInjector.binderWithCleanCallingIdentity(() -> {
            if (mDeviceManagementResourcesProvider.removeDrawables(drawableIds)) {
                sendDrawableUpdatedBroadcast(drawableIds);
            }
        });
    }

    @Override
    public ParcelableResource getDrawable(
            String drawableId, String drawableStyle, String drawableSource) {
        return mInjector.binderWithCleanCallingIdentity(() ->
                mDeviceManagementResourcesProvider.getDrawable(
                        drawableId, drawableStyle, drawableSource));
    }

    private void sendDrawableUpdatedBroadcast(List<String> drawableIds) {
        sendResourceUpdatedBroadcast(EXTRA_RESOURCE_TYPE_DRAWABLE, drawableIds);
    }

    @Override
    public void setStrings(@NonNull List<DevicePolicyStringResource> strings) {
        Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
                android.Manifest.permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES));

        Objects.requireNonNull(strings, "strings must be provided.");

        mInjector.binderWithCleanCallingIdentity(() -> {
            if (mDeviceManagementResourcesProvider.updateStrings(strings)) {
                sendStringsUpdatedBroadcast(
                        strings.stream().map(s -> s.getStringId()).collect(Collectors.toList()));
            }
        });
    }

    @Override
    public void resetStrings(@NonNull List<String> stringIds) {
        Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
                android.Manifest.permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES));

        mInjector.binderWithCleanCallingIdentity(() -> {
            if (mDeviceManagementResourcesProvider.removeStrings(stringIds)) {
                sendStringsUpdatedBroadcast(stringIds);
            }
        });
    }

    @Override
    public ParcelableResource getString(String stringId) {
        return mInjector.binderWithCleanCallingIdentity(() ->
                mDeviceManagementResourcesProvider.getString(stringId));
    }

    private void sendStringsUpdatedBroadcast(List<String> stringIds) {
        sendResourceUpdatedBroadcast(EXTRA_RESOURCE_TYPE_STRING, stringIds);
    }

    private void sendResourceUpdatedBroadcast(int resourceType, List<String> resourceIds) {
        final Intent intent = new Intent(ACTION_DEVICE_POLICY_RESOURCE_UPDATED);
        intent.putExtra(EXTRA_RESOURCE_IDS, resourceIds.toArray(String[]::new));
        intent.putExtra(EXTRA_RESOURCE_TYPE, resourceType);
        intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);

        List<UserInfo> users = mUserManager.getAliveUsers();
        for (int i = 0; i < users.size(); i++) {
            UserHandle user = users.get(i).getUserHandle();
            mContext.sendBroadcastAsUser(intent, user);
        }
    }

    private String getUpdatableString(
            String updatableStringId, int defaultStringId, Object... formatArgs) {
        ParcelableResource resource = mDeviceManagementResourcesProvider.getString(
                updatableStringId);
        if (resource == null) {
            return ParcelableResource.loadDefaultString(() ->
                    mContext.getString(defaultStringId, formatArgs));
        }
        return resource.getString(
                mContext, () -> mContext.getString(defaultStringId, formatArgs), formatArgs);
    }

    public boolean isDpcDownloaded() {
        Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
                MANAGE_PROFILE_AND_DEVICE_OWNERS));

        ContentResolver cr = mContext.getContentResolver();

        return mInjector.binderWithCleanCallingIdentity(() -> Settings.Secure.getIntForUser(
                cr, MANAGED_PROVISIONING_DPC_DOWNLOADED,
                /* def= */ 0, /* userHandle= */ cr.getUserId())
                == 1);
    }

    public void setDpcDownloaded(boolean downloaded) {
        Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
                MANAGE_PROFILE_AND_DEVICE_OWNERS));

        int setTo = downloaded ? 1 : 0;

        mInjector.binderWithCleanCallingIdentity(() -> Settings.Secure.putInt(
                mContext.getContentResolver(), MANAGED_PROVISIONING_DPC_DOWNLOADED, setTo));
    }

    @Override
    public void resetShouldAllowBypassingDevicePolicyManagementRoleQualificationState() {
        Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
                android.Manifest.permission.MANAGE_ROLE_HOLDERS));
        setBypassDevicePolicyManagementRoleQualificationStateInternal(
                /* currentRoleHolder= */ null, /* allowBypass= */ false);
    }

    @Override
    public boolean shouldAllowBypassingDevicePolicyManagementRoleQualification() {
        Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
                android.Manifest.permission.MANAGE_ROLE_HOLDERS));
        return mInjector.binderWithCleanCallingIdentity(() -> {
            if (getUserData(
                    UserHandle.USER_SYSTEM).mBypassDevicePolicyManagementRoleQualifications) {
                return true;
            }
            return shouldAllowBypassingDevicePolicyManagementRoleQualificationInternal();
        });
    }

    private boolean shouldAllowBypassingDevicePolicyManagementRoleQualificationInternal() {
        if (nonTestNonPrecreatedUsersExist()) {
            return false;
        }


        return !hasIncompatibleAccountsOnAnyUser();
    }

    private boolean hasAccountsOnAnyUser() {
        long callingIdentity = Binder.clearCallingIdentity();
        try {
            for (UserInfo user : mUserManagerInternal.getUsers(/* excludeDying= */ true)) {
                AccountManager am = mContext.createContextAsUser(
                                UserHandle.of(user.id), /* flags= */ 0)
                        .getSystemService(AccountManager.class);
                Account[] accounts = am.getAccounts();
                if (accounts.length != 0) {
                    return true;
                }
            }

            return false;
        } finally {
            Binder.restoreCallingIdentity(callingIdentity);
        }
    }

    private void setBypassDevicePolicyManagementRoleQualificationStateInternal(
            String currentRoleHolder, boolean allowBypass) {
        boolean stateChanged = false;
        DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
        if (policy.mBypassDevicePolicyManagementRoleQualifications != allowBypass) {
            policy.mBypassDevicePolicyManagementRoleQualifications = allowBypass;
            stateChanged = true;
        }
        if (!Objects.equals(currentRoleHolder, policy.mCurrentRoleHolder)) {
            policy.mCurrentRoleHolder = currentRoleHolder;
            stateChanged = true;
        }
        if (stateChanged) {
            synchronized (getLockObject()) {
                saveSettingsLocked(UserHandle.USER_SYSTEM);
            }
        }
    }

    private final class DevicePolicyManagementRoleObserver implements OnRoleHoldersChangedListener {
        private RoleManager mRm;
        private final Executor mExecutor;
        private final Context mContext;

        DevicePolicyManagementRoleObserver(@NonNull Context context) {
            mContext = context;
            mExecutor = mContext.getMainExecutor();
            mRm = mContext.getSystemService(RoleManager.class);
        }

        public void register() {
            mRm.addOnRoleHoldersChangedListenerAsUser(mExecutor, this, UserHandle.ALL);
        }

        @Override
        public void onRoleHoldersChanged(@NonNull String roleName, @NonNull UserHandle user) {
            mDevicePolicyEngine.handleRoleChanged(roleName, user.getIdentifier());
            if (RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT.equals(roleName)) {
                handleDevicePolicyManagementRoleChange(user);
                return;
            }
            if (RoleManager.ROLE_FINANCED_DEVICE_KIOSK.equals(roleName)) {
                handleFinancedDeviceKioskRoleChange();
                return;
            }
        }

        private void handleDevicePolicyManagementRoleChange(UserHandle user) {
            String newRoleHolder = getDeviceManagementRoleHolder(user);
            if (isDefaultRoleHolder(newRoleHolder)) {
                Slogf.i(LOG_TAG,
                        "onRoleHoldersChanged: Default role holder is set, returning early");
                return;
            }
            if (newRoleHolder == null) {
                Slogf.i(LOG_TAG,
                        "onRoleHoldersChanged: New role holder is null, returning early");
                return;
            }
            if (shouldAllowBypassingDevicePolicyManagementRoleQualificationInternal()) {
                Slogf.w(LOG_TAG,
                        "onRoleHoldersChanged: Updating current role holder to " + newRoleHolder);
                setBypassDevicePolicyManagementRoleQualificationStateInternal(
                        newRoleHolder, /* allowBypass= */ true);
                return;
            }
            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
            if (!newRoleHolder.equals(policy.mCurrentRoleHolder)) {
                Slogf.w(LOG_TAG,
                        "onRoleHoldersChanged: You can't set a different role holder, role "
                                + "is getting revoked from " + newRoleHolder);
                setBypassDevicePolicyManagementRoleQualificationStateInternal(
                        /* currentRoleHolder= */ null, /* allowBypass= */ false);
                mRm.removeRoleHolderAsUser(
                        RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT,
                        newRoleHolder,
                        /* flags= */ 0,
                        user,
                        mExecutor,
                        successful -> {});
            }
        }

        private void handleFinancedDeviceKioskRoleChange() {
            Slog.i(LOG_TAG, "Handling action " + ACTION_DEVICE_FINANCING_STATE_CHANGED);
            Intent intent = new Intent(ACTION_DEVICE_FINANCING_STATE_CHANGED);
            mInjector.binderWithCleanCallingIdentity(() -> {
                for (UserInfo userInfo : mUserManager.getUsers()) {
                    UserHandle user = userInfo.getUserHandle();
                    broadcastExplicitIntentToRoleHolder(
                            intent, RoleManager.ROLE_SYSTEM_SUPERVISION, user);
                    broadcastExplicitIntentToRoleHolder(
                            intent, RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT, user);
                    ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(user.getIdentifier());
                    if (admin == null) {
                        continue;
                    }
                    if (!isProfileOwnerOfOrganizationOwnedDevice(
                            admin.info.getComponent(), user.getIdentifier())
                            && !isDeviceOwner(admin)
                            && !(isProfileOwner(admin.info.getComponent(), user.getIdentifier())
                            && admin.getUserHandle().isSystem())) {
                        continue;
                    }
                    // Don't send the broadcast twice if the DPC is the same package as the
                    // DMRH
                    if (admin.info.getPackageName().equals(getDeviceManagementRoleHolder(user))) {
                        continue;
                    }
                    broadcastExplicitIntentToPackage(
                            intent, admin.info.getPackageName(), admin.getUserHandle());
                }
            });
        }

        private String getDeviceManagementRoleHolder(UserHandle user) {
            return DevicePolicyManagerService.this.getRoleHolderPackageNameOnUser(
                    mContext, RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT, user);
        }

        private boolean isDefaultRoleHolder(String packageName) {
            String defaultRoleHolder = getDefaultRoleHolderPackageName();
            if (packageName == null || defaultRoleHolder == null) {
                return false;
            }
            if (!defaultRoleHolder.equals(packageName)) {
                return false;
            }
            return hasSigningCertificate(
                    packageName, getDefaultRoleHolderPackageSignature());
        }

        private boolean hasSigningCertificate(String packageName, String  certificateString) {
            if (packageName == null || certificateString == null) {
                return false;
            }
            byte[] certificate;
            try {
                certificate = new Signature(certificateString).toByteArray();
            } catch (IllegalArgumentException e) {
                Slogf.w(LOG_TAG, "Cannot parse signing certificate: " + certificateString, e);
                return false;
            }
            PackageManager pm = mInjector.getPackageManager();
            return pm.hasSigningCertificate(
                    packageName, certificate, PackageManager.CERT_INPUT_SHA256);
        }

        private String getDefaultRoleHolderPackageName() {
            String[] info = getDefaultRoleHolderPackageNameAndSignature();
            if (info == null) {
                return null;
            }
            return info[0];
        }

        private String getDefaultRoleHolderPackageSignature() {
            String[] info = getDefaultRoleHolderPackageNameAndSignature();
            if (info == null || info.length < 2) {
                return null;
            }
            return info[1];
        }

        private String[] getDefaultRoleHolderPackageNameAndSignature() {
            String packageNameAndSignature = mContext.getString(
                    com.android.internal.R.string.config_devicePolicyManagement);
            if (TextUtils.isEmpty(packageNameAndSignature)) {
                return null;
            }
            if (packageNameAndSignature.contains(":")) {
                return packageNameAndSignature.split(":");
            }
            return new String[]{packageNameAndSignature};
        }
    }

    private void broadcastExplicitIntentToRoleHolder(
            Intent intent, String role, UserHandle userHandle) {
        String packageName = getRoleHolderPackageNameOnUser(mContext, role, userHandle);
        if (packageName == null) {
            return;
        }
        broadcastExplicitIntentToPackage(intent, packageName, userHandle);
    }

    private void broadcastExplicitIntentToPackage(
            Intent intent, String packageName, UserHandle userHandle) {
        int userId = userHandle.getIdentifier();
        if (packageName == null) {
            return;
        }
        Intent packageIntent = new Intent(intent)
                .setPackage(packageName);
        List<ResolveInfo> receivers = mContext.getPackageManager().queryBroadcastReceiversAsUser(
                packageIntent,
                PackageManager.ResolveInfoFlags.of(PackageManager.GET_RECEIVERS),
                userId);
        if (receivers.isEmpty()) {
            Slog.i(LOG_TAG, "Found no receivers to handle intent " + intent
                    + " in package " + packageName);
            return;
        }
        for (ResolveInfo receiver : receivers) {
            Intent componentIntent = new Intent(packageIntent)
                    .setComponent(receiver.getComponentInfo().getComponentName())
                    .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
            mContext.sendBroadcastAsUser(componentIntent, userHandle);
        }
    }

    @Override
    public List<UserHandle> getPolicyManagedProfiles(@NonNull UserHandle user) {
        Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
                MANAGE_PROFILE_AND_DEVICE_OWNERS));
        int userId = user.getIdentifier();
        return mInjector.binderWithCleanCallingIdentity(() -> {
            List<UserInfo> userProfiles = mUserManager.getProfiles(userId);
            List<UserHandle> result = new ArrayList<>();
            for (int i = 0; i < userProfiles.size(); i++) {
                UserInfo userInfo = userProfiles.get(i);
                if (userInfo.isManagedProfile() && hasProfileOwner(userInfo.id)) {
                    result.add(new UserHandle(userInfo.id));
                }
            }
            return result;
        });
    }

    // Permission that will need to be created in V.
    private static final String MANAGE_DEVICE_POLICY_BLOCK_UNINSTALL =
            "manage_device_policy_block_uninstall";
    private static final String MANAGE_DEVICE_POLICY_CAMERA_TOGGLE =
            "manage_device_policy_camera_toggle";
    private static final String MANAGE_DEVICE_POLICY_MICROPHONE_TOGGLE =
            "manage_device_policy_microphone_toggle";

    // DPC types
    private static final int NOT_A_DPC = -1;
    private static final int DEFAULT_DEVICE_OWNER = 0;
    private static final int FINANCED_DEVICE_OWNER = 1;
    private static final int PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE = 2;
    private static final int PROFILE_OWNER_ON_USER_0 = 3;
    private static final int PROFILE_OWNER = 4;
    private static final int PROFILE_OWNER_ON_USER = 5;
    private static final int AFFILIATED_PROFILE_OWNER_ON_USER = 6;
    // DPC types
    @IntDef(value = {
            NOT_A_DPC,
            DEFAULT_DEVICE_OWNER,
            FINANCED_DEVICE_OWNER,
            PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE,
            PROFILE_OWNER_ON_USER_0,
            PROFILE_OWNER,
            PROFILE_OWNER_ON_USER,
            AFFILIATED_PROFILE_OWNER_ON_USER
    })
    private @interface DpcType {}

    // Permissions of existing DPC types.
    private static final List<String> DEFAULT_DEVICE_OWNER_PERMISSIONS = List.of(
            MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT,
            MANAGE_DEVICE_POLICY_ACROSS_USERS,
            MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL,
            MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL,
            MANAGE_DEVICE_POLICY_AIRPLANE_MODE,
            MANAGE_DEVICE_POLICY_APPS_CONTROL,
            MANAGE_DEVICE_POLICY_APP_RESTRICTIONS,
            MANAGE_DEVICE_POLICY_AUDIO_OUTPUT,
            MANAGE_DEVICE_POLICY_AUTOFILL,
            MANAGE_DEVICE_POLICY_BLUETOOTH,
            MANAGE_DEVICE_POLICY_CALLS,
            MANAGE_DEVICE_POLICY_CAMERA,
            MANAGE_DEVICE_POLICY_CERTIFICATES,
            MANAGE_DEVICE_POLICY_COMMON_CRITERIA_MODE,
            MANAGE_DEVICE_POLICY_DEBUGGING_FEATURES,
            MANAGE_DEVICE_POLICY_DEFAULT_SMS,
            MANAGE_DEVICE_POLICY_DISPLAY,
            MANAGE_DEVICE_POLICY_FACTORY_RESET,
            MANAGE_DEVICE_POLICY_FUN,
            MANAGE_DEVICE_POLICY_INPUT_METHODS,
            MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES,
            MANAGE_DEVICE_POLICY_KEYGUARD,
            MANAGE_DEVICE_POLICY_LOCALE,
            MANAGE_DEVICE_POLICY_LOCATION,
            MANAGE_DEVICE_POLICY_LOCK,
            MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
            MANAGE_DEVICE_POLICY_LOCK_TASK,
            MANAGE_DEVICE_POLICY_MICROPHONE,
            MANAGE_DEVICE_POLICY_MOBILE_NETWORK,
            MANAGE_DEVICE_POLICY_MODIFY_USERS,
            MANAGE_DEVICE_POLICY_MTE,
            MANAGE_DEVICE_POLICY_NEARBY_COMMUNICATION,
            MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY,
            MANAGE_DEVICE_POLICY_PACKAGE_STATE,
            MANAGE_DEVICE_POLICY_PHYSICAL_MEDIA,
            MANAGE_DEVICE_POLICY_PRINTING,
            MANAGE_DEVICE_POLICY_PROFILES,
            MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
            MANAGE_DEVICE_POLICY_RESET_PASSWORD,
            MANAGE_DEVICE_POLICY_RESTRICT_PRIVATE_DNS,
            MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS,
            MANAGE_DEVICE_POLICY_SAFE_BOOT,
            MANAGE_DEVICE_POLICY_SCREEN_CAPTURE,
            MANAGE_DEVICE_POLICY_SCREEN_CONTENT,
            MANAGE_DEVICE_POLICY_SECURITY_LOGGING,
            MANAGE_DEVICE_POLICY_SMS,
            MANAGE_DEVICE_POLICY_STATUS_BAR,
            MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE,
            MANAGE_DEVICE_POLICY_SYSTEM_DIALOGS,
            MANAGE_DEVICE_POLICY_SYSTEM_UPDATES,
            MANAGE_DEVICE_POLICY_TIME,
            MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING,
            MANAGE_DEVICE_POLICY_USB_FILE_TRANSFER,
            MANAGE_DEVICE_POLICY_VPN,
            MANAGE_DEVICE_POLICY_WALLPAPER,
            MANAGE_DEVICE_POLICY_WIFI,
            MANAGE_DEVICE_POLICY_WINDOWS,
            MANAGE_DEVICE_POLICY_WIPE_DATA,
            SET_TIME,
            SET_TIME_ZONE
    );
    private static final List<String> FINANCED_DEVICE_OWNER_PERMISSIONS = List.of(
            MANAGE_DEVICE_POLICY_ACROSS_USERS,
            MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL,
            MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL,
            MANAGE_DEVICE_POLICY_APPS_CONTROL,
            MANAGE_DEVICE_POLICY_CALLS,
            MANAGE_DEVICE_POLICY_DEBUGGING_FEATURES,
            MANAGE_DEVICE_POLICY_FACTORY_RESET,
            MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES,
            MANAGE_DEVICE_POLICY_KEYGUARD,
            MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
            MANAGE_DEVICE_POLICY_LOCK_TASK,
            MANAGE_DEVICE_POLICY_MODIFY_USERS,
            MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY,
            MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS,
            MANAGE_DEVICE_POLICY_SAFE_BOOT,
            MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE,
            MANAGE_DEVICE_POLICY_TIME,
            MANAGE_DEVICE_POLICY_WIPE_DATA
    );

    /**
     * All the permissions granted to a profile owner.
     */
    private static final List<String> PROFILE_OWNER_PERMISSIONS  =
            List.of(
                    MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT,
                    MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL,
                    MANAGE_DEVICE_POLICY_APPS_CONTROL,
                    MANAGE_DEVICE_POLICY_APP_RESTRICTIONS,
                    MANAGE_DEVICE_POLICY_AUDIO_OUTPUT,
                    MANAGE_DEVICE_POLICY_AUTOFILL,
                    MANAGE_DEVICE_POLICY_BLUETOOTH,
                    MANAGE_DEVICE_POLICY_CALLS,
                    MANAGE_DEVICE_POLICY_CAMERA,
                    MANAGE_DEVICE_POLICY_CERTIFICATES,
                    MANAGE_DEVICE_POLICY_DEBUGGING_FEATURES,
                    MANAGE_DEVICE_POLICY_DISPLAY,
                    MANAGE_DEVICE_POLICY_FACTORY_RESET,
                    MANAGE_DEVICE_POLICY_INPUT_METHODS,
                    MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES,
                    MANAGE_DEVICE_POLICY_KEYGUARD,
                    MANAGE_DEVICE_POLICY_LOCALE,
                    MANAGE_DEVICE_POLICY_LOCATION,
                    MANAGE_DEVICE_POLICY_LOCK,
                    MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
                    MANAGE_DEVICE_POLICY_CERTIFICATES,
                    MANAGE_DEVICE_POLICY_NEARBY_COMMUNICATION,
                    MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY,
                    MANAGE_DEVICE_POLICY_PACKAGE_STATE,
                    MANAGE_DEVICE_POLICY_PRINTING,
                    MANAGE_DEVICE_POLICY_PROFILES,
                    MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
                    MANAGE_DEVICE_POLICY_RESET_PASSWORD,
                    MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS,
                    MANAGE_DEVICE_POLICY_SCREEN_CAPTURE,
                    MANAGE_DEVICE_POLICY_SCREEN_CONTENT,
                    MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE,
                    MANAGE_DEVICE_POLICY_SYSTEM_DIALOGS,
                    MANAGE_DEVICE_POLICY_TIME,
                    MANAGE_DEVICE_POLICY_VPN,
                    MANAGE_DEVICE_POLICY_WIPE_DATA
            );

    /**
     * All the additional permissions granted to an organisation owned profile owner.
     */
    private static final List<String>
            ADDITIONAL_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE_PERMISSIONS =
            List.of(
                    MANAGE_DEVICE_POLICY_ACROSS_USERS,
                    MANAGE_DEVICE_POLICY_AIRPLANE_MODE,
                    MANAGE_DEVICE_POLICY_APPS_CONTROL,
                    MANAGE_DEVICE_POLICY_COMMON_CRITERIA_MODE,
                    MANAGE_DEVICE_POLICY_DEFAULT_SMS,
                    MANAGE_DEVICE_POLICY_LOCALE,
                    MANAGE_DEVICE_POLICY_MICROPHONE,
                    MANAGE_DEVICE_POLICY_MOBILE_NETWORK,
                    MANAGE_DEVICE_POLICY_MTE,
                    MANAGE_DEVICE_POLICY_NEARBY_COMMUNICATION,
                    MANAGE_DEVICE_POLICY_PHYSICAL_MEDIA,
                    MANAGE_DEVICE_POLICY_RESTRICT_PRIVATE_DNS,
                    MANAGE_DEVICE_POLICY_SAFE_BOOT,
                    MANAGE_DEVICE_POLICY_SECURITY_LOGGING,
                    MANAGE_DEVICE_POLICY_SMS,
                    MANAGE_DEVICE_POLICY_SYSTEM_UPDATES,
                    MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING,
                    MANAGE_DEVICE_POLICY_USB_FILE_TRANSFER,
                    MANAGE_DEVICE_POLICY_WIFI,
                    SET_TIME,
                    SET_TIME_ZONE
            );

    /**
     * All the additional permissions granted to a Profile Owner on user 0.
     */
    private static final List<String> ADDITIONAL_PROFILE_OWNER_ON_USER_0_PERMISSIONS =
            List.of(
                    MANAGE_DEVICE_POLICY_AIRPLANE_MODE,
                    MANAGE_DEVICE_POLICY_DISPLAY,
                    MANAGE_DEVICE_POLICY_FUN,
                    MANAGE_DEVICE_POLICY_LOCK_TASK,
                    MANAGE_DEVICE_POLICY_MOBILE_NETWORK,
                    MANAGE_DEVICE_POLICY_MODIFY_USERS,
                    MANAGE_DEVICE_POLICY_PHYSICAL_MEDIA,
                    MANAGE_DEVICE_POLICY_PRINTING,
                    MANAGE_DEVICE_POLICY_PROFILES,
                    MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
                    MANAGE_DEVICE_POLICY_SAFE_BOOT,
                    MANAGE_DEVICE_POLICY_SMS,
                    MANAGE_DEVICE_POLICY_SYSTEM_DIALOGS,
                    MANAGE_DEVICE_POLICY_USB_FILE_TRANSFER,
                    MANAGE_DEVICE_POLICY_WINDOWS,
                    SET_TIME,
                    SET_TIME_ZONE
            );

    /**
     * All the additional permissions granted to a Profile Owner on an unaffiliated user.
     */
    private static final List<String> ADDITIONAL_PROFILE_OWNER_ON_USER_PERMISSIONS =
            List.of(
                    MANAGE_DEVICE_POLICY_LOCK_TASK
            );

    /**
     * All the additional permissions granted to a Profile Owner on an affiliated user.
     */
    private static final List<String> ADDITIONAL_AFFILIATED_PROFILE_OWNER_ON_USER_PERMISSIONS =
            List.of(
                    MANAGE_DEVICE_POLICY_STATUS_BAR
            );

    /**
     * Combination of {@link PROFILE_OWNER_PERMISSIONS} and
     * {@link ADDITIONAL_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE_PERMISSIONS}.
     */
    private static final List<String> PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE_PERMISSIONS =
            new ArrayList();

    /**
     * Combination of {@link PROFILE_OWNER_PERMISSIONS} and
     * {@link ADDITIONAL_PROFILE_OWNER_ON_USER_0_PERMISSIONS}.
     */
    private static final List<String> PROFILE_OWNER_ON_USER_0_PERMISSIONS  =
            new ArrayList();

    /**
     * Combination of {@link PROFILE_OWNER_PERMISSIONS} and
     * {@link ADDITIONAL_AFFILIATED_PROFIL_OWNER_ON_USER_PERMISSIONS}.
     */
    private static final List<String> AFFILIATED_PROFILE_OWNER_ON_USER_PERMISSIONS =
            new ArrayList();

    /**
     * Combination of {@link PROFILE_OWNER_PERMISSIONS} and
     * {@link ADDITIONAL_PROFILE_OWNER_ON_USER_PERMISSIONS}.
     */
    private static final List<String> PROFILE_OWNER_ON_USER_PERMISSIONS =
            new ArrayList();


    private static final HashMap<Integer, List<String>> DPC_PERMISSIONS = new HashMap<>();
    {
        // Organisation owned profile owners have all the permission of a profile owner plus
        // some extra permissions.
        PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE_PERMISSIONS.addAll(PROFILE_OWNER_PERMISSIONS);
        PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE_PERMISSIONS.addAll(
                ADDITIONAL_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE_PERMISSIONS);
        // Profile owners on user 0 have all the permission of a profile owner plus
        // some extra permissions.
        PROFILE_OWNER_ON_USER_0_PERMISSIONS.addAll(PROFILE_OWNER_PERMISSIONS);
        PROFILE_OWNER_ON_USER_0_PERMISSIONS.addAll(ADDITIONAL_PROFILE_OWNER_ON_USER_0_PERMISSIONS);
        // Profile owners on users have all the permission of a profile owner plus
        // some extra permissions.
        PROFILE_OWNER_ON_USER_PERMISSIONS.addAll(PROFILE_OWNER_PERMISSIONS);
        PROFILE_OWNER_ON_USER_PERMISSIONS.addAll(
                ADDITIONAL_PROFILE_OWNER_ON_USER_PERMISSIONS);
        // Profile owners on affiliated users have all the permission of a profile owner on a user
        // plus some extra permissions.
        AFFILIATED_PROFILE_OWNER_ON_USER_PERMISSIONS.addAll(PROFILE_OWNER_ON_USER_PERMISSIONS);
        AFFILIATED_PROFILE_OWNER_ON_USER_PERMISSIONS.addAll(
                ADDITIONAL_AFFILIATED_PROFILE_OWNER_ON_USER_PERMISSIONS);

        DPC_PERMISSIONS.put(DEFAULT_DEVICE_OWNER, DEFAULT_DEVICE_OWNER_PERMISSIONS);
        DPC_PERMISSIONS.put(FINANCED_DEVICE_OWNER, FINANCED_DEVICE_OWNER_PERMISSIONS);
        DPC_PERMISSIONS.put(PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE,
                PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE_PERMISSIONS);
        DPC_PERMISSIONS.put(PROFILE_OWNER_ON_USER_0, PROFILE_OWNER_ON_USER_0_PERMISSIONS);
        DPC_PERMISSIONS.put(PROFILE_OWNER, PROFILE_OWNER_PERMISSIONS);
        DPC_PERMISSIONS.put(PROFILE_OWNER_ON_USER, PROFILE_OWNER_ON_USER_PERMISSIONS);
        DPC_PERMISSIONS.put(AFFILIATED_PROFILE_OWNER_ON_USER,
                AFFILIATED_PROFILE_OWNER_ON_USER_PERMISSIONS);
    }
    //Map of Permission to Delegate Scope.
    private static final HashMap<String, String> DELEGATE_SCOPES = new HashMap<>();
    {
        DELEGATE_SCOPES.put(MANAGE_DEVICE_POLICY_APP_RESTRICTIONS, DELEGATION_APP_RESTRICTIONS);
        DELEGATE_SCOPES.put(MANAGE_DEVICE_POLICY_BLOCK_UNINSTALL, DELEGATION_BLOCK_UNINSTALL);
        DELEGATE_SCOPES.put(MANAGE_DEVICE_POLICY_CERTIFICATES, DELEGATION_CERT_INSTALL);
        DELEGATE_SCOPES.put(MANAGE_DEVICE_POLICY_PACKAGE_STATE, DELEGATION_PACKAGE_ACCESS);
        DELEGATE_SCOPES.put(MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS, DELEGATION_PERMISSION_GRANT);
        DELEGATE_SCOPES.put(MANAGE_DEVICE_POLICY_SECURITY_LOGGING, DELEGATION_SECURITY_LOGGING);
    }

    private static final HashMap<String, String> CROSS_USER_PERMISSIONS =
            new HashMap<>();
    {
        // The permissions are all intrinsically global and therefore have no cross-user permission.
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_FACTORY_RESET, null);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_MTE, null);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SECURITY_LOGGING, null);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_STATUS_BAR, null);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SYSTEM_UPDATES, null);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING, null);
        CROSS_USER_PERMISSIONS.put(SET_TIME, null);
        CROSS_USER_PERMISSIONS.put(SET_TIME_ZONE, null);

        // The permissions are all critical for securing data within the current user and
        // therefore are protected with MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL for
        // cross-user calls.
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_KEYGUARD,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL);

        // These permissions are required for securing device ownership without accessing user data
        // and therefore are protected with MANAGE_DEVICE_POLICY_ACROSS_USERS for cross-user calls.
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT,
                MANAGE_DEVICE_POLICY_ACROSS_USERS);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_AIRPLANE_MODE,
                MANAGE_DEVICE_POLICY_ACROSS_USERS);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_BLUETOOTH,
                MANAGE_DEVICE_POLICY_ACROSS_USERS);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_CALLS,
                MANAGE_DEVICE_POLICY_ACROSS_USERS);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_CAMERA,
                MANAGE_DEVICE_POLICY_ACROSS_USERS);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_DEFAULT_SMS,
                MANAGE_DEVICE_POLICY_ACROSS_USERS);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_INPUT_METHODS,
                MANAGE_DEVICE_POLICY_ACROSS_USERS);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_MICROPHONE,
                MANAGE_DEVICE_POLICY_ACROSS_USERS);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_MOBILE_NETWORK,
                MANAGE_DEVICE_POLICY_ACROSS_USERS);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_NEARBY_COMMUNICATION,
                MANAGE_DEVICE_POLICY_ACROSS_USERS);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_PHYSICAL_MEDIA,
                MANAGE_DEVICE_POLICY_ACROSS_USERS);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_PACKAGE_STATE,
                MANAGE_DEVICE_POLICY_ACROSS_USERS);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_RESTRICT_PRIVATE_DNS,
                MANAGE_DEVICE_POLICY_ACROSS_USERS);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SCREEN_CAPTURE,
                MANAGE_DEVICE_POLICY_ACROSS_USERS);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SMS,
                MANAGE_DEVICE_POLICY_ACROSS_USERS);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SAFE_BOOT,
                MANAGE_DEVICE_POLICY_ACROSS_USERS);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_TIME,
                MANAGE_DEVICE_POLICY_ACROSS_USERS);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_USB_FILE_TRANSFER,
                MANAGE_DEVICE_POLICY_ACROSS_USERS);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_WIFI,
                MANAGE_DEVICE_POLICY_ACROSS_USERS);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_WIPE_DATA,
                MANAGE_DEVICE_POLICY_ACROSS_USERS);

        // These permissions may grant access to user data and therefore must be protected with
        // MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL for cross-user calls.
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_APPS_CONTROL,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_APP_RESTRICTIONS,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_AUDIO_OUTPUT,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_AUTOFILL,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_BLOCK_UNINSTALL,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_CAMERA_TOGGLE,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_COMMON_CRITERIA_MODE,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_DEBUGGING_FEATURES,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_DISPLAY,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_FUN,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_LOCALE,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_LOCATION,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_LOCK,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_LOCK_TASK,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_MODIFY_USERS,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_MICROPHONE_TOGGLE,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_PROFILES,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_PRINTING,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_RESET_PASSWORD,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SCREEN_CONTENT,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SYSTEM_DIALOGS,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_VPN,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_WALLPAPER,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
        CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_WINDOWS,
                MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
    }

    /**
     * Checks if the calling process has been granted permission to apply a device policy on a
     * specific user. Only one permission provided in the list needs to be granted to pass this
     * check.
     * The given permissions will be checked along with their associated cross-user permissions if
     * they exists and the target user is different to the calling user.
     * Returns an {@link EnforcingAdmin} for the caller.
     *
     * @param admin the component name of the admin.
     * @param callerPackageName The package name of the calling application.
     * @param permissions an array of permission names to be checked.
     * @param targetUserId The userId of the user which the caller needs permission to act on.
     * @throws SecurityException if the caller has not been granted the given permission,
     * the associated cross-user permission if the caller's user is different to the target user.
     */
    private EnforcingAdmin enforcePermissionsAndGetEnforcingAdmin(@Nullable ComponentName admin,
            String[] permissions, String callerPackageName, int targetUserId) {
        enforcePermissions(permissions, callerPackageName, targetUserId);
        return getEnforcingAdminForCaller(admin, callerPackageName);
    }

    /**
     * Checks if the calling process has been granted permission to apply a device policy on a
     * specific user.
     * The given permission will be checked along with its associated cross-user permission if it
     * exists and the target user is different to the calling user.
     * Returns an {@link EnforcingAdmin} for the caller.
     *
     * @param admin the component name of the admin.
     * @param callerPackageName The package name of the calling application.
     * @param permission The name of the permission being checked.
     * @param targetUserId The userId of the user which the caller needs permission to act on.
     * @throws SecurityException if the caller has not been granted the given permission,
     * the associated cross-user permission if the caller's user is different to the target user.
     */
    private EnforcingAdmin enforcePermissionAndGetEnforcingAdmin(@Nullable ComponentName admin,
            String permission, String callerPackageName, int targetUserId) {
        enforcePermission(permission, callerPackageName, targetUserId);
        return getEnforcingAdminForCaller(admin, callerPackageName);
    }

    /**
     * Checks if the calling process has been granted permission to apply a device policy on a
     * specific user.
     * The given permission will be checked along with its associated cross-user permission if it
     * exists and the target user is different to the calling user.
     * Returns an {@link EnforcingAdmin} for the caller.
     *
     * @param admin the component name of the admin.
     * @param callerPackageName The package name  of the calling application.
     * @param permission The name of the permission being checked.
     * @param deviceAdminPolicy The userId of the user which the caller needs permission to act on.
     * @throws SecurityException if the caller has not been granted the given permission,
     * the associated cross-user permission if the caller's user is different to the target user.
     */
    private EnforcingAdmin enforcePermissionAndGetEnforcingAdmin(@Nullable ComponentName admin,
            String permission, int deviceAdminPolicy, String callerPackageName, int targetUserId) {
        enforcePermission(permission, deviceAdminPolicy, callerPackageName, targetUserId);
        return getEnforcingAdminForCaller(admin, callerPackageName);
    }

    /**
     * Checks if the calling process has been granted permission to apply a device policy on a
     * specific user.  Only one permission provided in the list needs to be granted to pass this
     * check.
     * The given permissions will be checked along with their associated cross-user permissions if
     * they exist and the target user is different to the calling user.
     * Returns an {@link EnforcingAdmin} for the caller.
     *
     * @param admin the component name of the admin.
     * @param callerPackageName The package name of the calling application.
     * @param permissions The names of the permissions being checked.
     * @param deviceAdminPolicy The userId of the user which the caller needs permission to act on.
     * @throws SecurityException if the caller has not been granted the given permission,
     * the associated cross-user permission if the caller's user is different to the target user.
     */
    private EnforcingAdmin enforcePermissionsAndGetEnforcingAdmin(@Nullable ComponentName admin,
            String[] permissions, int deviceAdminPolicy, String callerPackageName,
            int targetUserId) {
        enforcePermissions(permissions, deviceAdminPolicy, callerPackageName, targetUserId);
        return getEnforcingAdminForCaller(admin, callerPackageName);
    }

    /**
     * Checks whether the calling process has been granted permission to query a device policy on
     * a specific user.
     * The given permission will be checked along with its associated cross-user permission if it
     * exists and the target user is different to the calling user.
     *
     * @param permission The name of the permission being checked.
     * @param targetUserId The userId of the user which the caller needs permission to act on.
     * @throws SecurityException if the caller has not been granted the given permission,
     * the associated cross-user permission if the caller's user is different to the target user.
     */
    private EnforcingAdmin enforceCanQueryAndGetEnforcingAdmin(@Nullable ComponentName admin,
            String permission, String callerPackageName, int targetUserId) {
        enforceCanQuery(permission, callerPackageName, targetUserId);
        return getEnforcingAdminForCaller(admin, callerPackageName);
    }

    private static final HashMap<String, String> POLICY_IDENTIFIER_TO_PERMISSION = new HashMap<>();
    {
        POLICY_IDENTIFIER_TO_PERMISSION.put(AUTO_TIMEZONE_POLICY, SET_TIME_ZONE);
    }

    private static final HashMap<String, Integer> POLICY_IDENTIFIER_TO_ACTIVE_ADMIN_POLICY =
            new HashMap<>();

    /**
     * Checks if the calling process has been granted permission to apply a device policy.
     *
     * @param callerPackageName The package name  of the calling application.
     * @param permission The name of the permission being checked.
     * @throws SecurityException if the caller has not been granted the given permission,
     * the associated cross-user permission if the caller's user is different to the target user.
     */
    private void enforcePermission(String permission, String callerPackageName)
            throws SecurityException {
        if (!hasPermission(permission, callerPackageName)) {
            throw new SecurityException("Caller does not have the required permissions for "
                    + "this user. Permission required: "
                    + permission
                    + ".");
        }
    }


    /**
     * Checks if the calling process has been granted permission to apply a device policy on a
     * specific user. Only one permission provided in the list needs to be granted to pass this
     * check.
     * The given permissions will be checked along with their associated cross-user permissions if
     * they exists and the target user is different to the calling user.
     *
     * @param callerPackageName The package name  of the calling application.
     * @param permissions The names of the permissions being checked.
     * @param targetUserId The userId of the user which the caller needs permission to act on.
     * @throws SecurityException if the caller has not been granted the given permission,
     * the associated cross-user permission if the caller's user is different to the target user.
     */
    private void enforcePermission(String permission, String callerPackageName, int targetUserId)
            throws SecurityException {
        enforcePermission(permission, callerPackageName);
        if (targetUserId != getCallerIdentity(callerPackageName).getUserId()) {
            enforcePermission(CROSS_USER_PERMISSIONS.get(permission), callerPackageName);
        }
    }

    /**
     * Checks if the calling process has been granted permission to apply a device policy on a
     * specific user. Only one of the given permissions will be required to be held to pass this
     * check.
     * The given permissions will be checked along with their associated cross-user permissions if
     * they exist and the target user is different to the calling user.
     *
     * @param permissions An array of the names of the permissions being checked.
     * @param callerPackageName The package name  of the calling application.
     * @param targetUserId The userId of the user which the caller needs permission to act on.
     * @throws SecurityException if the caller has not been granted the given permission,
     * the associated cross-user permission if the caller's user is different to the target user.
     */
    private void enforcePermissions(String[] permissions, String callerPackageName,
            int targetUserId) throws SecurityException {
        String heldPermission = "";
        for (String permission : permissions) {
            if (hasPermission(permission, callerPackageName)) {
                heldPermission = permission;
                break;
            }
        }
        if (heldPermission.isEmpty()) {
            throw new SecurityException("Caller does not have the required permissions for "
                    + "this user. One of the following permission required: "
                    + Arrays.toString(permissions));
        }
        enforcePermission(heldPermission, callerPackageName, targetUserId);
    }

    /**
     * Checks if the calling process has been granted permission to apply a device policy on a
     * specific user.
     * The given permission will be checked along with its associated cross-user permission if it
     * exists and the target user is different to the calling user.
     *
     * @param callerPackageName The package name  of the calling application.
     * @param adminPolicy The admin policy that should grant holders permission.
     * @param permission The name of the permission being checked.
     * @param targetUserId The userId of the user which the caller needs permission to act on.
     * @throws SecurityException if the caller has not been granted the given permission,
     * the associated cross-user permission if the caller's user is different to the target user.
     */
    private void enforcePermission(String permission, int adminPolicy,
            String callerPackageName, int targetUserId) throws SecurityException {
        if (hasAdminPolicy(adminPolicy, callerPackageName)) {
            return;
        }
        enforcePermission(permission, callerPackageName, targetUserId);
    }

    /**
     * Checks if the calling process has been granted permission to apply a device policy on a
     * specific user.
     * The given permission will be checked along with its associated cross-user permission if it
     * exists and the target user is different to the calling user.
     *
     * @param callerPackageName The package name  of the calling application.
     * @param adminPolicy The admin policy that should grant holders permission.
     * @param permissions The names of the permissions being checked.
     * @param targetUserId The userId of the user which the caller needs permission to act on.
     * @throws SecurityException if the caller has not been granted the given permission,
     * the associated cross-user permission if the caller's user is different to the target user.
     */
    private void enforcePermissions(String[] permissions, int adminPolicy,
            String callerPackageName, int targetUserId) throws SecurityException {
        if (hasAdminPolicy(adminPolicy, callerPackageName)
                && mInjector.userHandleGetCallingUserId() == targetUserId) {
            return;
        }
        enforcePermissions(permissions, callerPackageName, targetUserId);
    }

    /**
     * Checks whether the calling process has been granted permission to query a device policy on
     * a specific user.
     * The given permission will be checked along with its associated cross-user permission if it
     * exists and the target user is different to the calling user.
     *
     * @param callerPackageName The package name  of the calling application.
     * @param permission The name of the permission being checked.
     * @param targetUserId The userId of the user which the caller needs permission to act on.
     * @throws SecurityException if the caller has not been granted the given permission,
     * the associated cross-user permission if the caller's user is different to the target user
     * and if the user has not been granted {@link QUERY_ADMIN_POLICY}.
     */
    private void enforceCanQuery(String permission, String callerPackageName, int targetUserId)
            throws SecurityException {
        if (hasPermission(QUERY_ADMIN_POLICY, callerPackageName)) {
            return;
        }
        enforcePermission(permission, callerPackageName, targetUserId);
    }

    private boolean hasAdminPolicy(int adminPolicy, String callerPackageName) {
        CallerIdentity caller = getCallerIdentity(callerPackageName);
        ActiveAdmin deviceAdmin = getActiveAdminWithPolicyForUidLocked(
                null, adminPolicy, caller.getUid());
        return deviceAdmin != null;
    }

    /**
     * Return whether the calling process has been granted permission to apply a device policy on
     * a specific user.
     *
     * @param callerPackageName The package name  of the calling application.
     * @param permission The name of the permission being checked.
     * @param targetUserId The userId of the user which the caller needs permission to act on.
     */
    private boolean hasPermission(String permission, String callerPackageName, int targetUserId) {
        CallerIdentity caller = getCallerIdentity(callerPackageName);
        boolean hasPermissionOnOwnUser = hasPermission(permission, caller.getPackageName());
        boolean hasPermissionOnTargetUser = true;
        if (hasPermissionOnOwnUser && caller.getUserId() != targetUserId) {
            hasPermissionOnTargetUser = hasPermissionOnTargetUser
                    && hasPermission(CROSS_USER_PERMISSIONS.get(permission),
                        caller.getPackageName());
        }

        return hasPermissionOnOwnUser && hasPermissionOnTargetUser;
    }

    /**
     * Return whether the calling process has been granted the given permission.
     *
     * @param callerPackageName The package name  of the calling application.
     * @param permission The name of the permission being checked.
     */
    private boolean hasPermission(String permission, @NonNull String callerPackageName) {
        Objects.requireNonNull(callerPackageName, "callerPackageName is null");
        if (permission == null) {
            return true;
        }

        CallerIdentity caller = getCallerIdentity(callerPackageName);

        // Check if the caller holds the permission
        if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
            return true;
        }
        int dpcType = getDpcType(caller);
        if (dpcType != NOT_A_DPC) {
            return DPC_PERMISSIONS.get(dpcType).contains(permission);
        }
        // Check the permission for the role-holder
        if (isCallerDevicePolicyManagementRoleHolder(caller)) {
            return anyDpcHasPermission(permission, caller.getUserId());
        }
        if (DELEGATE_SCOPES.containsKey(permission)) {
            return isCallerDelegate(caller, DELEGATE_SCOPES.get(permission));
        }
        return false;
    }

    /**
     * Returns whether there is a DPC on the given user that has been granted the given permission.
     *
     * @param permission The name of the permission being checked.
     * @param userId The id of the user to check.
     */
    private boolean anyDpcHasPermission(String permission, int userId) {
        if (mOwners.isDefaultDeviceOwnerUserId(userId)) {
            return DPC_PERMISSIONS.get(DEFAULT_DEVICE_OWNER).contains(permission);
        }
        if (mOwners.isFinancedDeviceOwnerUserId(userId)) {
            return DPC_PERMISSIONS.get(FINANCED_DEVICE_OWNER).contains(permission);
        }
        if (mOwners.isProfileOwnerOfOrganizationOwnedDevice(userId)) {
            return DPC_PERMISSIONS.get(PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE).contains(
                    permission);
        }
        if (userId == 0 && mOwners.hasProfileOwner(0)) {
            return DPC_PERMISSIONS.get(PROFILE_OWNER_ON_USER_0).contains(permission);
        }
        if (mOwners.hasProfileOwner(userId)) {
            return DPC_PERMISSIONS.get(PROFILE_OWNER).contains(permission);
        }
        return false;
    }

    private EnforcingAdmin getEnforcingAdminForCaller(@Nullable ComponentName who,
            String callerPackageName) {
        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
        int userId = caller.getUserId();
        ActiveAdmin admin;
        if (isDeviceOwner(caller) || isProfileOwner(caller) || isCallerDelegate(caller)) {
            ComponentName component;
            synchronized (getLockObject()) {
                if (who != null) {
                    admin = getActiveAdminUncheckedLocked(who, userId);
                    component = who;
                } else {
                    admin = getDeviceOrProfileOwnerAdminLocked(userId);
                    component = admin.info.getComponent();
                }
            }
            return EnforcingAdmin.createEnterpriseEnforcingAdmin(component, userId, admin);
        }
        // Check for non-DPC active admins.
        admin = getActiveAdminForCaller(who, caller);
        if (admin != null) {
            return EnforcingAdmin.createDeviceAdminEnforcingAdmin(admin.info.getComponent(), userId,
                    admin);
        }
        admin = getUserData(userId).createOrGetPermissionBasedAdmin(userId);
        return  EnforcingAdmin.createEnforcingAdmin(caller.getPackageName(), userId, admin);
    }

    private EnforcingAdmin getEnforcingAdminForPackage(@Nullable ComponentName who,
            String packageName, int userId) {
        ActiveAdmin admin;
        if (who != null) {
            if (isDeviceOwner(who, userId) || isProfileOwner(who, userId)) {
                synchronized (getLockObject()) {
                    admin = getActiveAdminUncheckedLocked(who, userId);
                }
                if (admin != null) {
                    return EnforcingAdmin.createEnterpriseEnforcingAdmin(who, userId, admin);
                }
            } else {
                // Check for non-DPC active admins.
                admin = getActiveAdminUncheckedLocked(who, userId);
                if (admin != null) {
                    return EnforcingAdmin.createDeviceAdminEnforcingAdmin(who, userId, admin);
                }
            }
        }

        admin = getUserData(userId).createOrGetPermissionBasedAdmin(userId);
        return  EnforcingAdmin.createEnforcingAdmin(packageName, userId, admin);
    }

    private int getAffectedUser(boolean calledOnParent) {
        int callingUserId = mInjector.userHandleGetCallingUserId();
        return calledOnParent ? getProfileParentId(callingUserId) : callingUserId;
    }

    /**
     * Return the DPC type of the given caller.
     */
    private @DpcType int getDpcType(CallerIdentity caller) {
        // Check the permissions of DPCs
        if (isDefaultDeviceOwner(caller)) {
            return DEFAULT_DEVICE_OWNER;
        }
        if (isFinancedDeviceOwner(caller)) {
            return FINANCED_DEVICE_OWNER;
        }
        if (isProfileOwner(caller)) {
            if (isProfileOwnerOfOrganizationOwnedDevice(caller)) {
                return PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE;
            }
            if (isManagedProfile(caller.getUserId())) {
                return PROFILE_OWNER;
            }
            if (isProfileOwnerOnUser0(caller)) {
                return PROFILE_OWNER_ON_USER_0;
            }
            if (isUserAffiliatedWithDevice(caller.getUserId())) {
                return AFFILIATED_PROFILE_OWNER_ON_USER;
            }
            return PROFILE_OWNER_ON_USER;
        }
        return NOT_A_DPC;
    }

    private boolean isPermissionCheckFlagEnabled() {
        return DeviceConfig.getBoolean(
                NAMESPACE_DEVICE_POLICY_MANAGER,
                PERMISSION_BASED_ACCESS_EXPERIMENT_FLAG,
                DEFAULT_VALUE_PERMISSION_BASED_ACCESS_FLAG);
    }

    private boolean isUnicornFlagEnabled() {
        return false;
    }

    private void unsuspendWorkAppsIfNecessary() {
        synchronized (getLockObject()) {
            DevicePolicyData policyData = getUserDataUnchecked(UserHandle.USER_SYSTEM);
            if (!policyData.mEffectiveKeepProfilesRunning) {
                return;
            }
            policyData.mEffectiveKeepProfilesRunning = false;
            saveSettingsLocked(UserHandle.USER_SYSTEM);
        }

        Slog.w(LOG_TAG, "Work apps may have been paused via suspension previously.");
        unsuspendAppsForQuietProfiles();
    }

    public void setMtePolicy(int flags, String callerPackageName) {
        final Set<Integer> allowedModes =
                Set.of(
                        DevicePolicyManager.MTE_NOT_CONTROLLED_BY_POLICY,
                        DevicePolicyManager.MTE_DISABLED,
                        DevicePolicyManager.MTE_ENABLED);
        Preconditions.checkArgument(
                allowedModes.contains(flags), "Provided mode is not one of the allowed values.");
        // In general, this API should be available when "bootctl_settings_toggle" is set, which
        // signals that there is a control for MTE in the user settings and this API fundamentally
        // is a way for the device admin to override that setting.
        // Allow bootctl_device_policy_manager as an override, e.g. to offer the
        // DevicePolicyManager only without a visible user setting.
        if (!mInjector.systemPropertiesGetBoolean(
                "ro.arm64.memtag.bootctl_device_policy_manager",
                mInjector.systemPropertiesGetBoolean(
                        "ro.arm64.memtag.bootctl_settings_toggle", false))) {
            throw new UnsupportedOperationException("device does not support MTE");
        }
        final CallerIdentity caller = getCallerIdentity(callerPackageName);
        // For now we continue to restrict the DISABLED setting to device owner - we might need
        // another permission for this in future.
        if (flags == DevicePolicyManager.MTE_DISABLED) {
            Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
        }

        if (isPermissionCheckFlagEnabled()) {
            enforcePermission(MANAGE_DEVICE_POLICY_MTE, caller.getPackageName(),
                    UserHandle.USER_ALL);
        } else {
            Preconditions.checkCallAuthorization(
                    isDefaultDeviceOwner(caller)
                            || isProfileOwnerOfOrganizationOwnedDevice(caller));
        }
        synchronized (getLockObject()) {
            ActiveAdmin admin =
                        getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();

            if (admin != null) {
                final String memtagProperty = "arm64.memtag.bootctl";
                if (flags == DevicePolicyManager.MTE_ENABLED) {
                    mInjector.systemPropertiesSet(memtagProperty, "memtag");
                } else if (flags == DevicePolicyManager.MTE_DISABLED) {
                    mInjector.systemPropertiesSet(memtagProperty, "memtag-off");
                }
                admin.mtePolicy = flags;
                saveSettingsLocked(caller.getUserId());

                DevicePolicyEventLogger.createEvent(DevicePolicyEnums.SET_MTE_POLICY)
                        .setInt(flags)
                        .setAdmin(caller.getPackageName())
                        .write();
            }
        }
    }

    @Override
    public int getMtePolicy(String callerPackageName) {
        final CallerIdentity caller = getCallerIdentity(callerPackageName);
        if (isPermissionCheckFlagEnabled()) {
            enforcePermission(MANAGE_DEVICE_POLICY_MTE, caller.getPackageName(),
                    UserHandle.USER_ALL);
        } else {
            Preconditions.checkCallAuthorization(
                    isDefaultDeviceOwner(caller)
                            || isProfileOwnerOfOrganizationOwnedDevice(caller)
                            || isSystemUid(caller));
        }
        synchronized (getLockObject()) {
            ActiveAdmin admin =
                        getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
            return admin != null
                    ? admin.mtePolicy
                    : DevicePolicyManager.MTE_NOT_CONTROLLED_BY_POLICY;
        }
    }

    @Override
    public ManagedSubscriptionsPolicy getManagedSubscriptionsPolicy() {
        synchronized (getLockObject()) {
            ActiveAdmin admin = getProfileOwnerOfOrganizationOwnedDeviceLocked();
            if (admin != null && admin.mManagedSubscriptionsPolicy != null) {
                return admin.mManagedSubscriptionsPolicy;
            }
        }
        return new ManagedSubscriptionsPolicy(
                ManagedSubscriptionsPolicy.TYPE_ALL_PERSONAL_SUBSCRIPTIONS);
    }

    @Override
    public void setManagedSubscriptionsPolicy(ManagedSubscriptionsPolicy policy) {
        CallerIdentity caller = getCallerIdentity();

        if (!isCallerDevicePolicyManagementRoleHolder(caller)
                && !Objects.equals(mInjector.settingsGlobalGetString(
                        Global.ALLOW_WORK_PROFILE_TELEPHONY_FOR_NON_DPM_ROLE_HOLDERS), "1")) {
            throw new UnsupportedOperationException("This api is not enabled");
        }

        Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller),
                "This policy can only be set by a profile owner on an organization-owned "
                        + "device.");

        int parentUserId = getProfileParentId(caller.getUserId());
        synchronized (getLockObject()) {
            final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
            if (hasUserSetupCompleted(parentUserId) && !isAdminTestOnlyLocked(
                    admin.info.getComponent(), caller.getUserId())) {
                throw new IllegalStateException("Not allowed to apply this policy after setup");
            }
            boolean changed = false;
            if (!Objects.equals(policy, admin.mManagedSubscriptionsPolicy)) {
                admin.mManagedSubscriptionsPolicy = policy;
                changed = true;
            }
            if (changed) {
                saveSettingsLocked(caller.getUserId());
            } else {
                return;
            }
        }

        applyManagedSubscriptionsPolicyIfRequired();

        int policyType = getManagedSubscriptionsPolicy().getPolicyType();
        final long id = mInjector.binderClearCallingIdentity();
        try {
            if (policyType == ManagedSubscriptionsPolicy.TYPE_ALL_MANAGED_SUBSCRIPTIONS) {
                installOemDefaultDialerAndSmsApp(caller.getUserId());
                updateTelephonyCrossProfileIntentFilters(parentUserId, caller.getUserId(), true);
            } else if (policyType == ManagedSubscriptionsPolicy.TYPE_ALL_PERSONAL_SUBSCRIPTIONS) {
                updateTelephonyCrossProfileIntentFilters(parentUserId, caller.getUserId(), false);
            }
        } finally {
            mInjector.binderRestoreCallingIdentity(id);
        }
    }

    private void installOemDefaultDialerAndSmsApp(int targetUserId) {
        try {
            String defaultDialerPackageName = getOemDefaultDialerPackage();
            String defaultSmsPackageName = getOemDefaultSmsPackage();

            if (defaultDialerPackageName != null) {
                mIPackageManager.installExistingPackageAsUser(defaultDialerPackageName,
                        targetUserId, PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
                        PackageManager.INSTALL_REASON_POLICY, null);
            } else {
                Slogf.w(LOG_TAG, "Couldn't install dialer app, dialer app package is null");
            }

            if (defaultSmsPackageName != null) {
                mIPackageManager.installExistingPackageAsUser(defaultSmsPackageName, targetUserId,
                        PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
                        PackageManager.INSTALL_REASON_POLICY, null);
            } else {
                Slogf.w(LOG_TAG, "Couldn't install sms app, sms app package is null");
            }

            updateDialerAndSmsManagedShortcutsOverrideCache();
        } catch (RemoteException re) {
            // shouldn't happen
            Slogf.wtf(LOG_TAG, "Failed to install dialer/sms app", re);
        }
    }

    private String getOemDefaultDialerPackage() {
        TelecomManager telecomManager = mContext.getSystemService(TelecomManager.class);
        return telecomManager.getSystemDialerPackage();
    }

    private String getOemDefaultSmsPackage() {
        return mContext.getString(R.string.config_defaultSms);
    }

    private void updateDialerAndSmsManagedShortcutsOverrideCache() {
        ArrayMap<String, String> shortcutOverrides = new ArrayMap<>();
        int managedUserId = getManagedUserId();
        List<String> dialerRoleHolders = mRoleManager.getRoleHoldersAsUser(RoleManager.ROLE_DIALER,
                UserHandle.of(managedUserId));
        List<String> smsRoleHolders = mRoleManager.getRoleHoldersAsUser(RoleManager.ROLE_SMS,
                UserHandle.of(managedUserId));

        String dialerPackageToOverride = getOemDefaultDialerPackage();
        String smsPackageToOverride = getOemDefaultSmsPackage();

        // To get the default app, we can get all the role holders and get the first element.
        if (dialerPackageToOverride != null) {
            shortcutOverrides.put(dialerPackageToOverride,
                    dialerRoleHolders.isEmpty() ? dialerPackageToOverride
                            : dialerRoleHolders.get(0));
        }
        if (smsPackageToOverride != null) {
            shortcutOverrides.put(smsPackageToOverride,
                    smsRoleHolders.isEmpty() ? smsPackageToOverride : smsRoleHolders.get(0));
        }

        mPolicyCache.setLauncherShortcutOverrides(shortcutOverrides);
    }

    private void registerListenerToAssignSubscriptionsToUser(int userId) {
        synchronized (mSubscriptionsChangedListenerLock) {
            if (mSubscriptionsChangedListener != null) {
                return;
            }
            SubscriptionManager subscriptionManager = mContext.getSystemService(
                    SubscriptionManager.class);
            // Listener to assign all current and future subs to managed profile.
            mSubscriptionsChangedListener = new SubscriptionManager.OnSubscriptionsChangedListener(
                    mHandler.getLooper()) {
                @Override
                public void onSubscriptionsChanged() {
                    final long id = mInjector.binderClearCallingIdentity();
                    try {
                        int[] subscriptionIds = subscriptionManager.getActiveSubscriptionIdList(
                                false);
                        for (int subId : subscriptionIds) {
                            UserHandle associatedUserHandle =
                                    subscriptionManager.getSubscriptionUserHandle(subId);
                            if (associatedUserHandle == null
                                    || associatedUserHandle.getIdentifier() != userId) {
                                subscriptionManager.setSubscriptionUserHandle(subId,
                                        UserHandle.of(userId));
                            }
                        }
                    } finally {
                        mInjector.binderRestoreCallingIdentity(id);
                    }
                }
            };

            final long id = mInjector.binderClearCallingIdentity();
            try {
                // When listener is added onSubscriptionsChanged gets called immediately for once
                // (even if subscriptions are not changed) and later on when subscriptions changes.
                subscriptionManager.addOnSubscriptionsChangedListener(
                        mHandler::post,
                        mSubscriptionsChangedListener);
            } finally {
                mInjector.binderRestoreCallingIdentity(id);
            }
        }
    }

    private void unregisterOnSubscriptionsChangedListener() {
        synchronized (mSubscriptionsChangedListenerLock) {
            if (mSubscriptionsChangedListener != null) {
                SubscriptionManager subscriptionManager = mContext.getSystemService(
                        SubscriptionManager.class);
                subscriptionManager.removeOnSubscriptionsChangedListener(
                        mSubscriptionsChangedListener);
                mSubscriptionsChangedListener = null;
            }
        }
    }

    @Override
    public DevicePolicyState getDevicePolicyState() {
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
        return mInjector.binderWithCleanCallingIdentity(mDevicePolicyEngine::getDevicePolicyState);
    }

    @Override
    public boolean triggerDevicePolicyEngineMigration(boolean forceMigration) {
        Preconditions.checkCallAuthorization(
                hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
        return mInjector.binderWithCleanCallingIdentity(() -> {
            boolean canForceMigration = forceMigration && !hasNonTestOnlyActiveAdmins();
            if (!canForceMigration && !shouldMigrateToDevicePolicyEngine()) {
                return false;
            }
            return migratePoliciesToDevicePolicyEngine();
        });
    }

    private boolean hasNonTestOnlyActiveAdmins() {
        return mInjector.binderWithCleanCallingIdentity(() -> {
            for (UserInfo userInfo : mUserManager.getUsers()) {
                synchronized (getLockObject()) {
                    List<ComponentName> activeAdmins = getActiveAdmins(userInfo.id);
                    if (activeAdmins == null) {
                        continue;
                    }
                    for (ComponentName admin : activeAdmins) {
                        if (!isAdminTestOnlyLocked(admin, userInfo.id)) {
                            return true;
                        }
                    }
                }
            }
            return false;
        });
    }

    private boolean shouldMigrateToDevicePolicyEngine() {
        return mInjector.binderWithCleanCallingIdentity(() -> !mOwners.isMigratedToPolicyEngine());
    }

    /**
     * @return {@code true} if policies were migrated successfully, {@code false} otherwise.
     */
    private boolean migratePoliciesToDevicePolicyEngine() {
        return mInjector.binderWithCleanCallingIdentity(() -> {
            try {
                synchronized (getLockObject()) {
                    Slogf.i(LOG_TAG,
                            "Started device policies migration to the device policy engine.");
                    if (isUnicornFlagEnabled()) {
                        migrateAutoTimezonePolicy();
                        migratePermissionGrantStatePolicies();
                    }
                    migrateScreenCapturePolicyLocked();
                    migratePermittedInputMethodsPolicyLocked();
                    migrateAccountManagementDisabledPolicyLocked();
                    migrateUserControlDisabledPackagesLocked();

                    mOwners.markMigrationToPolicyEngine();
                    return true;
                }
            } catch (Exception e) {
                mDevicePolicyEngine.clearAllPolicies();
                Slogf.e(LOG_TAG, e, "Error occurred during device policy migration, will "
                        + "reattempt on the next system server restart.");
                return false;
            }
        });
    }

    private void migrateAutoTimezonePolicy() {
        Slogf.i(LOG_TAG, "Skipping Migration of AUTO_TIMEZONE policy to device policy engine,"
                + "as no way to identify if the value was set by the admin or the user.");
    }

    private void migratePermissionGrantStatePolicies() {
        Slogf.i(LOG_TAG, "Migrating PERMISSION_GRANT policy to device policy engine.");
        for (UserInfo userInfo : mUserManager.getUsers()) {
            ActiveAdmin admin = getMostProbableDPCAdminForLocalPolicy(userInfo.id);
            if (admin == null) {
                Slogf.i(LOG_TAG, "No admin found that can set permission grant state on user "
                        + userInfo.id);
                continue;
            }
            for (PackageInfo packageInfo : getInstalledPackagesOnUser(userInfo.id)) {
                if (packageInfo.requestedPermissions == null) {
                    continue;
                }
                for (String permission : packageInfo.requestedPermissions) {
                    if (!isRuntimePermission(permission)) {
                        continue;
                    }
                    int grantState = DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
                    try {
                        grantState = getPermissionGrantStateForUser(
                                packageInfo.packageName, permission,
                                new CallerIdentity(
                                        mInjector.binderGetCallingUid(),
                                        admin.info.getComponent().getPackageName(),
                                        admin.info.getComponent()),
                                userInfo.id);
                    } catch (RemoteException e) {
                        Slogf.e(LOG_TAG, e, "Error retrieving permission grant state for %s "
                                        + "and %s", packageInfo.packageName, permission);
                    }
                    if (grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT) {
                        // Not Controlled by a policy
                        continue;
                    }

                    mDevicePolicyEngine.setLocalPolicy(
                            PolicyDefinition.PERMISSION_GRANT(packageInfo.packageName,
                                    permission),
                            EnforcingAdmin.createEnterpriseEnforcingAdmin(
                                    admin.info.getComponent(),
                                    admin.getUserHandle().getIdentifier()),
                            new IntegerPolicyValue(grantState),
                            userInfo.id,
                            /* skipEnforcePolicy= */ true);
                }
            }
        }
    }

    private void migrateScreenCapturePolicyLocked() {
        Binder.withCleanCallingIdentity(() -> {
            if (mPolicyCache.getScreenCaptureDisallowedUser() == UserHandle.USER_NULL) {
                return;
            }
            ActiveAdmin admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
            if (admin != null
                    && ((isDeviceOwner(admin) && admin.disableScreenCapture)
                    || (admin.getParentActiveAdmin() != null
                    && admin.getParentActiveAdmin().disableScreenCapture))) {
                EnforcingAdmin enforcingAdmin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
                        admin.info.getComponent(),
                        admin.getUserHandle().getIdentifier(),
                        admin);
                mDevicePolicyEngine.setGlobalPolicy(
                        PolicyDefinition.SCREEN_CAPTURE_DISABLED,
                        enforcingAdmin,
                        new BooleanPolicyValue(true));
            }

            List<UserInfo> users = mUserManager.getUsers();
            for (UserInfo userInfo : users) {
                ActiveAdmin profileOwner = getProfileOwnerLocked(userInfo.id);
                if (profileOwner != null && profileOwner.disableScreenCapture) {
                    EnforcingAdmin enforcingAdmin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
                            profileOwner.info.getComponent(),
                            profileOwner.getUserHandle().getIdentifier(),
                            profileOwner);
                    mDevicePolicyEngine.setLocalPolicy(
                            PolicyDefinition.SCREEN_CAPTURE_DISABLED,
                            enforcingAdmin,
                            new BooleanPolicyValue(true),
                            profileOwner.getUserHandle().getIdentifier());
                }
            }
        });
    }

    private void migratePermittedInputMethodsPolicyLocked() {
        Binder.withCleanCallingIdentity(() -> {
            List<UserInfo> users = mUserManager.getUsers();
            for (UserInfo userInfo : users) {
                ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(userInfo.id);
                if (admin != null) {
                    EnforcingAdmin enforcingAdmin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
                            admin.info.getComponent(),
                            admin.getUserHandle().getIdentifier(),
                            admin);
                    if (admin.permittedInputMethods != null) {
                        mDevicePolicyEngine.setLocalPolicy(
                                PolicyDefinition.PERMITTED_INPUT_METHODS,
                                enforcingAdmin,
                                new StringSetPolicyValue(
                                        new HashSet<>(admin.permittedInputMethods)),
                                admin.getUserHandle().getIdentifier());
                    }
                    if (admin.getParentActiveAdmin() != null
                            && admin.getParentActiveAdmin().permittedInputMethods != null) {
                        mDevicePolicyEngine.setLocalPolicy(
                                PolicyDefinition.PERMITTED_INPUT_METHODS,
                                enforcingAdmin,
                                new StringSetPolicyValue(
                                        new HashSet<>(admin.getParentActiveAdmin()
                                                .permittedInputMethods)),
                                getProfileParentId(admin.getUserHandle().getIdentifier()));
                    }
                }
            }
        });
    }

    private void migrateAccountManagementDisabledPolicyLocked() {
        Binder.withCleanCallingIdentity(() -> {
            List<UserInfo> users = mUserManager.getUsers();
            for (UserInfo userInfo : users) {
                ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(userInfo.id);
                if (admin != null) {
                    EnforcingAdmin enforcingAdmin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
                            admin.info.getComponent(),
                            admin.getUserHandle().getIdentifier(),
                            admin);
                    for (String accountType : admin.accountTypesWithManagementDisabled) {
                        mDevicePolicyEngine.setLocalPolicy(
                                PolicyDefinition.ACCOUNT_MANAGEMENT_DISABLED(accountType),
                                enforcingAdmin,
                                new BooleanPolicyValue(true),
                                admin.getUserHandle().getIdentifier());
                    }
                    if (admin.getParentActiveAdmin() != null) {
                        for (String accountType : admin.getParentActiveAdmin()
                                .accountTypesWithManagementDisabled) {
                            mDevicePolicyEngine.setLocalPolicy(
                                    PolicyDefinition.ACCOUNT_MANAGEMENT_DISABLED(accountType),
                                    enforcingAdmin,
                                    new BooleanPolicyValue(true),
                                    getProfileParentId(admin.getUserHandle().getIdentifier()));
                        }
                    }
                }
            }
        });
    }
    
    private void migrateUserControlDisabledPackagesLocked() {
        Binder.withCleanCallingIdentity(() -> {
            List<UserInfo> users = mUserManager.getUsers();
            for (UserInfo userInfo : users) {
                ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(userInfo.id);
                if (admin != null && admin.protectedPackages != null) {
                    EnforcingAdmin enforcingAdmin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
                            admin.info.getComponent(),
                            admin.getUserHandle().getIdentifier(),
                            admin);
                    if (isDeviceOwner(admin)) {
                        mDevicePolicyEngine.setGlobalPolicy(
                                PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
                                enforcingAdmin,
                                new StringSetPolicyValue(new HashSet<>(admin.protectedPackages)));
                    } else {
                        mDevicePolicyEngine.setLocalPolicy(
                                PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
                                enforcingAdmin,
                                new StringSetPolicyValue(new HashSet<>(admin.protectedPackages)),
                                admin.getUserHandle().getIdentifier());
                    }
                }
            }
        });
    }

    private List<PackageInfo> getInstalledPackagesOnUser(int userId) {
        return mInjector.binderWithCleanCallingIdentity(() ->
                mContext.getPackageManager().getInstalledPackagesAsUser(
                        PackageManager.PackageInfoFlags.of(
                                PackageManager.GET_PERMISSIONS), userId));
    }

    /**
     * Returns the most probable admin to have set a global policy according to the following
     * heuristics:
     *
     * <ul>
     * <li>The device owner on any user</li>
     * <li>The org owned profile owner on any user</li>
     * <li>The profile owner on any user</li>
     * </ul>
     */
    @Nullable
    // TODO(b/266928216): Check what the admin capabilities are when deciding which admin to return.
    private ActiveAdmin getMostProbableDPCAdminForGlobalPolicy() {
        synchronized (getLockObject()) {
            ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
            if (deviceOwner != null) {
                return deviceOwner;
            }

            List<UserInfo> users = mUserManager.getUsers();
            for (UserInfo userInfo : users) {
                if (isProfileOwnerOfOrganizationOwnedDevice(userInfo.id)) {
                    return getProfileOwnerAdminLocked(userInfo.id);
                }
            }

            for (UserInfo userInfo : users) {
                ActiveAdmin profileOwner = getProfileOwnerLocked(userInfo.id);
                if (profileOwner != null) {
                    return profileOwner;
                }
            }
            return null;
        }
    }

    /**
     * Returns the most probable admin to have set a policy on the given {@code userId} according
     * to the following heuristics:
     *
     * <ul>
     * <li>The device owner on the given userId</li>
     * <li>The profile owner on the given userId</li>
     * <li>The org owned profile owner of which the given userId is its parent</li>
     * <li>The profile owner of which the given userId is its parent</li>
     * <li>The device owner on any user</li>
     * <li>The profile owner on any user</li>
     * </ul>
     */
    @Nullable
    // TODO(b/266928216): Check what the admin capabilities are when deciding which admin to return.
    private ActiveAdmin getMostProbableDPCAdminForLocalPolicy(int userId) {
        synchronized (getLockObject()) {
            ActiveAdmin localDeviceOwner = getDeviceOwnerLocked(userId);
            if (localDeviceOwner != null) {
                return localDeviceOwner;
            }

            ActiveAdmin localProfileOwner = getProfileOwnerLocked(userId);
            if (localProfileOwner != null) {
                return localProfileOwner;
            }

            int[] profileIds = mUserManager.getProfileIds(userId, /* enabledOnly= */ false);
            for (int id : profileIds) {
                if (id == userId) {
                    continue;
                }
                if (isProfileOwnerOfOrganizationOwnedDevice(id)) {
                    return getProfileOwnerAdminLocked(id);
                }
            }

            for (int id : profileIds) {
                if (id == userId) {
                    continue;
                }
                if (isManagedProfile(id)) {
                    return getProfileOwnerAdminLocked(id);
                }
            }

            ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
            if (deviceOwner != null) {
                return deviceOwner;
            }

            for (UserInfo userInfo : mUserManager.getUsers()) {
                ActiveAdmin profileOwner = getProfileOwnerLocked(userInfo.id);
                if (profileOwner != null) {
                    return profileOwner;
                }
            }
            return null;
        }
    }

    // We need to add a mapping of policyId to permission in POLICY_IDENTIFIER_TO_PERMISSION
    // for each migrated permission.
    private List<ActiveAdmin> getNonDPCActiveAdminsForPolicyLocked(String policyIdentifier) {
        Integer activeAdminPolicy = POLICY_IDENTIFIER_TO_ACTIVE_ADMIN_POLICY.get(policyIdentifier);
        if (activeAdminPolicy == null) {
            Slogf.e(LOG_TAG,
                    "Can't find a active admin policy for %s in POLICY_IDENTIFIER_TO_PERMISSION",
                    policyIdentifier);
            return new ArrayList<>();
        }

        List<ActiveAdmin> admins = new ArrayList<>();
        for (UserInfo userInfo : mUserManager.getUsers()) {
            List<ComponentName> activeAdmins = getActiveAdmins(userInfo.id);
            for (ComponentName admin : activeAdmins) {
                if (isDeviceOwner(admin, userInfo.id) || isProfileOwner(admin, userInfo.id)) {
                    continue;
                }
                DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
                if (isActiveAdminWithPolicyForUserLocked(
                        policy.mAdminMap.get(admin), activeAdminPolicy,
                        userInfo.id)) {
                    admins.add(policy.mAdminMap.get(admin));
                }
            }
        }
        return admins;
    }

    // TODO: this can actually accept an EnforcingAdmin that gets created in the permission
    //  check method.
    private boolean isCallerActiveAdminOrDelegate(
            CallerIdentity caller, @Nullable String delegateScope) {
        return mInjector.binderWithCleanCallingIdentity(() -> {
            List<ComponentName> activeAdmins = getActiveAdmins(caller.getUserId());
            if (activeAdmins != null) {
                for (ComponentName admin : activeAdmins) {
                    if (admin.getPackageName().equals(caller.getPackageName())) {
                        return true;
                    }
                }
            }
            return delegateScope != null && isCallerDelegate(caller, delegateScope);
        });
    }

    /**
     * Truncates char sequence to maximum length, nulls are ignored.
     */
    private static CharSequence truncateIfLonger(CharSequence input, int maxLength) {
        return input == null || input.length() <= maxLength
                ? input
                : input.subSequence(0, maxLength);
    }

    /**
     * Throw if string argument is too long to be serialized.
     */
    private static void enforceMaxStringLength(String str, String argName) {
        Preconditions.checkArgument(
                str.length() <= MAX_POLICY_STRING_LENGTH, argName + " loo long");
    }

    private static void enforceMaxPackageNameLength(String pkg) {
        Preconditions.checkArgument(
                pkg.length() <= MAX_PACKAGE_NAME_LENGTH, "Package name too long");
    }

    /**
     * Throw if persistable bundle contains any string that we can't serialize.
     */
    private static void enforceMaxStringLength(PersistableBundle bundle, String argName) {
        // Persistable bundles can have other persistable bundles as values, traverse with a queue.
        Queue<PersistableBundle> queue = new ArrayDeque<>();
        queue.add(bundle);
        while (!queue.isEmpty()) {
            PersistableBundle current = queue.remove();
            for (String key : current.keySet()) {
                enforceMaxStringLength(key, "key in " + argName);
                Object value = current.get(key);
                if (value instanceof String) {
                    enforceMaxStringLength((String) value, "string value in " + argName);
                } else if (value instanceof String[]) {
                    for (String str : (String[]) value) {
                        enforceMaxStringLength(str, "string value in " + argName);
                    }
                } else if (value instanceof PersistableBundle) {
                    queue.add((PersistableBundle) value);
                }
            }
        }
    }

    private ActiveAdmin getActiveAdminForCaller(@Nullable ComponentName who,
            CallerIdentity caller) {
        synchronized (getLockObject()) {
            if (who != null) {
                return getActiveAdminUncheckedLocked(who, caller.getUserId());
            }
            return mInjector.binderWithCleanCallingIdentity(() -> {
                List<ComponentName> activeAdmins = getActiveAdmins(caller.getUserId());
                if (activeAdmins != null) {
                    for (ComponentName admin : activeAdmins) {
                        if (admin.getPackageName().equals(caller.getPackageName())) {
                            return getActiveAdminUncheckedLocked(admin, caller.getUserId());
                        }
                    }
                }
                return null;
            });
        }
    }

    @Override
    public boolean isDeviceFinanced(String callerPackageName) {
        CallerIdentity caller = getCallerIdentity(callerPackageName);
        Preconditions.checkCallAuthorization(isDeviceOwner(caller)
                || isProfileOwnerOfOrganizationOwnedDevice(caller)
                || isProfileOwnerOnUser0(caller)
                || isCallerDevicePolicyManagementRoleHolder(caller)
                || isCallerSystemSupervisionRoleHolder(caller));
        return getFinancedDeviceKioskRoleHolderOnAnyUser() != null;
    };

    @Override
    public String getFinancedDeviceKioskRoleHolder(String callerPackageName) {
        CallerIdentity caller = getCallerIdentity(callerPackageName);
        enforcePermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, caller.getPackageName(),
                caller.getUserId());
        return getFinancedDeviceKioskRoleHolderOnAnyUser();
    }

    private String getFinancedDeviceKioskRoleHolderOnAnyUser() {
        return getRoleHolderPackageNameOnUser(
                RoleManager.ROLE_FINANCED_DEVICE_KIOSK, UserHandle.USER_ALL);
    }

    /**
     * TODO (b/278924166): this method is added for debugging the specified bug.
     * Remove once fixed.
     **/
    private void logStackTrace(String methodName) {
        try {
            StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
            String stackMethod;
            StringBuilder stackTrace = new StringBuilder();
            for (StackTraceElement s : stackTraceElements) {
                stackMethod = s.getMethodName();
                if (stackMethod == null || stackMethod.equals("getThreadStackTrace")
                        || stackMethod.equals("getStackTrace")
                        || stackMethod.equals("logStackTrace")) {
                    continue;
                }
                stackTrace.append(s.getMethodName() + ":" + s.getLineNumber() + "\n");
            }
            Slogf.d(LOG_TAG, "StackTrace for " + methodName + ": \n" + stackTrace);
        } catch (Exception e) {
            Slogf.d(LOG_TAG, "Unable to get stacktrace");
        }
    }
}