summaryrefslogtreecommitdiff
path: root/common/device-side/bedstead/nene/src/main/java/com/android/bedstead/nene/packages/Package.java
blob: 1217a4fc23734a5e94f3941a069a86cb28cb54e1 (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
/*
 * Copyright (C) 2021 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.bedstead.nene.packages;

import static android.Manifest.permission.FORCE_STOP_PACKAGES;
import static android.Manifest.permission.QUERY_ALL_PACKAGES;
import static android.content.pm.ApplicationInfo.FLAG_STOPPED;
import static android.content.pm.ApplicationInfo.FLAG_SYSTEM;
import static android.content.pm.PackageManager.GET_PERMISSIONS;
import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static android.content.pm.PermissionInfo.PROTECTION_DANGEROUS;
import static android.content.pm.PermissionInfo.PROTECTION_FLAG_DEVELOPMENT;
import static android.os.Build.VERSION_CODES.P;
import static android.os.Build.VERSION_CODES.S;
import static android.os.Process.myUid;

import static com.android.bedstead.nene.permissions.CommonPermissions.CHANGE_COMPONENT_ENABLED_STATE;
import static com.android.bedstead.nene.permissions.CommonPermissions.INTERACT_ACROSS_USERS_FULL;
import static com.android.bedstead.nene.permissions.CommonPermissions.MANAGE_ROLE_HOLDERS;

import static com.google.common.truth.Truth.assertWithMessage;

import static org.junit.Assert.fail;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.role.RoleManager;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.CrossProfileApps;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PermissionInfo;
import android.os.Build;
import android.os.UserHandle;
import android.util.Log;

import androidx.annotation.Nullable;

import com.android.bedstead.nene.TestApis;
import com.android.bedstead.nene.annotations.Experimental;
import com.android.bedstead.nene.appops.AppOps;
import com.android.bedstead.nene.devicepolicy.DeviceOwner;
import com.android.bedstead.nene.devicepolicy.ProfileOwner;
import com.android.bedstead.nene.exceptions.AdbException;
import com.android.bedstead.nene.exceptions.AdbParseException;
import com.android.bedstead.nene.exceptions.NeneException;
import com.android.bedstead.nene.permissions.PermissionContext;
import com.android.bedstead.nene.permissions.Permissions;
import com.android.bedstead.nene.roles.RoleContext;
import com.android.bedstead.nene.users.UserReference;
import com.android.bedstead.nene.utils.Poll;
import com.android.bedstead.nene.utils.Retry;
import com.android.bedstead.nene.utils.ShellCommand;
import com.android.bedstead.nene.utils.ShellCommandUtils;
import com.android.bedstead.nene.utils.Versions;
import com.android.compatibility.common.util.BlockingBroadcastReceiver;
import com.android.compatibility.common.util.BlockingCallback.DefaultBlockingCallback;

import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * A representation of a package on device which may or may not exist.
 */
public final class Package {
    private static final String LOG_TAG = "PackageReference";
    private static final int PIDS_PER_USER_ID = 100000;
    private static final PackageManager sPackageManager =
            TestApis.context().instrumentedContext().getPackageManager();
    private static final RoleManager sRoleManager = TestApis.context().instrumentedContext()
            .getSystemService(RoleManager.class);

    private final String mPackageName;

    /**
     * Constructs a new {@link Package} from the provided {@code packageName}.
     */
    public static Package of(String packageName) {
        return new Package(packageName);
    }

    Package(String packageName) {
        mPackageName = packageName;
    }

    /** Return the package's name. */
    public String packageName() {
        return mPackageName;
    }

    /**
     * Install the package on the given user.
     *
     * <p>If you wish to install a package which is not already installed on another user, see
     * {@link Packages#install(UserReference, File)}.
     */
    public Package installExisting(UserReference user) {
        if (user == null) {
            throw new NullPointerException();
        }

        try {
            // Expected output "Package X installed for user: Y"
            ShellCommand.builderForUser(user, "cmd package install-existing")
                    .addOperand(mPackageName)
                    .validate(
                            (output) -> output.contains("installed for user"))
                    .execute();

            return this;
        } catch (AdbException e) {
            throw new NeneException("Could not install-existing package " + this, e);
        }
    }

    /**
     * Install this package on the given user, using {@link #installExisting(UserReference)} if
     * possible, otherwise installing fresh.
     */
    public Package install(UserReference user, File apkFile) {
        if (exists()) {
            return installExisting(user);
        }

        return TestApis.packages().install(user, apkFile);
    }

    /**
     * Install this package on the given user, using {@link #installExisting(UserReference)} if
     * possible, otherwise installing fresh.
     */
    public Package install(UserReference user, Supplier<File> apkFile) {
        if (exists()) {
            return installExisting(user);
        }

        return TestApis.packages().install(user, apkFile.get());
    }

    /**
     * Install this package on the given user, using {@link #installExisting(UserReference)} if
     * possible, otherwise installing fresh.
     */
    public Package installBytes(UserReference user, byte[] apkFile) {
        if (exists()) {
            return installExisting(user);
        }

        return TestApis.packages().install(user, apkFile);
    }

    /**
     * Install this package on the given user, using {@link #installExisting(UserReference)} if
     * possible, otherwise installing fresh.
     */
    public Package installBytes(UserReference user, Supplier<byte[]> apkFile) {
        if (exists()) {
            return installExisting(user);
        }

        return TestApis.packages().install(user, apkFile.get());
    }

    /**
     * Uninstall the package for all users.
     */
    public Package uninstallFromAllUsers() {
        for (UserReference user : installedOnUsers()) {
            uninstall(user);
        }

        return this;
    }

    /**
     * Uninstall the package for the given user.
     *
     * <p>If the package is not installed for the given user, nothing will happen.
     */
    public Package uninstall(UserReference user) {
        if (user == null) {
            throw new NullPointerException();
        }

        IntentFilter packageRemovedIntentFilter =
                new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
        packageRemovedIntentFilter.addDataScheme("package");

        // This is outside of the try because we don't want to await if the package isn't installed
        BlockingBroadcastReceiver broadcastReceiver = BlockingBroadcastReceiver.create(
                TestApis.context().androidContextAsUser(user),
                packageRemovedIntentFilter);

        try {

            boolean canWaitForBroadcast = false;
            if (Versions.meetsMinimumSdkVersionRequirement(Build.VERSION_CODES.R)) {
                try (PermissionContext p = TestApis.permissions().withPermission(
                        INTERACT_ACROSS_USERS_FULL)) {
                    broadcastReceiver.register();
                }
                canWaitForBroadcast = true;
            } else if (user.equals(TestApis.users().instrumented())) {
                broadcastReceiver.register();
                canWaitForBroadcast = true;
            }

            String commandOutput = Poll.forValue(() -> {
                // Expected output "Success"
                return ShellCommand.builderForUser(user, "pm uninstall")
                        .addOperand(mPackageName)
                        .execute();
            }).toMeet(output -> output.toUpperCase().startsWith("SUCCESS")
                    || output.toUpperCase().contains("NOT INSTALLED FOR"))
                    .terminalValue((output) -> {
                        if (output.contains("DELETE_FAILED_DEVICE_POLICY_MANAGER")) {
                            // A recently-removed device policy manager can't be removed - but won't
                            // show as DPC

                            DeviceOwner deviceOwner = TestApis.devicePolicy().getDeviceOwner();
                            if (deviceOwner != null && deviceOwner.pkg().equals(this)) {
                                // Terminal, can't remove actual DO
                                return true;
                            }
                            ProfileOwner profileOwner =
                                    TestApis.devicePolicy().getProfileOwner(user);
                            // Terminal, can't remove actual PO
                            return profileOwner != null && profileOwner.pkg().equals(this);

                            // Not PO or DO, likely temporary failure
                        }

                        return true;
                    })
                    .errorOnFail()
                    .await();

            if (commandOutput.toUpperCase().startsWith("SUCCESS")) {
                if (canWaitForBroadcast) {
                    broadcastReceiver.awaitForBroadcastOrFail();
                } else {
                    try {
                        // On versions prior to R - cross user installs can't block for broadcasts
                        // so we have an arbitrary sleep
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        Log.i(LOG_TAG, "Interrupted waiting for package uninstallation", e);
                    }
                }
            }
            return this;
        } catch (NeneException e) {
            throw new NeneException("Could not uninstall package " + this, e);
        } finally {
            broadcastReceiver.unregisterQuietly();
        }
    }

    /**
     * Enable this package for the given {@link UserReference}.
     */
    @Experimental
    public Package enable(UserReference user) {
        try {
            ShellCommand.builderForUser(user, "pm enable")
                    .addOperand(mPackageName)
                    .validate(o -> o.contains("new state"))
                    .execute();
        } catch (AdbException e) {
            throw new NeneException("Error enabling package " + this + " for user " + user, e);
        }
        return this;
    }

    /**
     * Enable this package on the instrumented user.
     */
    @Experimental
    public Package enable() {
        return enable(TestApis.users().instrumented());
    }

    /**
     * Disable this package for the given {@link UserReference}.
     */
    @Experimental
    public Package disable(UserReference user) {
        try {
            // TODO(279387509): "pm disable" is currently broken for packages - restore to normal
            //  disable when fixed
            ShellCommand.builderForUser(user, "pm disable-user")
                    .addOperand(mPackageName)
                    .validate(o -> o.contains("new state"))
                    .execute();
        } catch (AdbException e) {
            throw new NeneException("Error disabling package " + this + " for user " + user, e);
        }
        return this;
    }

    /**
     * Disable this package on the instrumented user.
     */
    @Experimental
    public Package disable() {
        return disable(TestApis.users().instrumented());
    }

    /**
     * Get a reference to the given {@code componentName} within this package.
     *
     * <p>This does not guarantee that the component exists.
     */
    @Experimental
    public ComponentReference component(String componentName) {
        return new ComponentReference(this, componentName);
    }

    /**
     * Grant a permission for the package on the given user.
     *
     * <p>The package must be installed on the user, must request the given permission, and the
     * permission must be a runtime permission.
     */
    public Package grantPermission(UserReference user, String permission) {
        // There is no readable output upon failure so we need to check ourselves
        checkCanGrantOrRevokePermission(user, permission);

        try {
            ShellCommand.builderForUser(user, "pm grant")
                    .addOperand(packageName())
                    .addOperand(permission)
                    .allowEmptyOutput(true)
                    .validate(String::isEmpty)
                    .execute();

            assertWithMessage("Error granting permission " + permission
                    + " to package " + this + " on user " + user
                    + ". Command appeared successful but not set.")
                    .that(hasPermission(user, permission)).isTrue();

            return this;
        } catch (AdbException e) {
            throw new NeneException("Error granting permission " + permission + " to package "
                    + this + " on user " + user, e);
        }
    }

    /** Grant the {@code permission} on the instrumented user. */
    public Package grantPermission(String permission) {
        return grantPermission(TestApis.users().instrumented(), permission);
    }

    /** Deny the {@code permission} on the instrumented user. */
    public Package denyPermission(String permission) {
        return denyPermission(TestApis.users().instrumented(), permission);
    }

    /**
     * Deny a permission for the package on the given user.
     *
     * <p>The package must be installed on the user, must request the given permission, and the
     * permission must be a runtime permission.
     *
     * <p>You can not deny permissions for the current package on the current user.
     */
    public Package denyPermission(UserReference user, String permission) {
        if (!hasPermission(user, permission)) {
            return this; // Already denied
        }

        // There is no readable output upon failure so we need to check ourselves
        checkCanGrantOrRevokePermission(user, permission);

        if (packageName().equals(TestApis.context().instrumentedContext().getPackageName())
                && user.equals(TestApis.users().instrumented())) {
            throw new NeneException("Cannot deny permission from current package");
        }

        try {
            ShellCommand.builderForUser(user, "pm revoke")
                    .addOperand(packageName())
                    .addOperand(permission)
                    .allowEmptyOutput(true)
                    .validate(String::isEmpty)
                    .execute();

            assertWithMessage("Error denying permission " + permission
                    + " to package " + this + " on user " + user
                    + ". Command appeared successful but not revoked.")
                    .that(hasPermission(user, permission)).isFalse();

            return this;
        } catch (AdbException e) {
            throw new NeneException("Error denying permission " + permission + " to package "
                    + this + " on user " + user, e);
        }
    }

    void checkCanGrantOrRevokePermission(UserReference user, String permission) {
        if (!installedOnUser(user)) {
            throw new NeneException("Attempting to grant " + permission + " to " + this
                    + " on user " + user + ". But it is not installed");
        }

        try {
            PermissionInfo permissionInfo =
                    sPackageManager.getPermissionInfo(permission, /* flags= */ 0);

            if (!protectionIsDangerous(permissionInfo.protectionLevel)
                    && !protectionIsDevelopment(permissionInfo.protectionLevel)) {
                throw new NeneException("Cannot grant non-runtime permission "
                        + permission + ", protection level is " + permissionInfo.protectionLevel);
            }

            if (!requestedPermissions().contains(permission)) {
                throw new NeneException("Cannot grant permission "
                        + permission + " which was not requested by package " + packageName());
            }
        } catch (PackageManager.NameNotFoundException e) {
            throw new NeneException("Permission does not exist: " + permission);
        }
    }

    private boolean protectionIsDangerous(int protectionLevel) {
        return (protectionLevel & PROTECTION_DANGEROUS) != 0;
    }

    private boolean protectionIsDevelopment(int protectionLevel) {
        return (protectionLevel & PROTECTION_FLAG_DEVELOPMENT) != 0;
    }

    /** Get running {@link ProcessReference} for this package on all users. */
    @Experimental
    public Set<ProcessReference> runningProcesses() {
        // TODO(scottjonathan): See if this can be remade using
        //  ActivityManager#getRunningappProcesses
        try {
            return ShellCommand.builder("ps")
                    .addOperand("-A")
                    .addOperand("-n")
                    .executeAndParseOutput(o -> parsePsOutput(o).stream()
                            .filter(p -> p.mPackageName.equals(mPackageName))
                            .map(p -> new ProcessReference(this, p.mPid, p.mUid,
                                    TestApis.users().find(p.mUserId))))
                    .collect(Collectors.toSet());
        } catch (AdbException e) {
            throw new NeneException("Error getting running processes ", e);
        }
    }

    private Set<ProcessInfo> parsePsOutput(String psOutput) {
        return Arrays.stream(psOutput.split("\n"))
                .skip(1) // Skip the title line
                .map(s -> s.split("\\s+"))
                .map(m -> new ProcessInfo(
                        m[8], Integer.parseInt(m[1]),
                        Integer.parseInt(m[0]),
                        Integer.parseInt(m[0]) / PIDS_PER_USER_ID))
                .collect(Collectors.toSet());
    }

    /** Get the running {@link ProcessReference} for this package on the given user. */
    @Experimental
    @Nullable
    public ProcessReference runningProcess(UserReference user) {
        ProcessReference p = runningProcesses().stream().filter(
                i -> i.user().equals(user))
                .findAny()
                .orElse(null);
        return p;
    }

    /** Get the running {@link ProcessReference} for this package on the given user. */
    @Experimental
    @Nullable
    public ProcessReference runningProcess(UserHandle user) {
        return runningProcess(TestApis.users().find(user));
    }

    /** Get the running {@link ProcessReference} for this package on the instrumented user. */
    @Experimental
    @Nullable
    public ProcessReference runningProcess() {
        return runningProcess(TestApis.users().instrumented());
    }

    /** {@code true} if the package is installed on the given user. */
    public boolean installedOnUser(UserHandle userHandle) {
        return installedOnUser(TestApis.users().find(userHandle));
    }

    /** {@code true} if the package is installed on the given user. */
    public boolean installedOnUser(UserReference user) {
        return packageInfoForUser(user, /* flags= */ 0) != null;
    }

    /** {@code true} if the package is installed on the instrumented user. */
    public boolean installedOnUser() {
        return installedOnUser(TestApis.users().instrumented());
    }

    /** {@code true} if the package on the given user has the given permission. */
    public boolean hasPermission(UserReference user, String permission) {
        return TestApis.context().androidContextAsUser(user).getPackageManager()
                .checkPermission(permission, mPackageName) == PERMISSION_GRANTED;
    }

    /** {@code true} if the package on the given user has the given permission. */
    public boolean hasPermission(UserHandle user, String permission) {
        return hasPermission(TestApis.users().find(user), permission);
    }

    /** {@code true} if the package on the instrumented user has the given permission. */
    public boolean hasPermission(String permission) {
        return hasPermission(TestApis.users().instrumented(), permission);
    }

    /** Get the permissions requested in the package's manifest. */
    public Set<String> requestedPermissions() {
        PackageInfo packageInfo = packageInfoFromAnyUser(GET_PERMISSIONS);

        if (packageInfo == null) {
            if (TestApis.packages().instrumented().isInstantApp()) {
                Log.i(LOG_TAG, "Tried to get requestedPermissions for "
                        + mPackageName + " but can't on instant apps");
                return new HashSet<>();
            }
            throw new NeneException("Error getting requestedPermissions, does not exist");
        }

        if (packageInfo.requestedPermissions == null) {
            return new HashSet<>();
        }

        return new HashSet<>(Arrays.asList(packageInfo.requestedPermissions));
    }

    @Nullable
    private PackageInfo packageInfoFromAnyUser(int flags) {
        return TestApis.users().all().stream()
                .map(i -> packageInfoForUser(i, flags))
                .filter(Objects::nonNull)
                .findFirst()
                .orElse(null);
    }

    @Nullable
    private PackageInfo packageInfoForUser(UserReference user, int flags) {
        if (TestApis.packages().instrumented().isInstantApp()
                || !Versions.meetsMinimumSdkVersionRequirement(S)) {
            // Can't call API's directly
            return packageInfoForUserPreS(user, flags);
        }

        if (user.equals(TestApis.users().instrumented())) {
            try {
                return TestApis.context().instrumentedContext()
                        .getPackageManager()
                        .getPackageInfo(mPackageName, /* flags= */ flags);
            } catch (PackageManager.NameNotFoundException e) {
                Log.e(LOG_TAG, "Could not find package " + this + " on user " + user, e);
                return null;
            }
        }

        if (Permissions.sIgnorePermissions.get()) {
            try {
                return TestApis.context().androidContextAsUser(user)
                        .getPackageManager()
                        .getPackageInfo(mPackageName, /* flags= */ flags);
            } catch (PackageManager.NameNotFoundException e) {
                return null;
            }
        } else {
            try (PermissionContext p = TestApis.permissions().withPermission(
                    INTERACT_ACROSS_USERS_FULL)) {
                return TestApis.context().androidContextAsUser(user)
                        .getPackageManager()
                        .getPackageInfo(mPackageName, /* flags= */ flags);
            } catch (PackageManager.NameNotFoundException e) {
                return null;
            }
        }
    }

    private PackageInfo packageInfoForUserPreS(UserReference user, int flags) {
        AdbPackage pkg = Packages.parseDumpsys().mPackages.get(mPackageName);

        if (pkg == null) {
            return null;
        }

        if (!pkg.installedOnUsers().contains(user)) {
            return null;
        }

        PackageInfo packageInfo = new PackageInfo();
        packageInfo.packageName = mPackageName;
        packageInfo.requestedPermissions = pkg.requestedPermissions().toArray(new String[]{});

        return packageInfo;
    }

    @Nullable
    private ApplicationInfo applicationInfoFromAnyUser(int flags) {
        return TestApis.users().all().stream()
                .map(i -> applicationInfoForUser(i, flags))
                .filter(Objects::nonNull)
                .findFirst()
                .orElse(null);
    }

    @Nullable
    private ApplicationInfo applicationInfoForUser(UserReference user, int flags) {
        if (user.equals(TestApis.users().instrumented())) {
            try {
                return TestApis.context().instrumentedContext()
                        .getPackageManager()
                        .getApplicationInfo(mPackageName, /* flags= */ flags);
            } catch (PackageManager.NameNotFoundException e) {
                return null;
            }
        }

        if (!Versions.meetsMinimumSdkVersionRequirement(Build.VERSION_CODES.Q)) {
            return applicationInfoForUserPreQ(user, flags);
        }

        if (Permissions.sIgnorePermissions.get()) {
            try {
                return TestApis.context().androidContextAsUser(user)
                        .getPackageManager()
                        .getApplicationInfo(mPackageName, /* flags= */ flags);
            } catch (PackageManager.NameNotFoundException e) {
                return null;
            }
        } else {
            try (PermissionContext p = TestApis.permissions().withPermission(
                    INTERACT_ACROSS_USERS_FULL)) {
                return TestApis.context().androidContextAsUser(user)
                        .getPackageManager()
                        .getApplicationInfo(mPackageName, /* flags= */ flags);
            } catch (PackageManager.NameNotFoundException e) {
                return null;
            }
        }
    }

    private ApplicationInfo applicationInfoForUserPreQ(UserReference user, int flags) {
        try {
            String dumpsysOutput = ShellCommand.builder("dumpsys package").execute();

            AdbPackageParser.ParseResult r = Packages.sParser.parse(dumpsysOutput);
            AdbPackage pkg = r.mPackages.get(mPackageName);

            if (pkg == null) {
                return null;
            }

            ApplicationInfo applicationInfo = new ApplicationInfo();
            applicationInfo.packageName = mPackageName;
            applicationInfo.uid = -1; // TODO: Get the actual uid...

            return applicationInfo;
        } catch (AdbException | AdbParseException e) {
            throw new NeneException("Error getting package info pre Q", e);
        }
    }

    /**
     * Get all users this package is installed on.
     *
     * <p>Note that this is an expensive operation - favor {@link #installedOnUser(UserReference)}
     * when possible.
     */
    public Set<UserReference> installedOnUsers() {
        return TestApis.users().all().stream()
                .filter(this::installedOnUser)
                .collect(Collectors.toSet());
    }

    /**
     * Force the running instance of the package to stop on the given user.
     *
     * <p>See {@link ActivityManager#forceStopPackage(String)}.
     */
    @Experimental
    public void forceStop(UserReference user) {
        try (PermissionContext p = TestApis.permissions().withPermission(FORCE_STOP_PACKAGES)) {
            ActivityManager userActivityManager =
                    TestApis.context().androidContextAsUser(user)
                            .getSystemService(ActivityManager.class);

            PackageManager userPackageManager =
                    TestApis.context().androidContextAsUser(user).getPackageManager();
            boolean shouldCheckPreviousProcess = runningProcess() != null;
            // In most cases this should work first time, however if a user restriction has been
            // recently removed we may need to retry

            int previousPid = shouldCheckPreviousProcess ? runningProcess().pid() : -1;

            Poll.forValue("Application flag", () -> {
                userActivityManager.forceStopPackage(mPackageName);

                return userPackageManager.getPackageInfo(mPackageName,
                            PackageManager.GET_META_DATA)
                            .applicationInfo.flags;
            }).toMeet(flag -> !shouldCheckPreviousProcess || (flag & FLAG_STOPPED) == FLAG_STOPPED
                            ||  previousPid != runningProcess().pid())
                    .errorOnFail("Expected application flags to contain FLAG_STOPPED ("
                            + FLAG_STOPPED + ")")
                    .await();
        }
    }

    /**
     * Force the running instance of the package to stop on the instrumented user.
     *
     * <p>See {@link ActivityManager#forceStopPackage(String)}.
     */
    @Experimental
    public void forceStop() {
        forceStop(TestApis.users().instrumented());
    }

    /**
     * Interact with AppOps on the instrumented user for the given package.
     */
    @Experimental
    public AppOps appOps() {
        return appOps(TestApis.users().instrumented());
    }

    /**
     * Interact with AppOps on the given user for the given package.
     */
    @Experimental
    public AppOps appOps(UserReference user) {
        return new AppOps(this, user);
    }

    /**
     * Get the UID of the package on the instrumented user.
     */
    @Experimental
    public int uid() {
        return uid(TestApis.users().instrumented());
    }

    /**
     * Get the UID of the package on the given {@code user}.
     */
    @Experimental
    public int uid(UserReference user) {
        if (user.equals(TestApis.users().instrumented())
                && this.equals(TestApis.packages().instrumented())) {
            return myUid();
        }

        ApplicationInfo applicationInfo = applicationInfoForUser(user, /* flags= */ 0);
        if (applicationInfo == null) {
            throw new IllegalStateException(
                    "Trying to get uid for not installed package " + this + " on user " + user);
        }

        return applicationInfo.uid;
    }

    @Override
    public int hashCode() {
        return mPackageName.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Package)) {
            return false;
        }

        Package other = (Package) obj;
        return other.mPackageName.equals(mPackageName);
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder("PackageReference{");
        stringBuilder.append("packageName=" + mPackageName);
        stringBuilder.append("}");
        return stringBuilder.toString();
    }

    /** {@code true} if the package exists on any user on the device as is not uninstalled. */
    @TargetApi(S)
    public boolean isInstalled() {
        Versions.requireMinimumVersion(S);

        try (PermissionContext p = TestApis.permissions().withPermission(QUERY_ALL_PACKAGES)) {
            return packageInfoFromAnyUser(0) != null;
        }
    }

    /** {@code true} if the package exists on the device. */
    public boolean exists() {
        if (Versions.meetsMinimumSdkVersionRequirement(S)) {
            try (PermissionContext p = TestApis.permissions().withPermission(QUERY_ALL_PACKAGES)) {
                return packageInfoFromAnyUser(MATCH_UNINSTALLED_PACKAGES) != null;
            }
        }

        return Packages.parseDumpsys().mPackages.containsKey(mPackageName);
    }

    /** Get the targetSdkVersion for the package. */
    @Experimental
    public int targetSdkVersion() {
        return applicationInfoFromAnyUserOrError(/* flags= */ 0).targetSdkVersion;
    }

    /**
     * {@code true} if the package is installed in the device's system image.
     */
    @Experimental
    public boolean hasSystemFlag() {
        return (applicationInfoFromAnyUserOrError(/* flags= */ 0).flags & FLAG_SYSTEM) > 0;
    }

    @Experimental
    public boolean isInstantApp() {
        return sPackageManager.isInstantApp(mPackageName);
    }

    /** Get the AppComponentFactory for the package. */
    @Experimental
    @Nullable
    @TargetApi(P)
    public String appComponentFactory() {
        return applicationInfoFromAnyUserOrError(/* flags= */ 0).appComponentFactory;
    }

    private ApplicationInfo applicationInfoFromAnyUserOrError(int flags) {
        ApplicationInfo appInfo = applicationInfoFromAnyUser(flags);
        if (appInfo == null) {
            throw new NeneException("Package not installed: " + this);
        }
        return appInfo;
    }

    /**
     * Gets the shared user id of the package.
     */
    @Experimental
    public String sharedUserId() {
        PackageInfo packageInfo = packageInfoFromAnyUser(/* flags= */ 0);

        if (packageInfo == null) {
            throw new NeneException("Error getting sharedUserId, does not exist");
        }

        return packageInfo.sharedUserId;
    }

    /**
     * See {@link PackageManager#setSyntheticAppDetailsActivityEnabled(String, boolean)}.
     */
    @Experimental
    public void setSyntheticAppDetailsActivityEnabled(UserReference user, boolean enabled) {
        try (PermissionContext p = TestApis.permissions()
                .withPermission(CHANGE_COMPONENT_ENABLED_STATE)) {
            TestApis.context().androidContextAsUser(user).getPackageManager()
                    .setSyntheticAppDetailsActivityEnabled(packageName(), enabled);
        }
    }

    /**
     * See {@link PackageManager#setSyntheticAppDetailsActivityEnabled(String, boolean)}.
     */
    @Experimental
    public void setSyntheticAppDetailsActivityEnabled(boolean enabled) {
        setSyntheticAppDetailsActivityEnabled(TestApis.users().instrumented(), enabled);
    }

    /**
     * See {@link PackageManager#getSyntheticAppDetailsActivityEnabled(String)}.
     */
    @Experimental
    public boolean syntheticAppDetailsActivityEnabled(UserReference user) {
        return TestApis.context().androidContextAsUser(user).getPackageManager()
                .getSyntheticAppDetailsActivityEnabled(packageName());
    }

    /**
     * See {@link PackageManager#getSyntheticAppDetailsActivityEnabled(String)}.
     */
    @Experimental
    public boolean syntheticAppDetailsActivityEnabled() {
        return syntheticAppDetailsActivityEnabled(TestApis.users().instrumented());
    }

    private static final class ProcessInfo {
        final String mPackageName;
        final int mPid;
        final int mUid;
        final int mUserId;

        ProcessInfo(String packageName, int pid, int uid, int userId) {
            if (packageName == null) {
                throw new NullPointerException();
            }
            mPackageName = packageName;
            mPid = pid;
            mUid = uid;
            mUserId = userId;
        }

        @Override
        public String toString() {
            return "ProcessInfo{packageName=" + mPackageName + ", pid="
                    + mPid + ", uid=" + mUid + ", userId=" + mUserId + "}";
        }
    }

    /**
     * Set this package as filling the given role on the instrumented user.
     */
    @Experimental
    public RoleContext setAsRoleHolder(String role) {
        return setAsRoleHolder(role, TestApis.users().instrumented());
    }

    /**
     * Set this package as filling the given role.
     */
    @Experimental
    public RoleContext setAsRoleHolder(String role, UserReference user) {
        try (PermissionContext p = TestApis.permissions().withPermission(
                MANAGE_ROLE_HOLDERS, INTERACT_ACROSS_USERS_FULL)) {

            Retry.logic(() -> {
                TestApis.logcat().clear();
                DefaultBlockingCallback<Boolean> blockingCallback = new DefaultBlockingCallback<>();

                sRoleManager.addRoleHolderAsUser(
                        role,
                        mPackageName,
                        /* flags= */ 0,
                        user.userHandle(),
                        TestApis.context().instrumentedContext().getMainExecutor(),
                        blockingCallback::triggerCallback);

                boolean success = blockingCallback.await();
                if (!success) {
                    fail("Could not set role holder of " + role + "." + " Relevant logcat: "
                            + TestApis.logcat().dump((line) -> line.contains(role)));
                }
                if (!TestApis.roles().getRoleHoldersAsUser(role, user).contains(packageName())) {
                    fail("addRoleHolderAsUser returned true but did not add role holder. "
                            + "Relevant logcat: " + TestApis.logcat().dump(
                                    (line) -> line.contains(role)));
                }
            }).terminalException(e -> {
                // Terminal unless we see logcat output indicating it might be temporary
                var logcat = TestApis.logcat()
                        .dump(l -> l.contains("Error calling onAddRoleHolder()"));
                if (!logcat.isEmpty()) {
                    // On low end devices - this can happen when the broadcast queue is full
                    try {
                        Thread.sleep(10_000);
                    } catch (InterruptedException ex) {
                        return true;
                    }

                    return false;
                }

                return true;
            }).runAndWrapException();

            return new RoleContext(role, this, user);
        }
    }

    /**
     * Remove this package from the given role on the instrumented user.
     */
    @Experimental
    public void removeAsRoleHolder(String role) {
        removeAsRoleHolder(role, TestApis.users().instrumented());
    }

    /**
     * Remove this package from the given role.
     */
    @Experimental
    public void removeAsRoleHolder(String role, UserReference user) {
        try (PermissionContext p = TestApis.permissions().withPermission(
                MANAGE_ROLE_HOLDERS)) {
            Retry.logic(() -> {
                TestApis.logcat().clear();
                DefaultBlockingCallback<Boolean> blockingCallback = new DefaultBlockingCallback<>();
                sRoleManager.removeRoleHolderAsUser(
                        role,
                        mPackageName,
                        /* flags= */ 0,
                        user.userHandle(),
                        TestApis.context().instrumentedContext().getMainExecutor(),
                        blockingCallback::triggerCallback);
                TestApis.roles().setBypassingRoleQualification(false);

                boolean success = blockingCallback.await();
                if (!success) {
                    fail("Failed to clear the role holder of "
                            + role + ".");
                }
                if (TestApis.roles().getRoleHoldersAsUser(role, user).contains(packageName())) {
                    fail("removeRoleHolderAsUser returned true but did not remove role holder. "
                            + "Relevant logcat: " + TestApis.logcat().dump(
                                    (line) -> line.contains(role)));
                }
            }).terminalException(e -> {
                // Terminal unless we see logcat output indicating it might be temporary
                var logcat = TestApis.logcat()
                        .dump(l -> l.contains("Error calling onRemoveRoleHolder()"));
                if (!logcat.isEmpty()) {
                    // On low end devices - this can happen when the broadcast queue is full
                    try {
                        Thread.sleep(10_000);
                    } catch (InterruptedException ex) {
                        return true;
                    }

                    return false;
                }

                return true;
            }).runAndWrapException();
        }
    }

    /**
     * True if the given package on the instrumented user can have its ability to interact across
     * profiles configured by the user.
     */
    @Experimental
    public boolean canConfigureInteractAcrossProfiles() {
        return canConfigureInteractAcrossProfiles(TestApis.users().instrumented());
    }

    /**
     * True if the given package can have its ability to interact across profiles configured
     * by the user.
     */
    @Experimental
    public boolean canConfigureInteractAcrossProfiles(UserReference user) {
        return TestApis.context().androidContextAsUser(user)
                .getSystemService(CrossProfileApps.class)
                .canConfigureInteractAcrossProfiles(packageName());
    }

    /**
     * Enable or disable this package from using @TestApis.
     */
    @Experimental
    public void setAllowTestApiAccess(boolean allowed) {
        ShellCommand.builder("am compat")
                .addOperand(allowed ? "enable" : "disable")
                .addOperand("ALLOW_TEST_API_ACCESS")
                .addOperand(packageName())
                .validate(s -> s.startsWith(allowed ? "Enabled change" : "Disabled change"))
                .executeOrThrowNeneException(
                        "Error allowing/disallowing test api access for " + this);
    }

    /**
     * True if the given package is suspended in the given user.
     */
    @Experimental
    public boolean isSuspended(UserReference user) {
        try (PermissionContext p =
                     TestApis.permissions().withPermission(INTERACT_ACROSS_USERS_FULL)) {
            return TestApis.context().androidContextAsUser(user).getPackageManager()
                    .isPackageSuspended(mPackageName);
        } catch (PackageManager.NameNotFoundException e) {
            throw new NeneException("Package " + mPackageName + " not found for user " + user);
        }
    }

    /**
     * Get the app standby bucket of the package.
     */
    @Experimental
    public int getAppStandbyBucket() {
        return getAppStandbyBucket(TestApis.users().instrumented());
    }

    /**
     * Get the app standby bucket of the package.
     */
    @Experimental
    public int getAppStandbyBucket(UserReference user) {
        try {
            return ShellCommand.builderForUser(user, "am get-standby-bucket")
                .addOperand(mPackageName)
                .executeAndParseOutput(o -> Integer.parseInt(o.trim()));
        } catch (AdbException e) {
            throw new NeneException("Could not get app standby bucket " + this, e);
        }
    }

    /** Approves all links for an auto verifiable app */
    @Experimental
    public void setAppLinksToAllApproved() {
        try {
            ShellCommand.builder("pm set-app-links")
                    .addOption("--package", this.mPackageName)
                    .addOperand(2) // 2 = STATE_APPROVED
                    .addOperand("all")
                    .execute();
        } catch (AdbException e) {
            throw new NeneException("Error verifying links ", e);
        }
    }

    /** Checks if the current package is a role holder for the given role*/
    @Experimental
    public boolean isRoleHolder(String role) {
        return TestApis.roles().getRoleHolders(role).contains(this.mPackageName);
    }

    @Experimental
    public void clearStorage() {
        ShellCommand.builder("pm clear")
                .addOperand(mPackageName)
                .validate(ShellCommandUtils::startsWithSuccess)
                .executeOrThrowNeneException("Error clearing storage for " + this);
    }
}