summaryrefslogtreecommitdiff
path: root/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java
blob: 5c36a6b07392f647ad39f1868ece244526651ee5 (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
/*
 * Copyright (C) 2017 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.companion;

import static android.Manifest.permission.MANAGE_COMPANION_DEVICES;
import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
import static android.companion.AssociationRequest.DEVICE_PROFILE_AUTOMOTIVE_PROJECTION;
import static android.content.pm.PackageManager.CERT_INPUT_SHA256;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static android.os.Process.SYSTEM_UID;
import static android.os.UserHandle.getCallingUserId;

import static com.android.internal.util.CollectionUtils.any;
import static com.android.internal.util.Preconditions.checkState;
import static com.android.internal.util.function.pooled.PooledLambda.obtainMessage;
import static com.android.server.companion.AssociationStore.CHANGE_TYPE_UPDATED_ADDRESS_UNCHANGED;
import static com.android.server.companion.MetricUtils.logRemoveAssociation;
import static com.android.server.companion.PackageUtils.enforceUsesCompanionDeviceFeature;
import static com.android.server.companion.PackageUtils.getPackageInfo;
import static com.android.server.companion.PermissionsUtils.checkCallerCanManageCompanionDevice;
import static com.android.server.companion.PermissionsUtils.enforceCallerCanManageAssociationsForPackage;
import static com.android.server.companion.PermissionsUtils.enforceCallerCanManageCompanionDevice;
import static com.android.server.companion.PermissionsUtils.enforceCallerIsSystemOr;
import static com.android.server.companion.PermissionsUtils.enforceCallerIsSystemOrCanInteractWithUserId;
import static com.android.server.companion.PermissionsUtils.sanitizeWithCallerChecks;
import static com.android.server.companion.RolesUtils.removeRoleHolderForAssociation;

import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.MINUTES;

import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SuppressLint;
import android.annotation.UserIdInt;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManagerInternal;
import android.app.AppOpsManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothDevice;
import android.companion.AssociationInfo;
import android.companion.AssociationRequest;
import android.companion.DeviceNotAssociatedException;
import android.companion.IAssociationRequestCallback;
import android.companion.ICompanionDeviceManager;
import android.companion.IOnAssociationsChangedListener;
import android.companion.IOnMessageReceivedListener;
import android.companion.IOnTransportsChangedListener;
import android.companion.ISystemDataTransferCallback;
import android.companion.utils.FeatureUtils;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManagerInternal;
import android.content.pm.UserInfo;
import android.net.MacAddress;
import android.net.NetworkPolicyManager;
import android.os.Binder;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcel;
import android.os.ParcelFileDescriptor;
import android.os.PowerWhitelistManager;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.os.ResultReceiver;
import android.os.ServiceManager;
import android.os.ShellCallback;
import android.os.SystemProperties;
import android.os.UserHandle;
import android.os.UserManager;
import android.util.ArraySet;
import android.util.ExceptionUtils;
import android.util.Log;
import android.util.Slog;
import android.util.SparseArray;
import android.util.SparseBooleanArray;

import com.android.internal.annotations.GuardedBy;
import com.android.internal.app.IAppOpsService;
import com.android.internal.content.PackageMonitor;
import com.android.internal.infra.PerUser;
import com.android.internal.notification.NotificationAccessConfirmationActivityContract;
import com.android.internal.os.BackgroundThread;
import com.android.internal.util.ArrayUtils;
import com.android.internal.util.DumpUtils;
import com.android.server.FgThread;
import com.android.server.LocalServices;
import com.android.server.SystemService;
import com.android.server.companion.datatransfer.SystemDataTransferProcessor;
import com.android.server.companion.datatransfer.SystemDataTransferRequestStore;
import com.android.server.companion.datatransfer.contextsync.CrossDeviceCall;
import com.android.server.companion.datatransfer.contextsync.CrossDeviceSyncController;
import com.android.server.companion.datatransfer.contextsync.CrossDeviceSyncControllerCallback;
import com.android.server.companion.presence.CompanionDevicePresenceMonitor;
import com.android.server.companion.transport.CompanionTransportManager;
import com.android.server.pm.UserManagerInternal;
import com.android.server.wm.ActivityTaskManagerInternal;

import java.io.File;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@SuppressLint("LongLogTag")
public class CompanionDeviceManagerService extends SystemService {
    static final String TAG = "CDM_CompanionDeviceManagerService";
    static final boolean DEBUG = false;

    /** Range of Association IDs allocated for a user.*/
    private static final int ASSOCIATIONS_IDS_PER_USER_RANGE = 100000;
    private static final long PAIR_WITHOUT_PROMPT_WINDOW_MS = 10 * 60 * 1000; // 10 min

    private static final String PREF_FILE_NAME = "companion_device_preferences.xml";
    private static final String PREF_KEY_AUTO_REVOKE_GRANTS_DONE = "auto_revoke_grants_done";
    private static final String SYS_PROP_DEBUG_REMOVAL_TIME_WINDOW =
            "debug.cdm.cdmservice.removal_time_window";

    private static final long ASSOCIATION_REMOVAL_TIME_WINDOW_DEFAULT = DAYS.toMillis(90);
    private static final int MAX_CN_LENGTH = 500;

    private final ActivityManager mActivityManager;
    private final OnPackageVisibilityChangeListener mOnPackageVisibilityChangeListener;

    private PersistentDataStore mPersistentStore;
    private final PersistUserStateHandler mUserPersistenceHandler;

    private final AssociationStoreImpl mAssociationStore;
    private final SystemDataTransferRequestStore mSystemDataTransferRequestStore;
    private AssociationRequestsProcessor mAssociationRequestsProcessor;
    private SystemDataTransferProcessor mSystemDataTransferProcessor;
    private CompanionDevicePresenceMonitor mDevicePresenceMonitor;
    private CompanionApplicationController mCompanionAppController;
    private CompanionTransportManager mTransportManager;

    private final ActivityTaskManagerInternal mAtmInternal;
    private final ActivityManagerInternal mAmInternal;
    private final IAppOpsService mAppOpsManager;
    private final PowerWhitelistManager mPowerWhitelistManager;
    private final UserManager mUserManager;
    final PackageManagerInternal mPackageManagerInternal;

    /**
     * A structure that consists of two nested maps, and effectively maps (userId + packageName) to
     * a list of IDs that have been previously assigned to associations for that package.
     * We maintain this structure so that we never re-use association IDs for the same package
     * (until it's uninstalled).
     */
    @GuardedBy("mPreviouslyUsedIds")
    private final SparseArray<Map<String, Set<Integer>>> mPreviouslyUsedIds = new SparseArray<>();

    /**
     * A structure that consists of a set of revoked associations that pending for role holder
     * removal per each user.
     *
     * @see #maybeRemoveRoleHolderForAssociation(AssociationInfo)
     * @see #addToPendingRoleHolderRemoval(AssociationInfo)
     * @see #removeFromPendingRoleHolderRemoval(AssociationInfo)
     * @see #getPendingRoleHolderRemovalAssociationsForUser(int)
     */
    @GuardedBy("mRevokedAssociationsPendingRoleHolderRemoval")
    private final PerUserAssociationSet mRevokedAssociationsPendingRoleHolderRemoval =
            new PerUserAssociationSet();
    /**
     * Contains uid-s of packages pending to be removed from the role holder list (after
     * revocation of an association), which will happen one the package is no longer visible to the
     * user.
     * For quicker uid -> (userId, packageName) look-up this is not a {@code Set<Integer>} but
     * a {@code Map<Integer, String>} which maps uid-s to packageName-s (userId-s can be derived
     * from uid-s using {@link UserHandle#getUserId(int)}).
     *
     * @see #maybeRemoveRoleHolderForAssociation(AssociationInfo)
     * @see #addToPendingRoleHolderRemoval(AssociationInfo)
     * @see #removeFromPendingRoleHolderRemoval(AssociationInfo)
     */
    @GuardedBy("mRevokedAssociationsPendingRoleHolderRemoval")
    private final Map<Integer, String> mUidsPendingRoleHolderRemoval = new HashMap<>();

    private final RemoteCallbackList<IOnAssociationsChangedListener> mListeners =
            new RemoteCallbackList<>();

    private CrossDeviceSyncController mCrossDeviceSyncController;

    public CompanionDeviceManagerService(Context context) {
        super(context);

        mActivityManager = context.getSystemService(ActivityManager.class);
        mPowerWhitelistManager = context.getSystemService(PowerWhitelistManager.class);
        mAppOpsManager = IAppOpsService.Stub.asInterface(
                ServiceManager.getService(Context.APP_OPS_SERVICE));
        mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
        mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
        mPackageManagerInternal = LocalServices.getService(PackageManagerInternal.class);
        mUserManager = context.getSystemService(UserManager.class);

        mUserPersistenceHandler = new PersistUserStateHandler();
        mAssociationStore = new AssociationStoreImpl();
        mSystemDataTransferRequestStore = new SystemDataTransferRequestStore();

        mOnPackageVisibilityChangeListener =
                new OnPackageVisibilityChangeListener(mActivityManager);
    }

    @Override
    public void onStart() {
        final Context context = getContext();

        mPersistentStore = new PersistentDataStore();

        loadAssociationsFromDisk();
        mAssociationStore.registerListener(mAssociationStoreChangeListener);

        mDevicePresenceMonitor = new CompanionDevicePresenceMonitor(mUserManager,
                mAssociationStore, mDevicePresenceCallback);

        mAssociationRequestsProcessor = new AssociationRequestsProcessor(
                /* cdmService */this, mAssociationStore);
        mCompanionAppController = new CompanionApplicationController(
                context, mAssociationStore, mDevicePresenceMonitor);
        mTransportManager = new CompanionTransportManager(context, mAssociationStore);
        mSystemDataTransferProcessor = new SystemDataTransferProcessor(this, mAssociationStore,
                mSystemDataTransferRequestStore, mTransportManager);
        // TODO(b/279663946): move context sync to a dedicated system service
        mCrossDeviceSyncController = new CrossDeviceSyncController(getContext(), mTransportManager);

        // Publish "binder" service.
        final CompanionDeviceManagerImpl impl = new CompanionDeviceManagerImpl();
        publishBinderService(Context.COMPANION_DEVICE_SERVICE, impl);

        // Publish "local" service.
        LocalServices.addService(CompanionDeviceManagerServiceInternal.class, new LocalService());
    }

    void loadAssociationsFromDisk() {
        final Set<AssociationInfo> allAssociations = new ArraySet<>();
        synchronized (mPreviouslyUsedIds) {
            // The data is stored in DE directories, so we can read the data for all users now
            // (which would not be possible if the data was stored to CE directories).
            mPersistentStore.readStateForUsers(
                    mUserManager.getAliveUsers(), allAssociations, mPreviouslyUsedIds);
        }

        final Set<AssociationInfo> activeAssociations =
                new ArraySet<>(/* capacity */ allAssociations.size());
        // A set contains the userIds that need to persist state after remove the app
        // from the list of role holders.
        final Set<Integer> usersToPersistStateFor = new ArraySet<>();

        for (AssociationInfo association : allAssociations) {
            if (!association.isRevoked()) {
                activeAssociations.add(association);
            } else if (maybeRemoveRoleHolderForAssociation(association)) {
                // Nothing more to do here, but we'll need to persist all the associations to the
                // disk afterwards.
                usersToPersistStateFor.add(association.getUserId());
            } else {
                addToPendingRoleHolderRemoval(association);
            }
        }

        mAssociationStore.setAssociations(activeAssociations);

        // IMPORTANT: only do this AFTER mAssociationStore.setAssociations(), because
        // persistStateForUser() queries AssociationStore.
        // (If persistStateForUser() is invoked before mAssociationStore.setAssociations() it
        // would effectively just clear-out all the persisted associations).
        for (int userId : usersToPersistStateFor) {
            persistStateForUser(userId);
        }
    }

    @Override
    public void onBootPhase(int phase) {
        final Context context = getContext();
        if (phase == PHASE_SYSTEM_SERVICES_READY) {
            // WARNING: moving PackageMonitor to another thread (Looper) may introduce significant
            // delays (even in case of the Main Thread). It may be fine overall, but would require
            // updating the tests (adding a delay there).
            mPackageMonitor.register(context, FgThread.get().getLooper(), UserHandle.ALL, true);
            mDevicePresenceMonitor.init(context);
        } else if (phase == PHASE_BOOT_COMPLETED) {
            // Run the Inactive Association Removal job service daily.
            InactiveAssociationsRemovalService.schedule(getContext());
            mCrossDeviceSyncController.onBootCompleted();
        }
    }

    @Override
    public void onUserUnlocking(@NonNull TargetUser user) {
        final int userId = user.getUserIdentifier();
        final List<AssociationInfo> associations = mAssociationStore.getAssociationsForUser(userId);

        if (associations.isEmpty()) return;

        updateAtm(userId, associations);

        BackgroundThread.getHandler().sendMessageDelayed(
                obtainMessage(CompanionDeviceManagerService::maybeGrantAutoRevokeExemptions, this),
                MINUTES.toMillis(10));
    }

    @Override
    public void onUserUnlocked(@NonNull TargetUser user) {
        // Notify and bind the app after the phone is unlocked.
        final int userId = user.getUserIdentifier();
        final Set<BluetoothDevice> blueToothDevices =
                mDevicePresenceMonitor.getPendingConnectedDevices().get(userId);
        if (blueToothDevices != null) {
            for (BluetoothDevice bluetoothDevice : blueToothDevices) {
                for (AssociationInfo ai:
                        mAssociationStore.getAssociationsByAddress(bluetoothDevice.getAddress())) {
                    Slog.i(TAG, "onUserUnlocked, device id( " + ai.getId() + " ) is connected");
                    mDevicePresenceMonitor.onBluetoothCompanionDeviceConnected(ai.getId());
                }
            }
        }
    }

    @NonNull
    AssociationInfo getAssociationWithCallerChecks(
            @UserIdInt int userId, @NonNull String packageName, @NonNull String macAddress) {
        AssociationInfo association = mAssociationStore.getAssociationsForPackageWithAddress(
                userId, packageName, macAddress);
        association = sanitizeWithCallerChecks(getContext(), association);
        if (association != null) {
            return association;
        } else {
            throw new IllegalArgumentException("Association does not exist "
                    + "or the caller does not have permissions to manage it "
                    + "(ie. it belongs to a different package or a different user).");
        }
    }

    @NonNull
    AssociationInfo getAssociationWithCallerChecks(int associationId) {
        AssociationInfo association = mAssociationStore.getAssociationById(associationId);
        association = sanitizeWithCallerChecks(getContext(), association);
        if (association != null) {
            return association;
        } else {
            throw new IllegalArgumentException("Association does not exist "
                    + "or the caller does not have permissions to manage it "
                    + "(ie. it belongs to a different package or a different user).");
        }
    }

    private void onDeviceAppearedInternal(int associationId) {
        if (DEBUG) Log.i(TAG, "onDevice_Appeared_Internal() id=" + associationId);

        final AssociationInfo association = mAssociationStore.getAssociationById(associationId);
        if (DEBUG) Log.d(TAG, "  association=" + association);

        if (!association.shouldBindWhenPresent()) return;

        final int userId = association.getUserId();
        final String packageName = association.getPackageName();
        // Set bindImportant to true when the association is self-managed to avoid the target
        // service being killed.
        final boolean bindImportant = association.isSelfManaged();

        if (!mCompanionAppController.isCompanionApplicationBound(userId, packageName)) {
            mCompanionAppController.bindCompanionApplication(userId, packageName, bindImportant);
        } else if (DEBUG) {
            Log.i(TAG, "u" + userId + "\\" + packageName + " is already bound");
        }
        mCompanionAppController.notifyCompanionApplicationDeviceAppeared(association);
    }

    private void onDeviceDisappearedInternal(int associationId) {
        if (DEBUG) Log.i(TAG, "onDevice_Disappeared_Internal() id=" + associationId);

        final AssociationInfo association = mAssociationStore.getAssociationById(associationId);
        if (DEBUG) Log.d(TAG, "  association=" + association);

        final int userId = association.getUserId();
        final String packageName = association.getPackageName();

        if (!mCompanionAppController.isCompanionApplicationBound(userId, packageName)) {
            if (DEBUG) Log.w(TAG, "u" + userId + "\\" + packageName + " is NOT bound");
            return;
        }

        if (association.shouldBindWhenPresent()) {
            mCompanionAppController.notifyCompanionApplicationDeviceDisappeared(association);
        }

        // Check if there are other devices associated to the app that are present.
        if (shouldBindPackage(userId, packageName)) return;

        mCompanionAppController.unbindCompanionApplication(userId, packageName);
    }

    /**
     * @return whether the package should be bound (i.e. at least one of the devices associated with
     *         the package is currently present).
     */
    private boolean shouldBindPackage(@UserIdInt int userId, @NonNull String packageName) {
        final List<AssociationInfo> packageAssociations =
                mAssociationStore.getAssociationsForPackage(userId, packageName);
        for (AssociationInfo association : packageAssociations) {
            if (!association.shouldBindWhenPresent()) continue;
            if (mDevicePresenceMonitor.isDevicePresent(association.getId())) return true;
        }
        return false;
    }

    private void onAssociationChangedInternal(
            @AssociationStore.ChangeType int changeType, AssociationInfo association) {
        final int id = association.getId();
        final int userId = association.getUserId();
        final String packageName = association.getPackageName();

        if (changeType == AssociationStore.CHANGE_TYPE_REMOVED) {
            markIdAsPreviouslyUsedForPackage(id, userId, packageName);
        }

        final List<AssociationInfo> updatedAssociations =
                mAssociationStore.getAssociationsForUser(userId);

        mUserPersistenceHandler.postPersistUserState(userId);

        // Notify listeners if ADDED, REMOVED or UPDATED_ADDRESS_CHANGED.
        // Do NOT notify when UPDATED_ADDRESS_UNCHANGED, which means a minor tweak in association's
        // configs, which "listeners" won't (and shouldn't) be able to see.
        if (changeType != CHANGE_TYPE_UPDATED_ADDRESS_UNCHANGED) {
            notifyListeners(userId, updatedAssociations);
        }
        updateAtm(userId, updatedAssociations);
    }

    private void persistStateForUser(@UserIdInt int userId) {
        // We want to store both active associations and the revoked (removed) association that we
        // are keeping around for the final clean-up (delayed role holder removal).
        final List<AssociationInfo> allAssociations;
        // Start with the active associations - these we can get from the AssociationStore.
        allAssociations = new ArrayList<>(
                mAssociationStore.getAssociationsForUser(userId));
        // ... and add the revoked (removed) association, that are yet to be permanently removed.
        allAssociations.addAll(getPendingRoleHolderRemovalAssociationsForUser(userId));

        final Map<String, Set<Integer>> usedIdsForUser = getPreviouslyUsedIdsForUser(userId);

        mPersistentStore.persistStateForUser(userId, allAssociations, usedIdsForUser);
    }

    private void notifyListeners(
            @UserIdInt int userId, @NonNull List<AssociationInfo> associations) {
        mListeners.broadcast((listener, callbackUserId) -> {
            if ((int) callbackUserId == userId) {
                try {
                    listener.onAssociationsChanged(associations);
                } catch (RemoteException ignored) {
                }
            }
        });
    }

    private void markIdAsPreviouslyUsedForPackage(
            int associationId, @UserIdInt int userId, @NonNull String packageName) {
        synchronized (mPreviouslyUsedIds) {
            Map<String, Set<Integer>> usedIdsForUser = mPreviouslyUsedIds.get(userId);
            if (usedIdsForUser == null) {
                usedIdsForUser = new HashMap<>();
                mPreviouslyUsedIds.put(userId, usedIdsForUser);
            }

            final Set<Integer> usedIdsForPackage =
                    usedIdsForUser.computeIfAbsent(packageName, it -> new HashSet<>());
            usedIdsForPackage.add(associationId);
        }
    }

    private void onPackageRemoveOrDataClearedInternal(
            @UserIdInt int userId, @NonNull String packageName) {
        if (DEBUG) {
            Log.i(TAG, "onPackageRemove_Or_DataCleared() u" + userId + "/"
                    + packageName);
        }

        // Clear associations.
        final List<AssociationInfo> associationsForPackage =
                mAssociationStore.getAssociationsForPackage(userId, packageName);
        for (AssociationInfo association : associationsForPackage) {
            mAssociationStore.removeAssociation(association.getId());
        }
        // Clear role holders
        for (AssociationInfo association : associationsForPackage) {
            maybeRemoveRoleHolderForAssociation(association);
        }

        mCompanionAppController.onPackagesChanged(userId);
    }

    private void onPackageModifiedInternal(@UserIdInt int userId, @NonNull String packageName) {
        if (DEBUG) Log.i(TAG, "onPackageModified() u" + userId + "/" + packageName);

        final List<AssociationInfo> associationsForPackage =
                mAssociationStore.getAssociationsForPackage(userId, packageName);
        for (AssociationInfo association : associationsForPackage) {
            updateSpecialAccessPermissionForAssociatedPackage(association);
        }

        mCompanionAppController.onPackagesChanged(userId);
    }

    // Revoke associations if the selfManaged companion device does not connect for 3 months.
    void removeInactiveSelfManagedAssociations() {
        final long currentTime = System.currentTimeMillis();
        long removalWindow = SystemProperties.getLong(SYS_PROP_DEBUG_REMOVAL_TIME_WINDOW, -1);
        if (removalWindow <= 0) {
            // 0 or negative values indicate that the sysprop was never set or should be ignored.
            removalWindow = ASSOCIATION_REMOVAL_TIME_WINDOW_DEFAULT;
        }

        for (AssociationInfo association : mAssociationStore.getAssociations()) {
            if (!association.isSelfManaged()) continue;

            final boolean isInactive =
                    currentTime - association.getLastTimeConnectedMs() >= removalWindow;
            if (!isInactive) continue;

            final int id = association.getId();

            Slog.i(TAG, "Removing inactive self-managed association id=" + id);
            disassociateInternal(id);
        }
    }

    class CompanionDeviceManagerImpl extends ICompanionDeviceManager.Stub {
        @Override
        public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
                throws RemoteException {
            try {
                return super.onTransact(code, data, reply, flags);
            } catch (Throwable e) {
                Slog.e(TAG, "Error during IPC", e);
                throw ExceptionUtils.propagate(e, RemoteException.class);
            }
        }

        @Override
        public void associate(AssociationRequest request, IAssociationRequestCallback callback,
                String packageName, int userId) throws RemoteException {
            Slog.i(TAG, "associate() "
                    + "request=" + request + ", "
                    + "package=u" + userId + "/" + packageName);
            enforceCallerCanManageAssociationsForPackage(getContext(), userId, packageName,
                    "create associations");

            mAssociationRequestsProcessor.processNewAssociationRequest(
                    request, packageName, userId, callback);
        }

        @Override
        public PendingIntent buildAssociationCancellationIntent(String packageName,
                int userId) throws RemoteException {
            Slog.i(TAG, "buildAssociationCancellationIntent() "
                    + "package=u" + userId + "/" + packageName);
            enforceCallerCanManageAssociationsForPackage(getContext(), userId, packageName,
                    "build association cancellation intent");

            return mAssociationRequestsProcessor.buildAssociationCancellationIntent(
                    packageName, userId);
        }

        @Override
        public List<AssociationInfo> getAssociations(String packageName, int userId) {
            enforceCallerCanManageAssociationsForPackage(getContext(), userId, packageName,
                    "get associations");

            if (!checkCallerCanManageCompanionDevice(getContext())) {
                // If the caller neither is system nor holds MANAGE_COMPANION_DEVICES: it needs to
                // request the feature (also: the caller is the app itself).
                enforceUsesCompanionDeviceFeature(getContext(), userId, packageName);
            }

            return mAssociationStore.getAssociationsForPackage(userId, packageName);
        }

        @Override
        public List<AssociationInfo> getAllAssociationsForUser(int userId) throws RemoteException {
            enforceCallerIsSystemOrCanInteractWithUserId(getContext(), userId);
            enforceCallerCanManageCompanionDevice(getContext(), "getAllAssociationsForUser");

            return mAssociationStore.getAssociationsForUser(userId);
        }

        @Override
        public void addOnAssociationsChangedListener(IOnAssociationsChangedListener listener,
                int userId) {
            enforceCallerIsSystemOrCanInteractWithUserId(getContext(), userId);
            enforceCallerCanManageCompanionDevice(getContext(),
                    "addOnAssociationsChangedListener");

            mListeners.register(listener, userId);
        }

        @Override
        public void removeOnAssociationsChangedListener(IOnAssociationsChangedListener listener,
                int userId) {
            enforceCallerIsSystemOrCanInteractWithUserId(getContext(), userId);
            enforceCallerCanManageCompanionDevice(
                    getContext(), "removeOnAssociationsChangedListener");

            mListeners.unregister(listener);
        }

        @Override
        public void addOnTransportsChangedListener(IOnTransportsChangedListener listener) {
            mTransportManager.addListener(listener);
        }

        @Override
        public void removeOnTransportsChangedListener(IOnTransportsChangedListener listener) {
            mTransportManager.removeListener(listener);
        }

        @Override
        public void sendMessage(int messageType, byte[] data, int[] associationIds) {
            mTransportManager.sendMessage(messageType, data, associationIds);
        }

        @Override
        public void addOnMessageReceivedListener(int messageType,
                IOnMessageReceivedListener listener) {
            mTransportManager.addListener(messageType, listener);
        }

        @Override
        public void removeOnMessageReceivedListener(int messageType,
                IOnMessageReceivedListener listener) {
            mTransportManager.removeListener(messageType, listener);
        }

        @Override
        public void legacyDisassociate(String deviceMacAddress, String packageName, int userId) {
            Log.i(TAG, "legacyDisassociate() pkg=u" + userId + "/" + packageName
                    + ", macAddress=" + deviceMacAddress);

            requireNonNull(deviceMacAddress);
            requireNonNull(packageName);

            final AssociationInfo association =
                    getAssociationWithCallerChecks(userId, packageName, deviceMacAddress);
            disassociateInternal(association.getId());
        }

        @Override
        public void disassociate(int associationId) {
            Log.i(TAG, "disassociate() associationId=" + associationId);

            final AssociationInfo association =
                    getAssociationWithCallerChecks(associationId);
            disassociateInternal(association.getId());
        }

        @Override
        public PendingIntent requestNotificationAccess(ComponentName component, int userId)
                throws RemoteException {
            String callingPackage = component.getPackageName();
            checkCanCallNotificationApi(callingPackage, userId);
            if (component.flattenToString().length() > MAX_CN_LENGTH) {
                throw new IllegalArgumentException("Component name is too long.");
            }
            final long identity = Binder.clearCallingIdentity();
            try {
                return PendingIntent.getActivityAsUser(getContext(),
                        0 /* request code */,
                        NotificationAccessConfirmationActivityContract.launcherIntent(
                                getContext(), userId, component),
                        PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_ONE_SHOT
                                | PendingIntent.FLAG_CANCEL_CURRENT,
                        null /* options */,
                        new UserHandle(userId));
            } finally {
                Binder.restoreCallingIdentity(identity);
            }
        }

        /**
        * @deprecated Use
        * {@link NotificationManager#isNotificationListenerAccessGranted(ComponentName)} instead.
        */
        @Deprecated
        @Override
        public boolean hasNotificationAccess(ComponentName component) throws RemoteException {
            checkCanCallNotificationApi(component.getPackageName(), getCallingUserId());
            NotificationManager nm = getContext().getSystemService(NotificationManager.class);
            return nm.isNotificationListenerAccessGranted(component);
        }

        @Override
        public boolean isDeviceAssociatedForWifiConnection(String packageName, String macAddress,
                int userId) {
            getContext().enforceCallingOrSelfPermission(
                    MANAGE_COMPANION_DEVICES, "isDeviceAssociated");

            boolean bypassMacPermission = getContext().getPackageManager().checkPermission(
                    android.Manifest.permission.COMPANION_APPROVE_WIFI_CONNECTIONS, packageName)
                    == PERMISSION_GRANTED;
            if (bypassMacPermission) {
                return true;
            }

            return any(mAssociationStore.getAssociationsForPackage(userId, packageName),
                    a -> a.isLinkedTo(macAddress));
        }

        @Override
        public void registerDevicePresenceListenerService(String deviceAddress,
                String callingPackage, int userId) throws RemoteException {
            // TODO: take the userId into account.
            registerDevicePresenceListenerActive(callingPackage, deviceAddress, true);
        }

        @Override
        public void unregisterDevicePresenceListenerService(String deviceAddress,
                String callingPackage, int userId) throws RemoteException {
            // TODO: take the userId into account.
            registerDevicePresenceListenerActive(callingPackage, deviceAddress, false);
        }

        @Override
        public PendingIntent buildPermissionTransferUserConsentIntent(String packageName,
                int userId, int associationId) {
            if (!FeatureUtils.isPermSyncEnabled()) {
                throw new UnsupportedOperationException("Calling"
                        + " buildPermissionTransferUserConsentIntent, but this API is disabled by"
                        + " the system.");
            }
            return mSystemDataTransferProcessor.buildPermissionTransferUserConsentIntent(
                    packageName, userId, associationId);
        }

        @Override
        public void startSystemDataTransfer(String packageName, int userId, int associationId,
                ISystemDataTransferCallback callback) {
            if (!FeatureUtils.isPermSyncEnabled()) {
                throw new UnsupportedOperationException("Calling startSystemDataTransfer, but this"
                        + " API is disabled by the system.");
            }
            mSystemDataTransferProcessor.startSystemDataTransfer(packageName, userId,
                    associationId, callback);
        }

        @Override
        public void attachSystemDataTransport(String packageName, int userId, int associationId,
                ParcelFileDescriptor fd) {
            getAssociationWithCallerChecks(associationId);
            mTransportManager.attachSystemDataTransport(packageName, userId, associationId, fd);
        }

        @Override
        public void detachSystemDataTransport(String packageName, int userId, int associationId) {
            getAssociationWithCallerChecks(associationId);
            mTransportManager.detachSystemDataTransport(packageName, userId, associationId);
        }

        @Override
        public void enableSystemDataSync(int associationId, int flags) {
            getAssociationWithCallerChecks(associationId);
            mAssociationRequestsProcessor.enableSystemDataSync(associationId, flags);
        }

        @Override
        public void disableSystemDataSync(int associationId, int flags) {
            getAssociationWithCallerChecks(associationId);
            mAssociationRequestsProcessor.disableSystemDataSync(associationId, flags);
        }

        @Override
        public void enableSecureTransport(boolean enabled) {
            mTransportManager.enableSecureTransport(enabled);
        }

        @Override
        public void notifyDeviceAppeared(int associationId) {
            if (DEBUG) Log.i(TAG, "notifyDevice_Appeared() id=" + associationId);

            AssociationInfo association = getAssociationWithCallerChecks(associationId);
            if (!association.isSelfManaged()) {
                throw new IllegalArgumentException("Association with ID " + associationId
                        + " is not self-managed. notifyDeviceAppeared(int) can only be called for"
                        + " self-managed associations.");
            }
            // AssociationInfo class is immutable: create a new AssociationInfo object with updated
            // timestamp.
            association = AssociationInfo.builder(association)
                    .setLastTimeConnected(System.currentTimeMillis())
                    .build();
            mAssociationStore.updateAssociation(association);

            mDevicePresenceMonitor.onSelfManagedDeviceConnected(associationId);
        }

        @Override
        public void notifyDeviceDisappeared(int associationId) {
            if (DEBUG) Log.i(TAG, "notifyDevice_Disappeared() id=" + associationId);

            final AssociationInfo association = getAssociationWithCallerChecks(associationId);
            if (!association.isSelfManaged()) {
                throw new IllegalArgumentException("Association with ID " + associationId
                        + " is not self-managed. notifyDeviceAppeared(int) can only be called for"
                        + " self-managed associations.");
            }

            mDevicePresenceMonitor.onSelfManagedDeviceDisconnected(associationId);
        }

        @Override
        public boolean isCompanionApplicationBound(String packageName, int userId) {
            return mCompanionAppController.isCompanionApplicationBound(userId, packageName);
        }

        private void registerDevicePresenceListenerActive(String packageName, String deviceAddress,
                boolean active) throws RemoteException {
            if (DEBUG) {
                Log.i(TAG, "registerDevicePresenceListenerActive()"
                        + " active=" + active
                        + " deviceAddress=" + deviceAddress);
            }

            getContext().enforceCallingOrSelfPermission(
                    android.Manifest.permission.REQUEST_OBSERVE_COMPANION_DEVICE_PRESENCE,
                    "[un]registerDevicePresenceListenerService");
            final int userId = getCallingUserId();
            enforceCallerIsSystemOr(userId, packageName);

            AssociationInfo association = mAssociationStore.getAssociationsForPackageWithAddress(
                    userId, packageName, deviceAddress);

            if (association == null) {
                throw new RemoteException(new DeviceNotAssociatedException("App " + packageName
                        + " is not associated with device " + deviceAddress
                        + " for user " + userId));
            }

            // If already at specified state, then no-op.
            if (active == association.isNotifyOnDeviceNearby()) {
                if (DEBUG) Log.d(TAG, "Device presence listener is already at desired state.");
                return;
            }

            // AssociationInfo class is immutable: create a new AssociationInfo object with updated
            // flag.
            association = AssociationInfo.builder(association)
                    .setNotifyOnDeviceNearby(active)
                    .build();
            // Do not need to call {@link BleCompanionDeviceScanner#restartScan()} since it will
            // trigger {@link BleCompanionDeviceScanner#restartScan(int, AssociationInfo)} when
            // an application sets/unsets the mNotifyOnDeviceNearby flag.
            mAssociationStore.updateAssociation(association);

            // If device is already present, then trigger callback.
            if (active && mDevicePresenceMonitor.isDevicePresent(association.getId())) {
                if (DEBUG) Log.d(TAG, "Device is already present. Triggering callback.");
                onDeviceAppearedInternal(association.getId());
            }

            // If last listener is unregistered, then unbind application.
            if (!active && !shouldBindPackage(userId, packageName)) {
                if (DEBUG) Log.d(TAG, "Last listener unregistered. Unbinding application.");
                mCompanionAppController.unbindCompanionApplication(userId, packageName);
            }
        }

        @Override
        public void createAssociation(String packageName, String macAddress, int userId,
                byte[] certificate) {
            if (!getContext().getPackageManager().hasSigningCertificate(
                    packageName, certificate, CERT_INPUT_SHA256)) {
                Slog.e(TAG, "Given certificate doesn't match the package certificate.");
                return;
            }

            getContext().enforceCallingOrSelfPermission(
                    android.Manifest.permission.ASSOCIATE_COMPANION_DEVICES, "createAssociation");

            final MacAddress macAddressObj = MacAddress.fromString(macAddress);
            createNewAssociation(userId, packageName, macAddressObj, null, null, false);
        }

        private void checkCanCallNotificationApi(String callingPackage, int userId) {
            enforceCallerIsSystemOr(userId, callingPackage);

            if (getCallingUid() == SYSTEM_UID) return;

            enforceUsesCompanionDeviceFeature(getContext(), userId, callingPackage);
            checkState(!ArrayUtils.isEmpty(
                            mAssociationStore.getAssociationsForPackage(userId, callingPackage)),
                    "App must have an association before calling this API");
        }

        @Override
        public boolean canPairWithoutPrompt(String packageName, String macAddress, int userId) {
            final AssociationInfo association =
                    mAssociationStore.getAssociationsForPackageWithAddress(
                            userId, packageName, macAddress);
            if (association == null) {
                return false;
            }
            return System.currentTimeMillis() - association.getTimeApprovedMs()
                    < PAIR_WITHOUT_PROMPT_WINDOW_MS;
        }

        @Override
        public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
                String[] args, ShellCallback callback, ResultReceiver resultReceiver)
                throws RemoteException {
            new CompanionDeviceShellCommand(CompanionDeviceManagerService.this, mAssociationStore,
                    mDevicePresenceMonitor, mTransportManager, mSystemDataTransferRequestStore,
                    mAssociationRequestsProcessor)
                    .exec(this, in, out, err, args, callback, resultReceiver);
        }

        @Override
        public void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter out,
                @Nullable String[] args) {
            if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, out)) {
                return;
            }

            mAssociationStore.dump(out);
            mDevicePresenceMonitor.dump(out);
            mCompanionAppController.dump(out);
        }
    }

    void createNewAssociation(@UserIdInt int userId, @NonNull String packageName,
            @Nullable MacAddress macAddress, @Nullable CharSequence displayName,
            @Nullable String deviceProfile, boolean isSelfManaged) {
        mAssociationRequestsProcessor.createAssociation(userId, packageName, macAddress,
                displayName, deviceProfile, /* associatedDevice */ null, isSelfManaged,
                /* callback */ null, /* resultReceiver */ null);
    }

    @NonNull
    private Map<String, Set<Integer>> getPreviouslyUsedIdsForUser(@UserIdInt int userId) {
        synchronized (mPreviouslyUsedIds) {
            return getPreviouslyUsedIdsForUserLocked(userId);
        }
    }

    @GuardedBy("mPreviouslyUsedIds")
    @NonNull
    private Map<String, Set<Integer>> getPreviouslyUsedIdsForUserLocked(@UserIdInt int userId) {
        final Map<String, Set<Integer>> usedIdsForUser = mPreviouslyUsedIds.get(userId);
        if (usedIdsForUser == null) {
            return Collections.emptyMap();
        }
        return deepUnmodifiableCopy(usedIdsForUser);
    }

    @GuardedBy("mPreviouslyUsedIds")
    @NonNull
    private Set<Integer> getPreviouslyUsedIdsForPackageLocked(
            @UserIdInt int userId, @NonNull String packageName) {
        // "Deeply unmodifiable" map: the map itself and the Set<Integer> values it contains are all
        // unmodifiable.
        final Map<String, Set<Integer>> usedIdsForUser = getPreviouslyUsedIdsForUserLocked(userId);
        final Set<Integer> usedIdsForPackage = usedIdsForUser.get(packageName);

        if (usedIdsForPackage == null) {
            return Collections.emptySet();
        }

        //The set is already unmodifiable.
        return usedIdsForPackage;
    }

    int getNewAssociationIdForPackage(@UserIdInt int userId, @NonNull String packageName) {
        synchronized (mPreviouslyUsedIds) {
            // First: collect all IDs currently in use for this user's Associations.
            final SparseBooleanArray usedIds = new SparseBooleanArray();

            // We should really only be checking associations for the given user (i.e.:
            // mAssociationStore.getAssociationsForUser(userId)), BUT in the past we've got in a
            // state where association IDs were not assigned correctly in regard to
            // user-to-association-ids-range (e.g. associations with IDs from 1 to 100,000 should
            // always belong to u0), so let's check all the associations.
            for (AssociationInfo it : mAssociationStore.getAssociations()) {
                usedIds.put(it.getId(), true);
            }

            // Second: collect all IDs that have been previously used for this package (and user).
            final Set<Integer> previouslyUsedIds =
                    getPreviouslyUsedIdsForPackageLocked(userId, packageName);

            int id = getFirstAssociationIdForUser(userId);
            final int lastAvailableIdForUser = getLastAssociationIdForUser(userId);

            // Find first ID that isn't used now AND has never been used for the given package.
            while (usedIds.get(id) || previouslyUsedIds.contains(id)) {
                // Increment and try again
                id++;
                // ... but first check if the ID is valid (within the range allocated to the user).
                if (id > lastAvailableIdForUser) {
                    throw new RuntimeException("Cannot create a new Association ID for "
                            + packageName + " for user " + userId);
                }
            }

            return id;
        }
    }

    // TODO: also revoke notification access
    void disassociateInternal(int associationId) {
        final AssociationInfo association = mAssociationStore.getAssociationById(associationId);
        final int userId = association.getUserId();
        final String packageName = association.getPackageName();
        final String deviceProfile = association.getDeviceProfile();

        if (!maybeRemoveRoleHolderForAssociation(association)) {
            // Need to remove the app from list of the role holders, but will have to do it later
            // (the app is in foreground at the moment).
            addToPendingRoleHolderRemoval(association);
        }

        // Need to check if device still present now because CompanionDevicePresenceMonitor will
        // remove current connected device after mAssociationStore.removeAssociation
        final boolean wasPresent = mDevicePresenceMonitor.isDevicePresent(associationId);

        // Removing the association.
        mAssociationStore.removeAssociation(associationId);
        // Do not need to persistUserState since CompanionDeviceManagerService will get callback
        // from #onAssociationChanged, and it will handle the persistUserState which including
        // active and revoked association.
        logRemoveAssociation(deviceProfile);

        // Remove all the system data transfer requests for the association.
        mSystemDataTransferRequestStore.removeRequestsByAssociationId(userId, associationId);

        if (!wasPresent || !association.isNotifyOnDeviceNearby()) return;
        // The device was connected and the app was notified: check if we need to unbind the app
        // now.
        final boolean shouldStayBound = any(
                mAssociationStore.getAssociationsForPackage(userId, packageName),
                it -> it.isNotifyOnDeviceNearby()
                        && mDevicePresenceMonitor.isDevicePresent(it.getId()));
        if (shouldStayBound) return;
        mCompanionAppController.unbindCompanionApplication(userId, packageName);
    }

    /**
     * First, checks if the companion application should be removed from the list role holders when
     * upon association's removal, i.e.: association's profile (matches the role) is not null,
     * the application does not have other associations with the same profile, etc.
     *
     * <p>
     * Then, if establishes that the application indeed has to be removed from the list of the role
     * holders, checks if it could be done right now -
     * {@link android.app.role.RoleManager#removeRoleHolderAsUser(String, String, int, UserHandle, java.util.concurrent.Executor, java.util.function.Consumer) RoleManager#removeRoleHolderAsUser()}
     * will kill the application's process, which leads poor user experience if the application was
     * in foreground when this happened, to avoid this CDMS delays invoking
     * {@code RoleManager.removeRoleHolderAsUser()} until the app is no longer in foreground.
     *
     * @return {@code true} if the application does NOT need be removed from the list of the role
     *         holders OR if the application was successfully removed from the list of role holders.
     *         I.e.: from the role-management perspective the association is done with.
     *         {@code false} if the application needs to be removed from the list of role the role
     *         holders, BUT it CDMS would prefer to do it later.
     *         I.e.: application is in the foreground at the moment, but invoking
     *         {@code RoleManager.removeRoleHolderAsUser()} will kill the application's process,
     *         which would lead to the poor UX, hence need to try later.
     */

    private boolean maybeRemoveRoleHolderForAssociation(@NonNull AssociationInfo association) {
        if (DEBUG) Log.d(TAG, "maybeRemoveRoleHolderForAssociation() association=" + association);

        final String deviceProfile = association.getDeviceProfile();
        if (deviceProfile == null) {
            // No role was granted to for this association, there is nothing else we need to here.
            return true;
        }
        // Do not need to remove the system role since it was pre-granted by the system.
        if (deviceProfile.equals(DEVICE_PROFILE_AUTOMOTIVE_PROJECTION)) {
            return true;
        }

        // Check if the applications is associated with another devices with the profile. If so,
        // it should remain the role holder.
        final int id = association.getId();
        final int userId = association.getUserId();
        final String packageName = association.getPackageName();
        final boolean roleStillInUse = any(
                mAssociationStore.getAssociationsForPackage(userId, packageName),
                it -> deviceProfile.equals(it.getDeviceProfile()) && id != it.getId());
        if (roleStillInUse) {
            // Application should remain a role holder, there is nothing else we need to here.
            return true;
        }

        final int packageProcessImportance = getPackageProcessImportance(userId, packageName);
        if (packageProcessImportance <= IMPORTANCE_VISIBLE) {
            // Need to remove the app from the list of role holders, but the process is visible to
            // the user at the moment, so we'll need to it later: log and return false.
            Slog.i(TAG, "Cannot remove role holder for the removed association id=" + id
                    + " now - process is visible.");
            return false;
        }

        removeRoleHolderForAssociation(getContext(), association);
        return true;
    }

    private int getPackageProcessImportance(@UserIdInt int userId, @NonNull String packageName) {
        return Binder.withCleanCallingIdentity(() -> {
            final int uid =
                    mPackageManagerInternal.getPackageUid(packageName, /* flags */0, userId);
            return mActivityManager.getUidImportance(uid);
        });
    }

    /**
     * Set revoked flag for active association and add the revoked association and the uid into
     * the caches.
     *
     * @see #mRevokedAssociationsPendingRoleHolderRemoval
     * @see #mUidsPendingRoleHolderRemoval
     * @see OnPackageVisibilityChangeListener
     */
    private void addToPendingRoleHolderRemoval(@NonNull AssociationInfo association) {
        // First: set revoked flag.
        association = AssociationInfo.builder(association)
                .setRevoked(true)
                .build();

        final String packageName = association.getPackageName();
        final int userId = association.getUserId();
        final int uid = mPackageManagerInternal.getPackageUid(packageName, /* flags */0, userId);

        // Second: add to the set.
        synchronized (mRevokedAssociationsPendingRoleHolderRemoval) {
            mRevokedAssociationsPendingRoleHolderRemoval.forUser(association.getUserId())
                    .add(association);
            if (!mUidsPendingRoleHolderRemoval.containsKey(uid)) {
                mUidsPendingRoleHolderRemoval.put(uid, packageName);

                if (mUidsPendingRoleHolderRemoval.size() == 1) {
                    // Just added first uid: start the listener
                    mOnPackageVisibilityChangeListener.startListening();
                }
            }
        }
    }

    /**
     * Remove the revoked association from the cache and also remove the uid from the map if
     * there are other associations with the same package still pending for role holder removal.
     *
     * @see #mRevokedAssociationsPendingRoleHolderRemoval
     * @see #mUidsPendingRoleHolderRemoval
     * @see OnPackageVisibilityChangeListener
     */
    private void removeFromPendingRoleHolderRemoval(@NonNull AssociationInfo association) {
        final String packageName = association.getPackageName();
        final int userId = association.getUserId();
        final int uid = mPackageManagerInternal.getPackageUid(packageName, /* flags */0, userId);

        synchronized (mRevokedAssociationsPendingRoleHolderRemoval) {
            mRevokedAssociationsPendingRoleHolderRemoval.forUser(userId)
                    .remove(association);

            final boolean shouldKeepUidForRemoval = any(
                    getPendingRoleHolderRemovalAssociationsForUser(userId),
                    ai -> packageName.equals(ai.getPackageName()));
            // Do not remove the uid from the map since other associations with
            // the same packageName still pending for role holder removal.
            if (!shouldKeepUidForRemoval) {
                mUidsPendingRoleHolderRemoval.remove(uid);
            }

            if (mUidsPendingRoleHolderRemoval.isEmpty()) {
                // The set is empty now - can "turn off" the listener.
                mOnPackageVisibilityChangeListener.stopListening();
            }
        }
    }

    /**
     * @return a copy of the revoked associations set (safeguarding against
     *         {@code ConcurrentModificationException}-s).
     */
    private @NonNull Set<AssociationInfo> getPendingRoleHolderRemovalAssociationsForUser(
            @UserIdInt int userId) {
        synchronized (mRevokedAssociationsPendingRoleHolderRemoval) {
            // Return a copy.
            return new ArraySet<>(mRevokedAssociationsPendingRoleHolderRemoval.forUser(userId));
        }
    }

    private String getPackageNameByUid(int uid) {
        synchronized (mRevokedAssociationsPendingRoleHolderRemoval) {
            return mUidsPendingRoleHolderRemoval.get(uid);
        }
    }

    void updateSpecialAccessPermissionForAssociatedPackage(AssociationInfo association) {
        final PackageInfo packageInfo =
                getPackageInfo(getContext(), association.getUserId(), association.getPackageName());

        Binder.withCleanCallingIdentity(() -> updateSpecialAccessPermissionAsSystem(packageInfo));
    }

    private void updateSpecialAccessPermissionAsSystem(PackageInfo packageInfo) {
        if (packageInfo == null) {
            return;
        }
        if (containsEither(packageInfo.requestedPermissions,
                android.Manifest.permission.RUN_IN_BACKGROUND,
                android.Manifest.permission.REQUEST_COMPANION_RUN_IN_BACKGROUND)) {
            mPowerWhitelistManager.addToWhitelist(packageInfo.packageName);
        } else {
            try {
                mPowerWhitelistManager.removeFromWhitelist(packageInfo.packageName);
            } catch (UnsupportedOperationException e) {
                Slog.w(TAG, packageInfo.packageName + " can't be removed from power save"
                        + " whitelist. It might due to the package is whitelisted by the system.");
            }
        }

        NetworkPolicyManager networkPolicyManager = NetworkPolicyManager.from(getContext());
        try {
            if (containsEither(packageInfo.requestedPermissions,
                    android.Manifest.permission.USE_DATA_IN_BACKGROUND,
                    android.Manifest.permission.REQUEST_COMPANION_USE_DATA_IN_BACKGROUND)) {
                networkPolicyManager.addUidPolicy(
                        packageInfo.applicationInfo.uid,
                        NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND);
            } else {
                networkPolicyManager.removeUidPolicy(
                        packageInfo.applicationInfo.uid,
                        NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND);
            }
        } catch (IllegalArgumentException e) {
            Slog.e(TAG, e.getMessage());
        }

        exemptFromAutoRevoke(packageInfo.packageName, packageInfo.applicationInfo.uid);
    }

    private void exemptFromAutoRevoke(String packageName, int uid) {
        try {
            mAppOpsManager.setMode(
                    AppOpsManager.OP_AUTO_REVOKE_PERMISSIONS_IF_UNUSED,
                    uid,
                    packageName,
                    AppOpsManager.MODE_IGNORED);
        } catch (RemoteException e) {
            Slog.w(TAG, "Error while granting auto revoke exemption for " + packageName, e);
        }
    }

    private void updateAtm(int userId, List<AssociationInfo> associations) {
        final Set<Integer> companionAppUids = new ArraySet<>();
        for (AssociationInfo association : associations) {
            final int uid = mPackageManagerInternal.getPackageUid(association.getPackageName(),
                    0, userId);
            if (uid >= 0) {
                companionAppUids.add(uid);
            }
        }
        if (mAtmInternal != null) {
            mAtmInternal.setCompanionAppUids(userId, companionAppUids);
        }
        if (mAmInternal != null) {
            // Make a copy of the set and send it to ActivityManager.
            mAmInternal.setCompanionAppUids(userId, new ArraySet<>(companionAppUids));
        }
    }

    private void maybeGrantAutoRevokeExemptions() {
        Slog.d(TAG, "maybeGrantAutoRevokeExemptions()");

        PackageManager pm = getContext().getPackageManager();
        for (int userId : LocalServices.getService(UserManagerInternal.class).getUserIds()) {
            SharedPreferences pref = getContext().getSharedPreferences(
                    new File(Environment.getUserSystemDirectory(userId), PREF_FILE_NAME),
                    Context.MODE_PRIVATE);
            if (pref.getBoolean(PREF_KEY_AUTO_REVOKE_GRANTS_DONE, false)) {
                continue;
            }

            try {
                final List<AssociationInfo> associations =
                        mAssociationStore.getAssociationsForUser(userId);
                for (AssociationInfo a : associations) {
                    try {
                        int uid = pm.getPackageUidAsUser(a.getPackageName(), userId);
                        exemptFromAutoRevoke(a.getPackageName(), uid);
                    } catch (PackageManager.NameNotFoundException e) {
                        Slog.w(TAG, "Unknown companion package: " + a.getPackageName(), e);
                    }
                }
            } finally {
                pref.edit().putBoolean(PREF_KEY_AUTO_REVOKE_GRANTS_DONE, true).apply();
            }
        }
    }

    private final AssociationStore.OnChangeListener mAssociationStoreChangeListener =
            new AssociationStore.OnChangeListener() {
        @Override
        public void onAssociationChanged(int changeType, AssociationInfo association) {
            onAssociationChangedInternal(changeType, association);
        }
    };

    private final CompanionDevicePresenceMonitor.Callback mDevicePresenceCallback =
            new CompanionDevicePresenceMonitor.Callback() {
        @Override
        public void onDeviceAppeared(int associationId) {
            onDeviceAppearedInternal(associationId);
        }

        @Override
        public void onDeviceDisappeared(int associationId) {
            onDeviceDisappearedInternal(associationId);
        }
    };

    private final PackageMonitor mPackageMonitor = new PackageMonitor() {
        @Override
        public void onPackageRemoved(String packageName, int uid) {
            onPackageRemoveOrDataClearedInternal(getChangingUserId(), packageName);
        }

        @Override
        public void onPackageDataCleared(String packageName, int uid) {
            onPackageRemoveOrDataClearedInternal(getChangingUserId(), packageName);
        }

        @Override
        public void onPackageModified(String packageName) {
            onPackageModifiedInternal(getChangingUserId(), packageName);
        }
    };

    static int getFirstAssociationIdForUser(@UserIdInt int userId) {
        // We want the IDs to start from 1, not 0.
        return userId * ASSOCIATIONS_IDS_PER_USER_RANGE + 1;
    }

    static int getLastAssociationIdForUser(@UserIdInt int userId) {
        return (userId + 1) * ASSOCIATIONS_IDS_PER_USER_RANGE;
    }

    private static Map<String, Set<Integer>> deepUnmodifiableCopy(Map<String, Set<Integer>> orig) {
        final Map<String, Set<Integer>> copy = new HashMap<>();

        for (Map.Entry<String, Set<Integer>> entry : orig.entrySet()) {
            final Set<Integer> valueCopy = new HashSet<>(entry.getValue());
            copy.put(entry.getKey(), Collections.unmodifiableSet(valueCopy));
        }

        return Collections.unmodifiableMap(copy);
    }

    private static <T> boolean containsEither(T[] array, T a, T b) {
        return ArrayUtils.contains(array, a) || ArrayUtils.contains(array, b);
    }

    private class LocalService implements CompanionDeviceManagerServiceInternal {
        @Override
        public void removeInactiveSelfManagedAssociations() {
            CompanionDeviceManagerService.this.removeInactiveSelfManagedAssociations();
        }

        @Override
        public void registerCallMetadataSyncCallback(CrossDeviceSyncControllerCallback callback,
                @CrossDeviceSyncControllerCallback.Type int type) {
            if (CompanionDeviceConfig.isEnabled(
                    CompanionDeviceConfig.ENABLE_CONTEXT_SYNC_TELECOM)) {
                mCrossDeviceSyncController.registerCallMetadataSyncCallback(callback, type);
            }
        }

        @Override
        public void crossDeviceSync(int userId, Collection<CrossDeviceCall> calls) {
            if (CompanionDeviceConfig.isEnabled(
                    CompanionDeviceConfig.ENABLE_CONTEXT_SYNC_TELECOM)) {
                mCrossDeviceSyncController.syncToAllDevicesForUserId(userId, calls);
            }
        }

        @Override
        public void crossDeviceSync(AssociationInfo associationInfo,
                Collection<CrossDeviceCall> calls) {
            if (CompanionDeviceConfig.isEnabled(
                    CompanionDeviceConfig.ENABLE_CONTEXT_SYNC_TELECOM)) {
                mCrossDeviceSyncController.syncToSingleDevice(associationInfo, calls);
            }
        }

        @Override
        public void sendCrossDeviceSyncMessage(int associationId, byte[] message) {
            if (CompanionDeviceConfig.isEnabled(
                    CompanionDeviceConfig.ENABLE_CONTEXT_SYNC_TELECOM)) {
                mCrossDeviceSyncController.syncMessageToDevice(associationId, message);
            }
        }

        @Override
        public void sendCrossDeviceSyncMessageToAllDevices(int userId, byte[] message) {
            if (CompanionDeviceConfig.isEnabled(
                    CompanionDeviceConfig.ENABLE_CONTEXT_SYNC_TELECOM)) {
                mCrossDeviceSyncController.syncMessageToAllDevicesForUserId(userId, message);
            }
        }

        @Override
        public void addSelfOwnedCallId(String callId) {
            if (CompanionDeviceConfig.isEnabled(
                    CompanionDeviceConfig.ENABLE_CONTEXT_SYNC_TELECOM)) {
                mCrossDeviceSyncController.addSelfOwnedCallId(callId);
            }
        }

        @Override
        public void removeSelfOwnedCallId(String callId) {
            if (CompanionDeviceConfig.isEnabled(
                    CompanionDeviceConfig.ENABLE_CONTEXT_SYNC_TELECOM)) {
                mCrossDeviceSyncController.removeSelfOwnedCallId(callId);
            }
        }
    }

    /**
     * This method must only be called from {@link CompanionDeviceShellCommand} for testing
     * purposes only!
     */
    void persistState() {
        mUserPersistenceHandler.clearMessages();
        for (UserInfo user : mUserManager.getAliveUsers()) {
            persistStateForUser(user.id);
        }
    }

    /**
     * This class is dedicated to handling requests to persist user state.
     */
    @SuppressLint("HandlerLeak")
    private class PersistUserStateHandler extends Handler {
        PersistUserStateHandler() {
            super(BackgroundThread.get().getLooper());
        }

        /**
         * Persists user state unless there is already an outstanding request for the given user.
         */
        synchronized void postPersistUserState(@UserIdInt int userId) {
            if (!hasMessages(userId)) {
                sendMessage(obtainMessage(userId));
            }
        }

        /**
         * Clears *ALL* outstanding persist requests for *ALL* users.
         */
        synchronized void clearMessages() {
            removeCallbacksAndMessages(null);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            final int userId = msg.what;
            persistStateForUser(userId);
        }
    }

    /**
     * An OnUidImportanceListener class which watches the importance of the packages.
     * In this class, we ONLY interested in the importance of the running process is greater than
     * {@link RunningAppProcessInfo.IMPORTANCE_VISIBLE} for the uids have been added into the
     * {@link mUidsPendingRoleHolderRemoval}. Lastly remove the role holder for the revoked
     * associations for the same packages.
     *
     * @see #maybeRemoveRoleHolderForAssociation(AssociationInfo)
     * @see #removeFromPendingRoleHolderRemoval(AssociationInfo)
     * @see #getPendingRoleHolderRemovalAssociationsForUser(int)
     */
    private class OnPackageVisibilityChangeListener implements
            ActivityManager.OnUidImportanceListener {
        final @NonNull ActivityManager mAm;

        OnPackageVisibilityChangeListener(@NonNull ActivityManager am) {
            this.mAm = am;
        }

        void startListening() {
            Binder.withCleanCallingIdentity(
                    () -> mAm.addOnUidImportanceListener(
                            /* listener */ OnPackageVisibilityChangeListener.this,
                            RunningAppProcessInfo.IMPORTANCE_VISIBLE));
        }

        void stopListening() {
            Binder.withCleanCallingIdentity(
                    () -> mAm.removeOnUidImportanceListener(
                            /* listener */ OnPackageVisibilityChangeListener.this));
        }

        @Override
        public void onUidImportance(int uid, int importance) {
            if (importance <= RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
                // The lower the importance value the more "important" the process is.
                // We are only interested when the process ceases to be visible.
                return;
            }

            final String packageName = getPackageNameByUid(uid);
            if (packageName == null) {
                // Not interested in this uid.
                return;
            }

            final int userId = UserHandle.getUserId(uid);

            boolean needToPersistStateForUser = false;

            for (AssociationInfo association :
                    getPendingRoleHolderRemovalAssociationsForUser(userId)) {
                if (!packageName.equals(association.getPackageName())) continue;

                if (!maybeRemoveRoleHolderForAssociation(association)) {
                    // Did not remove the role holder, will have to try again later.
                    continue;
                }

                removeFromPendingRoleHolderRemoval(association);
                needToPersistStateForUser = true;
            }

            if (needToPersistStateForUser) {
                mUserPersistenceHandler.postPersistUserState(userId);
            }
        }
    }

    private static class PerUserAssociationSet extends PerUser<Set<AssociationInfo>> {
        @Override
        protected @NonNull Set<AssociationInfo> create(int userId) {
            return new ArraySet<>();
        }
    }
}