• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.server.pm;
18 
19 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
20 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
21 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
22 import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
23 import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
24 import static android.content.pm.PackageManager.MATCH_DEFAULT_ONLY;
25 import static android.content.pm.PackageManager.UNINSTALL_REASON_UNKNOWN;
26 import static android.content.pm.PackageManager.UNINSTALL_REASON_USER_TYPE;
27 import static android.os.Process.INVALID_UID;
28 import static android.os.Process.PACKAGE_INFO_GID;
29 import static android.os.Process.SYSTEM_UID;
30 
31 import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME;
32 import static com.android.server.pm.SharedUidMigration.BEST_EFFORT;
33 
34 import android.annotation.NonNull;
35 import android.annotation.Nullable;
36 import android.annotation.UserIdInt;
37 import android.app.compat.ChangeIdStateCache;
38 import android.content.ComponentName;
39 import android.content.Intent;
40 import android.content.IntentFilter;
41 import android.content.pm.ActivityInfo;
42 import android.content.pm.ApplicationInfo;
43 import android.content.pm.IntentFilterVerificationInfo;
44 import android.content.pm.PackageInstaller;
45 import android.content.pm.PackageManager;
46 import android.content.pm.PackageManagerInternal;
47 import android.content.pm.PackagePartitions;
48 import android.content.pm.PermissionInfo;
49 import android.content.pm.ResolveInfo;
50 import android.content.pm.Signature;
51 import android.content.pm.SuspendDialogInfo;
52 import android.content.pm.UserInfo;
53 import android.content.pm.VerifierDeviceIdentity;
54 import android.content.pm.overlay.OverlayPaths;
55 import android.net.Uri;
56 import android.os.Binder;
57 import android.os.Build;
58 import android.os.CreateAppDataArgs;
59 import android.os.Environment;
60 import android.os.FileUtils;
61 import android.os.Handler;
62 import android.os.Message;
63 import android.os.PatternMatcher;
64 import android.os.PersistableBundle;
65 import android.os.SELinux;
66 import android.os.SystemClock;
67 import android.os.Trace;
68 import android.os.UserHandle;
69 import android.os.UserManager;
70 import android.os.storage.StorageManager;
71 import android.os.storage.VolumeInfo;
72 import android.service.pm.PackageServiceDumpProto;
73 import android.text.TextUtils;
74 import android.util.ArrayMap;
75 import android.util.ArraySet;
76 import android.util.AtomicFile;
77 import android.util.IntArray;
78 import android.util.Log;
79 import android.util.LogPrinter;
80 import android.util.Pair;
81 import android.util.Slog;
82 import android.util.SparseArray;
83 import android.util.SparseBooleanArray;
84 import android.util.SparseIntArray;
85 import android.util.SparseLongArray;
86 import android.util.TypedXmlPullParser;
87 import android.util.TypedXmlSerializer;
88 import android.util.Xml;
89 import android.util.proto.ProtoOutputStream;
90 
91 import com.android.internal.annotations.GuardedBy;
92 import com.android.internal.annotations.VisibleForTesting;
93 import com.android.internal.os.BackgroundThread;
94 import com.android.internal.util.ArrayUtils;
95 import com.android.internal.util.CollectionUtils;
96 import com.android.internal.util.IndentingPrintWriter;
97 import com.android.internal.util.JournaledFile;
98 import com.android.internal.util.XmlUtils;
99 import com.android.permission.persistence.RuntimePermissionsPersistence;
100 import com.android.permission.persistence.RuntimePermissionsState;
101 import com.android.server.LocalServices;
102 import com.android.server.backup.PreferredActivityBackupHelper;
103 import com.android.server.pm.Installer.InstallerException;
104 import com.android.server.pm.parsing.PackageInfoUtils;
105 import com.android.server.pm.parsing.pkg.AndroidPackage;
106 import com.android.server.pm.parsing.pkg.AndroidPackageUtils;
107 import com.android.server.pm.permission.LegacyPermissionDataProvider;
108 import com.android.server.pm.permission.LegacyPermissionSettings;
109 import com.android.server.pm.permission.LegacyPermissionState;
110 import com.android.server.pm.permission.LegacyPermissionState.PermissionState;
111 import com.android.server.pm.pkg.PackageStateInternal;
112 import com.android.server.pm.pkg.PackageUserState;
113 import com.android.server.pm.pkg.PackageUserStateInternal;
114 import com.android.server.pm.pkg.SuspendParams;
115 import com.android.server.pm.pkg.component.ParsedComponent;
116 import com.android.server.pm.pkg.component.ParsedIntentInfo;
117 import com.android.server.pm.pkg.component.ParsedPermission;
118 import com.android.server.pm.pkg.component.ParsedProcess;
119 import com.android.server.pm.pkg.parsing.PackageInfoWithoutStateUtils;
120 import com.android.server.pm.resolution.ComponentResolver;
121 import com.android.server.pm.verify.domain.DomainVerificationLegacySettings;
122 import com.android.server.pm.verify.domain.DomainVerificationManagerInternal;
123 import com.android.server.pm.verify.domain.DomainVerificationPersistence;
124 import com.android.server.utils.Slogf;
125 import com.android.server.utils.Snappable;
126 import com.android.server.utils.SnapshotCache;
127 import com.android.server.utils.TimingsTraceAndSlog;
128 import com.android.server.utils.Watchable;
129 import com.android.server.utils.WatchableImpl;
130 import com.android.server.utils.Watched;
131 import com.android.server.utils.WatchedArrayList;
132 import com.android.server.utils.WatchedArrayMap;
133 import com.android.server.utils.WatchedArraySet;
134 import com.android.server.utils.WatchedSparseArray;
135 import com.android.server.utils.WatchedSparseIntArray;
136 import com.android.server.utils.Watcher;
137 
138 import dalvik.annotation.optimization.NeverCompile;
139 
140 import libcore.io.IoUtils;
141 
142 import org.xmlpull.v1.XmlPullParser;
143 import org.xmlpull.v1.XmlPullParserException;
144 import org.xmlpull.v1.XmlSerializer;
145 
146 import java.io.BufferedWriter;
147 import java.io.File;
148 import java.io.FileInputStream;
149 import java.io.FileNotFoundException;
150 import java.io.FileOutputStream;
151 import java.io.IOException;
152 import java.io.InputStream;
153 import java.io.OutputStreamWriter;
154 import java.io.PrintWriter;
155 import java.nio.charset.Charset;
156 import java.nio.charset.StandardCharsets;
157 import java.text.SimpleDateFormat;
158 import java.util.ArrayList;
159 import java.util.Arrays;
160 import java.util.Collection;
161 import java.util.Date;
162 import java.util.Iterator;
163 import java.util.List;
164 import java.util.Map;
165 import java.util.Map.Entry;
166 import java.util.Objects;
167 import java.util.Random;
168 import java.util.Set;
169 import java.util.UUID;
170 import java.util.function.Consumer;
171 
172 /**
173  * Holds information about dynamic settings.
174  */
175 public final class Settings implements Watchable, Snappable {
176     private static final String TAG = "PackageSettings";
177 
178     /**
179      * Watchable machinery
180      */
181     private final WatchableImpl mWatchable = new WatchableImpl();
182 
183     /**
184      * Ensures an observer is in the list, exactly once. The observer cannot be null.  The
185      * function quietly returns if the observer is already in the list.
186      *
187      * @param observer The {@link Watcher} to be notified when the {@link Watchable} changes.
188      */
registerObserver(@onNull Watcher observer)189     public void registerObserver(@NonNull Watcher observer) {
190         mWatchable.registerObserver(observer);
191     }
192 
193     /**
194      * Ensures an observer is not in the list. The observer must not be null.  The function
195      * quietly returns if the objserver is not in the list.
196      *
197      * @param observer The {@link Watcher} that should not be in the notification list.
198      */
unregisterObserver(@onNull Watcher observer)199     public void unregisterObserver(@NonNull Watcher observer) {
200         mWatchable.unregisterObserver(observer);
201     }
202 
203     /**
204      * Return true if the {@link Watcher) is a registered observer.
205      * @param observer A {@link Watcher} that might be registered
206      * @return true if the observer is registered with this {@link Watchable}.
207      */
208     @Override
isRegisteredObserver(@onNull Watcher observer)209     public boolean isRegisteredObserver(@NonNull Watcher observer) {
210         return mWatchable.isRegisteredObserver(observer);
211     }
212 
213     /**
214      * Invokes {@link Watcher#onChange} on each registered observer.  The method can be called
215      * with the {@link Watchable} that generated the event.  In a tree of {@link Watchable}s, this
216      * is generally the first (deepest) {@link Watchable} to detect a change.
217      *
218      * @param what The {@link Watchable} that generated the event.
219      */
dispatchChange(@ullable Watchable what)220     public void dispatchChange(@Nullable Watchable what) {
221         mWatchable.dispatchChange(what);
222     }
223     /**
224      * Notify listeners that this object has changed.
225      */
onChanged()226     protected void onChanged() {
227         dispatchChange(this);
228     }
229 
230     /**
231      * Current version of the package database. Set it to the latest version in
232      * the {@link DatabaseVersion} class below to ensure the database upgrade
233      * doesn't happen repeatedly.
234      * <p>
235      * Note that care should be taken to make sure all database upgrades are
236      * idempotent.
237      */
238     public static final int CURRENT_DATABASE_VERSION = DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
239 
240     /**
241      * This class contains constants that can be referred to from upgrade code.
242      * Insert constant values here that describe the upgrade reason. The version
243      * code must be monotonically increasing.
244      */
245     public static class DatabaseVersion {
246         /**
247          * The initial version of the database.
248          */
249         public static final int FIRST_VERSION = 1;
250 
251         /**
252          * Migrating the Signature array from the entire certificate chain to
253          * just the signing certificate.
254          */
255         public static final int SIGNATURE_END_ENTITY = 2;
256 
257         /**
258          * There was a window of time in
259          * {@link android.os.Build.VERSION_CODES#LOLLIPOP} where we persisted
260          * certificates after potentially mutating them. To switch back to the
261          * original untouched certificates, we need to force a collection pass.
262          */
263         public static final int SIGNATURE_MALFORMED_RECOVER = 3;
264     }
265 
266     static final boolean DEBUG_STOPPED = false;
267     private static final boolean DEBUG_MU = false;
268     private static final boolean DEBUG_KERNEL = false;
269     private static final boolean DEBUG_PARSER = false;
270 
271     private static final String RUNTIME_PERMISSIONS_FILE_NAME = "runtime-permissions.xml";
272 
273     private static final String TAG_READ_EXTERNAL_STORAGE = "read-external-storage";
274     private static final String ATTR_ENFORCEMENT = "enforcement";
275 
276     public static final String TAG_ITEM = "item";
277     private static final String TAG_DISABLED_COMPONENTS = "disabled-components";
278     private static final String TAG_ENABLED_COMPONENTS = "enabled-components";
279     private static final String TAG_PACKAGE_RESTRICTIONS = "package-restrictions";
280     private static final String TAG_PACKAGE = "pkg";
281     private static final String TAG_SHARED_USER = "shared-user";
282     private static final String TAG_RUNTIME_PERMISSIONS = "runtime-permissions";
283     private static final String TAG_PERMISSIONS = "perms";
284     private static final String TAG_CHILD_PACKAGE = "child-package";
285     private static final String TAG_USES_SDK_LIB = "uses-sdk-lib";
286     private static final String TAG_USES_STATIC_LIB = "uses-static-lib";
287     private static final String TAG_BLOCK_UNINSTALL_PACKAGES = "block-uninstall-packages";
288     private static final String TAG_BLOCK_UNINSTALL = "block-uninstall";
289 
290     private static final String TAG_PERSISTENT_PREFERRED_ACTIVITIES =
291             "persistent-preferred-activities";
292     static final String TAG_CROSS_PROFILE_INTENT_FILTERS =
293             "crossProfile-intent-filters";
294     public static final String TAG_DOMAIN_VERIFICATION = "domain-verification";
295     private static final String TAG_DEFAULT_APPS = "default-apps";
296     public static final String TAG_ALL_INTENT_FILTER_VERIFICATION =
297             "all-intent-filter-verifications";
298     private static final String TAG_DEFAULT_BROWSER = "default-browser";
299     private static final String TAG_DEFAULT_DIALER = "default-dialer";
300     private static final String TAG_VERSION = "version";
301     /**
302      * @deprecated Moved to {@link SuspendParams}
303      */
304     @Deprecated
305     private static final String TAG_SUSPENDED_DIALOG_INFO = "suspended-dialog-info";
306     /**
307      * @deprecated Moved to {@link SuspendParams}
308      */
309     @Deprecated
310     private static final String TAG_SUSPENDED_APP_EXTRAS = "suspended-app-extras";
311     /**
312      * @deprecated Moved to {@link SuspendParams}
313      */
314     @Deprecated
315     private static final String TAG_SUSPENDED_LAUNCHER_EXTRAS = "suspended-launcher-extras";
316     private static final String TAG_SUSPEND_PARAMS = "suspend-params";
317     private static final String TAG_MIME_GROUP = "mime-group";
318     private static final String TAG_MIME_TYPE = "mime-type";
319 
320     public static final String ATTR_NAME = "name";
321     public static final String ATTR_PACKAGE = "package";
322     private static final String ATTR_GRANTED = "granted";
323     private static final String ATTR_FLAGS = "flags";
324     private static final String ATTR_VERSION = "version";
325 
326     private static final String ATTR_CE_DATA_INODE = "ceDataInode";
327     private static final String ATTR_INSTALLED = "inst";
328     private static final String ATTR_STOPPED = "stopped";
329     private static final String ATTR_NOT_LAUNCHED = "nl";
330     // Legacy, here for reading older versions of the package-restrictions.
331     private static final String ATTR_BLOCKED = "blocked";
332     // New name for the above attribute.
333     private static final String ATTR_HIDDEN = "hidden";
334     private static final String ATTR_DISTRACTION_FLAGS = "distraction_flags";
335     private static final String ATTR_SUSPENDED = "suspended";
336     private static final String ATTR_SUSPENDING_PACKAGE = "suspending-package";
337     /**
338      * @deprecated Legacy attribute, kept only for upgrading from P builds.
339      */
340     @Deprecated
341     private static final String ATTR_SUSPEND_DIALOG_MESSAGE = "suspend_dialog_message";
342     // Legacy, uninstall blocks are stored separately.
343     @Deprecated
344     private static final String ATTR_BLOCK_UNINSTALL = "blockUninstall";
345     private static final String ATTR_ENABLED = "enabled";
346     private static final String ATTR_ENABLED_CALLER = "enabledCaller";
347     private static final String ATTR_DOMAIN_VERIFICATON_STATE = "domainVerificationStatus";
348     private static final String ATTR_APP_LINK_GENERATION = "app-link-generation";
349     private static final String ATTR_INSTALL_REASON = "install-reason";
350     private static final String ATTR_UNINSTALL_REASON = "uninstall-reason";
351     private static final String ATTR_INSTANT_APP = "instant-app";
352     private static final String ATTR_VIRTUAL_PRELOAD = "virtual-preload";
353     private static final String ATTR_HARMFUL_APP_WARNING = "harmful-app-warning";
354     private static final String ATTR_SPLASH_SCREEN_THEME = "splash-screen-theme";
355 
356     private static final String ATTR_PACKAGE_NAME = "packageName";
357     private static final String ATTR_FINGERPRINT = "fingerprint";
358     private static final String ATTR_VOLUME_UUID = "volumeUuid";
359     private static final String ATTR_SDK_VERSION = "sdkVersion";
360     private static final String ATTR_DATABASE_VERSION = "databaseVersion";
361     private static final String ATTR_VALUE = "value";
362     private static final String ATTR_FIRST_INSTALL_TIME = "first-install-time";
363 
364     private final Handler mHandler;
365 
366     private final PackageManagerTracedLock mLock;
367 
368     @Watched(manual = true)
369     private final RuntimePermissionPersistence mRuntimePermissionsPersistence;
370 
371     private final File mSettingsFilename;
372     private final File mBackupSettingsFilename;
373     private final File mPackageListFilename;
374     private final File mStoppedPackagesFilename;
375     private final File mBackupStoppedPackagesFilename;
376     /** The top level directory in configfs for sdcardfs to push the package->uid,userId mappings */
377     private final File mKernelMappingFilename;
378 
379     /** Map from package name to settings */
380     @Watched
381     @VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE)
382     final WatchedArrayMap<String, PackageSetting> mPackages;
383     private final SnapshotCache<WatchedArrayMap<String, PackageSetting>> mPackagesSnapshot;
384 
385     /**
386      * List of packages that were involved in installing other packages, i.e. packages that created
387      * new sessions or are listed in at least one app's InstallSource.
388      */
389     @Watched
390     private final WatchedArraySet<String> mInstallerPackages;
391     private final SnapshotCache<WatchedArraySet<String>> mInstallerPackagesSnapshot;
392 
393     /** Map from package name to appId and excluded userids */
394     @Watched
395     private final WatchedArrayMap<String, KernelPackageState> mKernelMapping;
396     private final SnapshotCache<WatchedArrayMap<String, KernelPackageState>> mKernelMappingSnapshot;
397 
398     // List of replaced system applications
399     @Watched
400     @VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE)
401     final WatchedArrayMap<String, PackageSetting> mDisabledSysPackages = new WatchedArrayMap<>();
402 
403     /** List of packages that are blocked for uninstall for specific users */
404     @Watched
405     private final WatchedSparseArray<ArraySet<String>> mBlockUninstallPackages =
406             new WatchedSparseArray<>();
407 
408     private static final class KernelPackageState {
409         int appId;
410         int[] excludedUserIds;
411     }
412 
413     /** Map from volume UUID to {@link VersionInfo} */
414     @Watched
415     private final WatchedArrayMap<String, VersionInfo> mVersion = new WatchedArrayMap<>();
416 
417     /**
418      * Version details for a storage volume that may hold apps.
419      */
420     public static class VersionInfo {
421         /**
422          * These are the last platform API version we were using for the apps
423          * installed on internal and external storage. It is used to grant newer
424          * permissions one time during a system upgrade.
425          */
426         int sdkVersion;
427 
428         /**
429          * The current database version for apps on internal storage. This is
430          * used to upgrade the format of the packages.xml database not
431          * necessarily tied to an SDK version.
432          */
433         int databaseVersion;
434 
435         /**
436          * Last known value of {@link Build#FINGERPRINT}. Used to determine when
437          * an system update has occurred, meaning we need to clear code caches.
438          */
439         String fingerprint;
440 
441         /**
442          * Force all version information to match current system values,
443          * typically after resolving any required upgrade steps.
444          */
forceCurrent()445         public void forceCurrent() {
446             sdkVersion = Build.VERSION.SDK_INT;
447             databaseVersion = CURRENT_DATABASE_VERSION;
448             fingerprint = PackagePartitions.FINGERPRINT;
449         }
450     }
451 
452     /** Device identity for the purpose of package verification. */
453     @Watched(manual = true)
454     private VerifierDeviceIdentity mVerifierDeviceIdentity;
455 
456     // The user's preferred activities associated with particular intent
457     // filters.
458     @Watched
459     private final WatchedSparseArray<PreferredIntentResolver> mPreferredActivities;
460     private final SnapshotCache<WatchedSparseArray<PreferredIntentResolver>>
461             mPreferredActivitiesSnapshot;
462 
463     // The persistent preferred activities of the user's profile/device owner
464     // associated with particular intent filters.
465     @Watched
466     private final WatchedSparseArray<PersistentPreferredIntentResolver>
467             mPersistentPreferredActivities;
468     private final SnapshotCache<WatchedSparseArray<PersistentPreferredIntentResolver>>
469             mPersistentPreferredActivitiesSnapshot;
470 
471 
472     // For every user, it is used to find to which other users the intent can be forwarded.
473     @Watched
474     private final WatchedSparseArray<CrossProfileIntentResolver> mCrossProfileIntentResolvers;
475     private final SnapshotCache<WatchedSparseArray<CrossProfileIntentResolver>>
476             mCrossProfileIntentResolversSnapshot;
477 
478     @Watched
479     final WatchedArrayMap<String, SharedUserSetting> mSharedUsers = new WatchedArrayMap<>();
480     @Watched(manual = true)
481     private final AppIdSettingMap mAppIds;
482 
483     // For reading/writing settings file.
484     @Watched
485     private final WatchedArrayList<Signature> mPastSignatures;
486     private final SnapshotCache<WatchedArrayList<Signature>> mPastSignaturesSnapshot;
487 
488     @Watched
489     private final WatchedArrayMap<Long, Integer> mKeySetRefs;
490     private final SnapshotCache<WatchedArrayMap<Long, Integer>> mKeySetRefsSnapshot;
491 
492     // Packages that have been renamed since they were first installed.
493     // Keys are the new names of the packages, values are the original
494     // names.  The packages appear everywhere else under their original
495     // names.
496     @Watched
497     private final WatchedArrayMap<String, String> mRenamedPackages =
498             new WatchedArrayMap<String, String>();
499 
500     // For every user, it is used to find the package name of the default Browser App.
501     @Watched
502     final WatchedSparseArray<String> mDefaultBrowserApp = new WatchedSparseArray<String>();
503 
504     // TODO(b/161161364): This seems unused, and is probably not relevant in the new API, but should
505     //  verify.
506     // App-link priority tracking, per-user
507     @NonNull
508     @Watched
509     private final WatchedSparseIntArray mNextAppLinkGeneration = new WatchedSparseIntArray();
510 
511     final StringBuilder mReadMessages = new StringBuilder();
512 
513     /**
514      * Used to track packages that have a shared user ID that hasn't been read
515      * in yet.
516      * <p>
517      * TODO: make this just a local variable that is passed in during package
518      * scanning to make it less confusing.
519      */
520     @Watched
521     private final WatchedArrayList<PackageSetting> mPendingPackages;
522     private final SnapshotCache<WatchedArrayList<PackageSetting>> mPendingPackagesSnapshot;
523 
524     private final File mSystemDir;
525 
526     private final KeySetManagerService mKeySetManagerService;
527 
528     /** Settings and other information about permissions */
529     @Watched(manual = true)
530     final LegacyPermissionSettings mPermissions;
531 
532     @Watched(manual = true)
533     private final LegacyPermissionDataProvider mPermissionDataProvider;
534 
535     @Watched(manual = true)
536     private final DomainVerificationManagerInternal mDomainVerificationManager;
537 
538     /**
539      * The observer that watches for changes from array members
540      */
541     private final Watcher mObserver = new Watcher() {
542             @Override
543             public void onChange(@Nullable Watchable what) {
544                 Settings.this.dispatchChange(what);
545             }
546         };
547 
548     private final SnapshotCache<Settings> mSnapshot;
549 
550     // Create a snapshot cache
makeCache()551     private SnapshotCache<Settings> makeCache() {
552         return new SnapshotCache<Settings>(this, this) {
553             @Override
554             public Settings createSnapshot() {
555                 Settings s = new Settings(mSource);
556                 s.mWatchable.seal();
557                 return s;
558             }};
559     }
560 
561     private void registerObservers() {
562         mPackages.registerObserver(mObserver);
563         mInstallerPackages.registerObserver(mObserver);
564         mKernelMapping.registerObserver(mObserver);
565         mDisabledSysPackages.registerObserver(mObserver);
566         mBlockUninstallPackages.registerObserver(mObserver);
567         mVersion.registerObserver(mObserver);
568         mPreferredActivities.registerObserver(mObserver);
569         mPersistentPreferredActivities.registerObserver(mObserver);
570         mCrossProfileIntentResolvers.registerObserver(mObserver);
571         mSharedUsers.registerObserver(mObserver);
572         mAppIds.registerObserver(mObserver);
573         mRenamedPackages.registerObserver(mObserver);
574         mNextAppLinkGeneration.registerObserver(mObserver);
575         mDefaultBrowserApp.registerObserver(mObserver);
576         mPendingPackages.registerObserver(mObserver);
577         mPastSignatures.registerObserver(mObserver);
578         mKeySetRefs.registerObserver(mObserver);
579     }
580 
581     // CONSTRUCTOR
582     @VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE)
583     public Settings(Map<String, PackageSetting> pkgSettings) {
584         mPackages = new WatchedArrayMap<>();
585         mPackagesSnapshot =
586                 new SnapshotCache.Auto<>(mPackages, mPackages, "Settings.mPackages");
587         mKernelMapping = new WatchedArrayMap<>();
588         mKernelMappingSnapshot =
589                 new SnapshotCache.Auto<>(mKernelMapping, mKernelMapping, "Settings.mKernelMapping");
590         mInstallerPackages = new WatchedArraySet<>();
591         mInstallerPackagesSnapshot =
592                 new SnapshotCache.Auto<>(mInstallerPackages, mInstallerPackages,
593                                          "Settings.mInstallerPackages");
594         mPreferredActivities = new WatchedSparseArray<>();
595         mPreferredActivitiesSnapshot = new SnapshotCache.Auto<>(mPreferredActivities,
596                 mPreferredActivities, "Settings.mPreferredActivities");
597         mPersistentPreferredActivities = new WatchedSparseArray<>();
598         mPersistentPreferredActivitiesSnapshot = new SnapshotCache.Auto<>(
599                 mPersistentPreferredActivities, mPersistentPreferredActivities,
600                 "Settings.mPersistentPreferredActivities");
601         mCrossProfileIntentResolvers = new WatchedSparseArray<>();
602         mCrossProfileIntentResolversSnapshot = new SnapshotCache.Auto<>(
603                 mCrossProfileIntentResolvers, mCrossProfileIntentResolvers,
604                 "Settings.mCrossProfileIntentResolvers");
605         mPastSignatures = new WatchedArrayList<>();
606         mPastSignaturesSnapshot = new SnapshotCache.Auto<>(mPastSignatures, mPastSignatures,
607                 "Settings.mPastSignatures");
608         mKeySetRefs = new WatchedArrayMap<>();
609         mKeySetRefsSnapshot = new SnapshotCache.Auto<>(mKeySetRefs, mKeySetRefs,
610                 "Settings.mKeySetRefs");
611         mPendingPackages = new WatchedArrayList<>();
612         mPendingPackagesSnapshot = new SnapshotCache.Auto<>(mPendingPackages, mPendingPackages,
613                 "Settings.mPendingPackages");
614         mKeySetManagerService = new KeySetManagerService(mPackages);
615 
616         // Test-only handler working on background thread.
617         mHandler = new Handler(BackgroundThread.getHandler().getLooper());
618         mLock = new PackageManagerTracedLock();
619         mPackages.putAll(pkgSettings);
620         mAppIds = new AppIdSettingMap();
621         mSystemDir = null;
622         mPermissions = null;
623         mRuntimePermissionsPersistence = null;
624         mPermissionDataProvider = null;
625         mSettingsFilename = null;
626         mBackupSettingsFilename = null;
627         mPackageListFilename = null;
628         mStoppedPackagesFilename = null;
629         mBackupStoppedPackagesFilename = null;
630         mKernelMappingFilename = null;
631         mDomainVerificationManager = null;
632 
633         registerObservers();
634         Watchable.verifyWatchedAttributes(this, mObserver);
635 
636         mSnapshot = makeCache();
637     }
638 
639     Settings(File dataDir, RuntimePermissionsPersistence runtimePermissionsPersistence,
640             LegacyPermissionDataProvider permissionDataProvider,
641             @NonNull DomainVerificationManagerInternal domainVerificationManager,
642             @NonNull Handler handler,
643             @NonNull PackageManagerTracedLock lock)  {
644         mPackages = new WatchedArrayMap<>();
645         mPackagesSnapshot  =
646                 new SnapshotCache.Auto<>(mPackages, mPackages, "Settings.mPackages");
647         mKernelMapping = new WatchedArrayMap<>();
648         mKernelMappingSnapshot =
649                 new SnapshotCache.Auto<>(mKernelMapping, mKernelMapping, "Settings.mKernelMapping");
650         mInstallerPackages = new WatchedArraySet<>();
651         mInstallerPackagesSnapshot =
652                 new SnapshotCache.Auto<>(mInstallerPackages, mInstallerPackages,
653                                          "Settings.mInstallerPackages");
654         mPreferredActivities = new WatchedSparseArray<>();
655         mPreferredActivitiesSnapshot = new SnapshotCache.Auto<>(mPreferredActivities,
656                 mPreferredActivities, "Settings.mPreferredActivities");
657         mPersistentPreferredActivities = new WatchedSparseArray<>();
658         mPersistentPreferredActivitiesSnapshot = new SnapshotCache.Auto<>(
659                 mPersistentPreferredActivities, mPersistentPreferredActivities,
660                 "Settings.mPersistentPreferredActivities");
661         mCrossProfileIntentResolvers = new WatchedSparseArray<>();
662         mCrossProfileIntentResolversSnapshot = new SnapshotCache.Auto<>(
663                 mCrossProfileIntentResolvers, mCrossProfileIntentResolvers,
664                 "Settings.mCrossProfileIntentResolvers");
665         mPastSignatures = new WatchedArrayList<>();
666         mPastSignaturesSnapshot = new SnapshotCache.Auto<>(mPastSignatures, mPastSignatures,
667                 "Settings.mPastSignatures");
668         mKeySetRefs = new WatchedArrayMap<>();
669         mKeySetRefsSnapshot = new SnapshotCache.Auto<>(mKeySetRefs, mKeySetRefs,
670                 "Settings.mKeySetRefs");
671         mPendingPackages = new WatchedArrayList<>();
672         mPendingPackagesSnapshot = new SnapshotCache.Auto<>(mPendingPackages, mPendingPackages,
673                 "Settings.mPendingPackages");
674         mKeySetManagerService = new KeySetManagerService(mPackages);
675 
676         mHandler = handler;
677         mLock = lock;
678         mAppIds = new AppIdSettingMap();
679         mPermissions = new LegacyPermissionSettings(lock);
680         mRuntimePermissionsPersistence = new RuntimePermissionPersistence(
681                 runtimePermissionsPersistence, new Consumer<Integer>() {
682             @Override
683             public void accept(Integer userId) {
684                 mRuntimePermissionsPersistence.writeStateForUser(userId, mPermissionDataProvider,
685                         mPackages, mSharedUsers, mHandler, mLock, /*sync=*/false);
686             }
687         });
688         mPermissionDataProvider = permissionDataProvider;
689 
690         mSystemDir = new File(dataDir, "system");
691         mSystemDir.mkdirs();
692         FileUtils.setPermissions(mSystemDir.toString(),
693                 FileUtils.S_IRWXU|FileUtils.S_IRWXG
694                 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
695                 -1, -1);
696         mSettingsFilename = new File(mSystemDir, "packages.xml");
697         mBackupSettingsFilename = new File(mSystemDir, "packages-backup.xml");
698         mPackageListFilename = new File(mSystemDir, "packages.list");
699         FileUtils.setPermissions(mPackageListFilename, 0640, SYSTEM_UID, PACKAGE_INFO_GID);
700 
701         final File kernelDir = new File("/config/sdcardfs");
702         mKernelMappingFilename = kernelDir.exists() ? kernelDir : null;
703 
704         // Deprecated: Needed for migration
705         mStoppedPackagesFilename = new File(mSystemDir, "packages-stopped.xml");
706         mBackupStoppedPackagesFilename = new File(mSystemDir, "packages-stopped-backup.xml");
707 
708         mDomainVerificationManager = domainVerificationManager;
709 
710         registerObservers();
711         Watchable.verifyWatchedAttributes(this, mObserver);
712 
713         mSnapshot = makeCache();
714     }
715 
716     /**
717      * A copy constructor used in snapshot().  Attributes that are supposed to be
718      * immutable in the PackageManagerService application are referenced.  Attributes that
719      * are changed by PackageManagerService APIs are deep-copied
720      */
721     private Settings(Settings r) {
722         mPackages = r.mPackagesSnapshot.snapshot();
723         mPackagesSnapshot  = new SnapshotCache.Sealed<>();
724         mKernelMapping = r.mKernelMappingSnapshot.snapshot();
725         mKernelMappingSnapshot = new SnapshotCache.Sealed<>();
726         mInstallerPackages = r.mInstallerPackagesSnapshot.snapshot();
727         mInstallerPackagesSnapshot = new SnapshotCache.Sealed<>();
728         mKeySetManagerService = new KeySetManagerService(r.mKeySetManagerService, mPackages);
729 
730         // The following assignments satisfy Java requirements but are not
731         // needed by the read-only methods.  Note especially that the lock
732         // is not required because this clone is meant to support lock-free
733         // read-only methods.
734         mHandler = null;
735         mLock = null;
736         mRuntimePermissionsPersistence = r.mRuntimePermissionsPersistence;
737         mSettingsFilename = null;
738         mBackupSettingsFilename = null;
739         mPackageListFilename = null;
740         mStoppedPackagesFilename = null;
741         mBackupStoppedPackagesFilename = null;
742         mKernelMappingFilename = null;
743 
744         mDomainVerificationManager = r.mDomainVerificationManager;
745 
746         mDisabledSysPackages.snapshot(r.mDisabledSysPackages);
747         mBlockUninstallPackages.snapshot(r.mBlockUninstallPackages);
748         mVersion.putAll(r.mVersion);
749         mVerifierDeviceIdentity = r.mVerifierDeviceIdentity;
750         mPreferredActivities = r.mPreferredActivitiesSnapshot.snapshot();
751         mPreferredActivitiesSnapshot = new SnapshotCache.Sealed<>();
752         mPersistentPreferredActivities = r.mPersistentPreferredActivitiesSnapshot.snapshot();
753         mPersistentPreferredActivitiesSnapshot = new SnapshotCache.Sealed<>();
754         mCrossProfileIntentResolvers = r.mCrossProfileIntentResolversSnapshot.snapshot();
755         mCrossProfileIntentResolversSnapshot = new SnapshotCache.Sealed<>();
756 
757         mSharedUsers.snapshot(r.mSharedUsers);
758         mAppIds = r.mAppIds.snapshot();
759 
760         mPastSignatures = r.mPastSignaturesSnapshot.snapshot();
761         mPastSignaturesSnapshot = new SnapshotCache.Sealed<>();
762         mKeySetRefs = r.mKeySetRefsSnapshot.snapshot();
763         mKeySetRefsSnapshot = new SnapshotCache.Sealed<>();
764 
765         mRenamedPackages.snapshot(r.mRenamedPackages);
766         mNextAppLinkGeneration.snapshot(r.mNextAppLinkGeneration);
767         mDefaultBrowserApp.snapshot(r.mDefaultBrowserApp);
768         // mReadMessages
769         mPendingPackages = r.mPendingPackagesSnapshot.snapshot();
770         mPendingPackagesSnapshot = new SnapshotCache.Sealed<>();
771         mSystemDir = null;
772         // mKeySetManagerService;
773         mPermissions = r.mPermissions;
774         mPermissionDataProvider = r.mPermissionDataProvider;
775 
776         // Do not register any Watchables and do not create a snapshot cache.
777         mSnapshot = new SnapshotCache.Sealed();
778     }
779 
780     /**
781      * Return a snapshot.
782      */
783     public Settings snapshot() {
784         return mSnapshot.snapshot();
785     }
786 
787     private void invalidatePackageCache() {
788         PackageManagerService.invalidatePackageInfoCache();
789         ChangeIdStateCache.invalidate();
790         onChanged();
791     }
792 
793     PackageSetting getPackageLPr(String pkgName) {
794         return mPackages.get(pkgName);
795     }
796 
797     WatchedArrayMap<String, PackageSetting> getPackagesLocked() {
798         return mPackages;
799     }
800 
801     KeySetManagerService getKeySetManagerService() {
802         return mKeySetManagerService;
803     }
804 
805     String getRenamedPackageLPr(String pkgName) {
806         return mRenamedPackages.get(pkgName);
807     }
808 
809     String addRenamedPackageLPw(String pkgName, String origPkgName) {
810         return mRenamedPackages.put(pkgName, origPkgName);
811     }
812 
813     void removeRenamedPackageLPw(String pkgName) {
814         mRenamedPackages.remove(pkgName);
815     }
816 
817     void pruneRenamedPackagesLPw() {
818         for (int i = mRenamedPackages.size() - 1; i >= 0; i--) {
819             PackageSetting ps = mPackages.get(mRenamedPackages.valueAt(i));
820             if (ps == null) {
821                 mRenamedPackages.removeAt(i);
822             }
823         }
824     }
825 
826     /** Gets and optionally creates a new shared user id. */
827     SharedUserSetting getSharedUserLPw(String name, int pkgFlags, int pkgPrivateFlags,
828             boolean create) throws PackageManagerException {
829         SharedUserSetting s = mSharedUsers.get(name);
830         if (s == null && create) {
831             s = new SharedUserSetting(name, pkgFlags, pkgPrivateFlags);
832             s.mAppId = mAppIds.acquireAndRegisterNewAppId(s);
833             if (s.mAppId < 0) {
834                 // < 0 means we couldn't assign a userid; throw exception
835                 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
836                         "Creating shared user " + name + " failed");
837             }
838             Log.i(PackageManagerService.TAG, "New shared user " + name + ": id=" + s.mAppId);
839             mSharedUsers.put(name, s);
840         }
841         return s;
842     }
843 
844     Collection<SharedUserSetting> getAllSharedUsersLPw() {
845         return mSharedUsers.values();
846     }
847 
848     boolean disableSystemPackageLPw(String name, boolean replaced) {
849         final PackageSetting p = mPackages.get(name);
850         if(p == null) {
851             Log.w(PackageManagerService.TAG, "Package " + name + " is not an installed package");
852             return false;
853         }
854         final PackageSetting dp = mDisabledSysPackages.get(name);
855         // always make sure the system package code and resource paths dont change
856         if (dp == null && p.getPkg() != null && p.getPkg().isSystem()
857                 && !p.getPkgState().isUpdatedSystemApp()) {
858             p.getPkgState().setUpdatedSystemApp(true);
859             final PackageSetting disabled;
860             if (replaced) {
861                 // a little trick...  when we install the new package, we don't
862                 // want to modify the existing PackageSetting for the built-in
863                 // version.  so at this point we make a copy to place into the
864                 // disabled set.
865                 disabled = new PackageSetting(p);
866             } else {
867                 disabled = p;
868             }
869             mDisabledSysPackages.put(name, disabled);
870             SharedUserSetting sharedUserSetting = getSharedUserSettingLPr(disabled);
871             if (sharedUserSetting != null) {
872                 sharedUserSetting.mDisabledPackages.add(disabled);
873             }
874             return true;
875         }
876         return false;
877     }
878 
879     PackageSetting enableSystemPackageLPw(String name) {
880         PackageSetting p = mDisabledSysPackages.get(name);
881         if(p == null) {
882             Log.w(PackageManagerService.TAG, "Package " + name + " is not disabled");
883             return null;
884         }
885         SharedUserSetting sharedUserSetting = getSharedUserSettingLPr(p);
886         if (sharedUserSetting != null) {
887             sharedUserSetting.mDisabledPackages.remove(p);
888         }
889         p.getPkgState().setUpdatedSystemApp(false);
890         PackageSetting ret = addPackageLPw(name, p.getRealName(), p.getPath(),
891                 p.getLegacyNativeLibraryPath(), p.getPrimaryCpuAbi(),
892                 p.getSecondaryCpuAbi(), p.getCpuAbiOverride(),
893                 p.getAppId(), p.getVersionCode(), p.getFlags(), p.getPrivateFlags(),
894                 p.getUsesSdkLibraries(), p.getUsesSdkLibrariesVersionsMajor(),
895                 p.getUsesStaticLibraries(), p.getUsesStaticLibrariesVersions(), p.getMimeGroups(),
896                 mDomainVerificationManager.generateNewId());
897         if (ret != null) {
898             ret.getPkgState().setUpdatedSystemApp(false);
899         }
900         mDisabledSysPackages.remove(name);
901         return ret;
902     }
903 
904     boolean isDisabledSystemPackageLPr(String name) {
905         return mDisabledSysPackages.containsKey(name);
906     }
907 
908     void removeDisabledSystemPackageLPw(String name) {
909         final PackageSetting p = mDisabledSysPackages.remove(name);
910         if (p != null) {
911             SharedUserSetting sharedUserSetting = getSharedUserSettingLPr(p);
912             if (sharedUserSetting != null) {
913                 sharedUserSetting.mDisabledPackages.remove(p);
914                 checkAndPruneSharedUserLPw(sharedUserSetting, false);
915             }
916         }
917     }
918 
919     PackageSetting addPackageLPw(String name, String realName, File codePath,
920             String legacyNativeLibraryPathString, String primaryCpuAbiString,
921             String secondaryCpuAbiString, String cpuAbiOverrideString, int uid, long vc,
922             int pkgFlags, int pkgPrivateFlags, String[] usesSdkLibraries,
923             long[] usesSdkLibrariesVersions, String[] usesStaticLibraries,
924             long[] usesStaticLibrariesVersions, Map<String, Set<String>> mimeGroups,
925             @NonNull UUID domainSetId) {
926         PackageSetting p = mPackages.get(name);
927         if (p != null) {
928             if (p.getAppId() == uid) {
929                 return p;
930             }
931             PackageManagerService.reportSettingsProblem(Log.ERROR,
932                     "Adding duplicate package, keeping first: " + name);
933             return null;
934         }
935         p = new PackageSetting(name, realName, codePath, legacyNativeLibraryPathString,
936                 primaryCpuAbiString, secondaryCpuAbiString, cpuAbiOverrideString, vc, pkgFlags,
937                 pkgPrivateFlags, 0 /*userId*/, usesSdkLibraries, usesSdkLibrariesVersions,
938                 usesStaticLibraries, usesStaticLibrariesVersions, mimeGroups, domainSetId);
939         p.setAppId(uid);
940         if (mAppIds.registerExistingAppId(uid, p, name)) {
941             mPackages.put(name, p);
942             return p;
943         }
944         return null;
945     }
946 
947     SharedUserSetting addSharedUserLPw(String name, int uid, int pkgFlags, int pkgPrivateFlags) {
948         SharedUserSetting s = mSharedUsers.get(name);
949         if (s != null) {
950             if (s.mAppId == uid) {
951                 return s;
952             }
953             PackageManagerService.reportSettingsProblem(Log.ERROR,
954                     "Adding duplicate shared user, keeping first: " + name);
955             return null;
956         }
957         s = new SharedUserSetting(name, pkgFlags, pkgPrivateFlags);
958         s.mAppId = uid;
959         if (mAppIds.registerExistingAppId(uid, s, name)) {
960             mSharedUsers.put(name, s);
961             return s;
962         }
963         return null;
964     }
965 
966     void pruneSharedUsersLPw() {
967         List<String> removeKeys = new ArrayList<>();
968         List<SharedUserSetting> removeValues = new ArrayList<>();
969         for (Map.Entry<String, SharedUserSetting> entry : mSharedUsers.entrySet()) {
970             final SharedUserSetting sus = entry.getValue();
971             if (sus == null) {
972                 removeKeys.add(entry.getKey());
973                 continue;
974             }
975             boolean changed = false;
976             // remove packages that are no longer installed
977             WatchedArraySet<PackageSetting> sharedUserPackageSettings = sus.getPackageSettings();
978             for (int i = sharedUserPackageSettings.size() - 1; i >= 0; i--) {
979                 PackageSetting ps = sharedUserPackageSettings.valueAt(i);
980                 if (mPackages.get(ps.getPackageName()) == null) {
981                     sharedUserPackageSettings.removeAt(i);
982                     changed = true;
983                 }
984             }
985             WatchedArraySet<PackageSetting> sharedUserDisabledPackageSettings =
986                     sus.getDisabledPackageSettings();
987             for (int i = sharedUserDisabledPackageSettings.size() - 1; i >= 0; i--) {
988                 PackageSetting ps = sharedUserDisabledPackageSettings.valueAt(i);
989                 if (mDisabledSysPackages.get(ps.getPackageName()) == null) {
990                     sharedUserDisabledPackageSettings.removeAt(i);
991                     changed = true;
992                 }
993             }
994             if (changed) {
995                 sus.onChanged();
996             }
997             if (sharedUserPackageSettings.isEmpty()
998                     && sharedUserDisabledPackageSettings.isEmpty()) {
999                 removeValues.add(sus);
1000             }
1001         }
1002         removeKeys.forEach(mSharedUsers::remove);
1003         removeValues.forEach(sus -> checkAndPruneSharedUserLPw(sus, true));
1004     }
1005 
1006     /**
1007      * Creates a new {@code PackageSetting} object.
1008      * Use this method instead of the constructor to ensure a settings object is created
1009      * with the correct base.
1010      */
1011     static @NonNull PackageSetting createNewSetting(String pkgName, PackageSetting originalPkg,
1012             PackageSetting disabledPkg, String realPkgName, SharedUserSetting sharedUser,
1013             File codePath, String legacyNativeLibraryPath, String primaryCpuAbi,
1014             String secondaryCpuAbi, long versionCode, int pkgFlags, int pkgPrivateFlags,
1015             UserHandle installUser, boolean allowInstall, boolean instantApp,
1016             boolean virtualPreload, UserManagerService userManager,
1017             String[] usesSdkLibraries, long[] usesSdkLibrariesVersions,
1018             String[] usesStaticLibraries, long[] usesStaticLibrariesVersions,
1019             Set<String> mimeGroupNames, @NonNull UUID domainSetId) {
1020         final PackageSetting pkgSetting;
1021         if (originalPkg != null) {
1022             if (PackageManagerService.DEBUG_UPGRADE) Log.v(PackageManagerService.TAG, "Package "
1023                     + pkgName + " is adopting original package " + originalPkg.getPackageName());
1024             pkgSetting = new PackageSetting(originalPkg, pkgName /*realPkgName*/)
1025                     .setPath(codePath)
1026                     .setLegacyNativeLibraryPath(legacyNativeLibraryPath)
1027                     .setPrimaryCpuAbi(primaryCpuAbi)
1028                     .setSecondaryCpuAbi(secondaryCpuAbi)
1029                     // NOTE: Create a deeper copy of the package signatures so we don't
1030                     // overwrite the signatures in the original package setting.
1031                     .setSignatures(new PackageSignatures())
1032                     .setLongVersionCode(versionCode)
1033                     .setUsesSdkLibraries(usesSdkLibraries)
1034                     .setUsesSdkLibrariesVersionsMajor(usesSdkLibrariesVersions)
1035                     .setUsesStaticLibraries(usesStaticLibraries)
1036                     .setUsesStaticLibrariesVersions(usesStaticLibrariesVersions)
1037                     // Update new package state.
1038                     .setLastModifiedTime(codePath.lastModified())
1039                     .setDomainSetId(domainSetId);
1040             pkgSetting.setPkgFlags(pkgFlags, pkgPrivateFlags);
1041         } else {
1042             pkgSetting = new PackageSetting(pkgName, realPkgName, codePath,
1043                     legacyNativeLibraryPath, primaryCpuAbi, secondaryCpuAbi,
1044                     null /*cpuAbiOverrideString*/, versionCode, pkgFlags, pkgPrivateFlags,
1045                     0 /*sharedUserId*/, usesSdkLibraries, usesSdkLibrariesVersions,
1046                     usesStaticLibraries, usesStaticLibrariesVersions,
1047                     createMimeGroups(mimeGroupNames), domainSetId);
1048             pkgSetting.setLastModifiedTime(codePath.lastModified());
1049             if (sharedUser != null) {
1050                 pkgSetting.setSharedUserAppId(sharedUser.mAppId);
1051             }
1052             // If this is not a system app, it starts out stopped.
1053             if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
1054                 if (DEBUG_STOPPED) {
1055                     RuntimeException e = new RuntimeException("here");
1056                     e.fillInStackTrace();
1057                     Slog.i(PackageManagerService.TAG, "Stopping package " + pkgName, e);
1058                 }
1059                 List<UserInfo> users = getAllUsers(userManager);
1060                 int installUserId = installUser != null ? installUser.getIdentifier()
1061                         : UserHandle.USER_SYSTEM;
1062                 if (users != null && allowInstall) {
1063                     for (UserInfo user : users) {
1064                         // By default we consider this app to be installed
1065                         // for the user if no user has been specified (which
1066                         // means to leave it at its original value, and the
1067                         // original default value is true), or we are being
1068                         // asked to install for all users, or this is the
1069                         // user we are installing for.
1070                         final boolean installed = installUser == null
1071                                 || (installUserId == UserHandle.USER_ALL
1072                                     && !isAdbInstallDisallowed(userManager, user.id)
1073                                     && !user.preCreated)
1074                                 || installUserId == user.id;
1075                         if (DEBUG_MU) {
1076                             Slogf.d(TAG, "createNewSetting(pkg=%s, installUserId=%s, user=%s, "
1077                                     + "installed=%b)",
1078                                     pkgName, installUserId, user.toFullString(), installed);
1079                         }
1080                         pkgSetting.setUserState(user.id, 0, COMPONENT_ENABLED_STATE_DEFAULT,
1081                                 installed,
1082                                 true /*stopped*/,
1083                                 true /*notLaunched*/,
1084                                 false /*hidden*/,
1085                                 0 /*distractionFlags*/,
1086                                 null /*suspendParams*/,
1087                                 instantApp,
1088                                 virtualPreload,
1089                                 null /*lastDisableAppCaller*/,
1090                                 null /*enabledComponents*/,
1091                                 null /*disabledComponents*/,
1092                                 PackageManager.INSTALL_REASON_UNKNOWN,
1093                                 PackageManager.UNINSTALL_REASON_UNKNOWN,
1094                                 null /*harmfulAppWarning*/,
1095                                 null /*splashscreenTheme*/,
1096                                 0 /*firstInstallTime*/
1097                         );
1098                     }
1099                 }
1100             }
1101             if (sharedUser != null) {
1102                 pkgSetting.setAppId(sharedUser.mAppId);
1103             } else {
1104                 // Clone the setting here for disabled system packages
1105                 if (disabledPkg != null) {
1106                     // For disabled packages a new setting is created
1107                     // from the existing user id. This still has to be
1108                     // added to list of user id's
1109                     // Copy signatures from previous setting
1110                     pkgSetting.setSignatures(new PackageSignatures(disabledPkg.getSignatures()));
1111                     pkgSetting.setAppId(disabledPkg.getAppId());
1112                     // Clone permissions
1113                     pkgSetting.getLegacyPermissionState()
1114                             .copyFrom(disabledPkg.getLegacyPermissionState());
1115                     // Clone component info
1116                     List<UserInfo> users = getAllUsers(userManager);
1117                     if (users != null) {
1118                         for (UserInfo user : users) {
1119                             final int userId = user.id;
1120                             pkgSetting.setDisabledComponentsCopy(
1121                                     disabledPkg.getDisabledComponents(userId), userId);
1122                             pkgSetting.setEnabledComponentsCopy(
1123                                     disabledPkg.getEnabledComponents(userId), userId);
1124                         }
1125                     }
1126                 }
1127             }
1128         }
1129         return pkgSetting;
1130     }
1131 
1132     private static Map<String, Set<String>> createMimeGroups(Set<String> mimeGroupNames) {
1133         if (mimeGroupNames == null) {
1134             return null;
1135         }
1136 
1137         return new KeySetToValueMap<>(mimeGroupNames, new ArraySet<>());
1138     }
1139 
1140     /**
1141      * Updates the given package setting using the provided information.
1142      * <p>
1143      * WARNING: The provided PackageSetting object may be mutated.
1144      */
1145     static void updatePackageSetting(@NonNull PackageSetting pkgSetting,
1146             @Nullable PackageSetting disabledPkg,
1147             @Nullable SharedUserSetting existingSharedUserSetting,
1148             @Nullable SharedUserSetting sharedUser,
1149             @NonNull File codePath, @Nullable String legacyNativeLibraryPath,
1150             @Nullable String primaryCpuAbi, @Nullable String secondaryCpuAbi, int pkgFlags,
1151             int pkgPrivateFlags, @NonNull UserManagerService userManager,
1152             @Nullable String[] usesSdkLibraries, @Nullable long[] usesSdkLibrariesVersions,
1153             @Nullable String[] usesStaticLibraries, @Nullable long[] usesStaticLibrariesVersions,
1154             @Nullable Set<String> mimeGroupNames, @NonNull UUID domainSetId)
1155                     throws PackageManagerException {
1156         final String pkgName = pkgSetting.getPackageName();
1157         if (sharedUser != null) {
1158             if (!Objects.equals(existingSharedUserSetting, sharedUser)) {
1159                 PackageManagerService.reportSettingsProblem(Log.WARN,
1160                         "Package " + pkgName + " shared user changed from "
1161                                 + (existingSharedUserSetting != null
1162                                 ? existingSharedUserSetting.name : "<nothing>")
1163                                 + " to " + sharedUser.name);
1164                 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
1165                         "Updating application package " + pkgName + " failed");
1166             }
1167             pkgSetting.setSharedUserAppId(sharedUser.mAppId);
1168         } else {
1169             // migrating off shared user
1170             pkgSetting.setSharedUserAppId(INVALID_UID);
1171         }
1172 
1173         if (!pkgSetting.getPath().equals(codePath)) {
1174             final boolean isSystem = pkgSetting.isSystem();
1175             Slog.i(PackageManagerService.TAG,
1176                     "Update" + (isSystem ? " system" : "")
1177                     + " package " + pkgName
1178                     + " code path from " + pkgSetting.getPathString()
1179                     + " to " + codePath.toString()
1180                     + "; Retain data and using new");
1181             if (!isSystem) {
1182                 // The package isn't considered as installed if the application was
1183                 // first installed by another user. Update the installed flag when the
1184                 // application ever becomes part of the system.
1185                 if ((pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0 && disabledPkg == null) {
1186                     final List<UserInfo> allUserInfos = getAllUsers(userManager);
1187                     if (allUserInfos != null) {
1188                         for (UserInfo userInfo : allUserInfos) {
1189                             pkgSetting.setInstalled(true, userInfo.id);
1190                             pkgSetting.setUninstallReason(UNINSTALL_REASON_UNKNOWN, userInfo.id);
1191                         }
1192                     }
1193                 }
1194 
1195                 // Since we've changed paths, prefer the new native library path over
1196                 // the one stored in the package settings since we might have moved from
1197                 // internal to external storage or vice versa.
1198                 pkgSetting.setLegacyNativeLibraryPath(legacyNativeLibraryPath);
1199             }
1200             pkgSetting.setPath(codePath);
1201         }
1202 
1203         pkgSetting.setPrimaryCpuAbi(primaryCpuAbi)
1204                 .setSecondaryCpuAbi(secondaryCpuAbi)
1205                 .updateMimeGroups(mimeGroupNames)
1206                 .setDomainSetId(domainSetId);
1207         // Update SDK library dependencies if needed.
1208         if (usesSdkLibraries != null && usesSdkLibrariesVersions != null
1209                 && usesSdkLibraries.length == usesSdkLibrariesVersions.length) {
1210             pkgSetting.setUsesSdkLibraries(usesSdkLibraries)
1211                     .setUsesSdkLibrariesVersionsMajor(usesSdkLibrariesVersions);
1212         } else {
1213             pkgSetting.setUsesSdkLibraries(null)
1214                     .setUsesSdkLibrariesVersionsMajor(null);
1215         }
1216 
1217         // Update static shared library dependencies if needed.
1218         if (usesStaticLibraries != null && usesStaticLibrariesVersions != null
1219                 && usesStaticLibraries.length == usesStaticLibrariesVersions.length) {
1220             pkgSetting.setUsesStaticLibraries(usesStaticLibraries)
1221                     .setUsesStaticLibrariesVersions(usesStaticLibrariesVersions);
1222         } else {
1223             pkgSetting.setUsesStaticLibraries(null)
1224                     .setUsesStaticLibrariesVersions(null);
1225         }
1226 
1227         // If what we are scanning is a system (and possibly privileged) package,
1228         // then make it so, regardless of whether it was previously installed only
1229         // in the data partition. Reset first.
1230         int newPkgFlags = pkgSetting.getFlags();
1231         newPkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1232         newPkgFlags |= pkgFlags & ApplicationInfo.FLAG_SYSTEM;
1233         // Only set pkgFlags.
1234         pkgSetting.setPkgFlags(newPkgFlags, pkgSetting.getPrivateFlags());
1235 
1236         boolean wasRequiredForSystemUser = (pkgSetting.getPrivateFlags()
1237                 & ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER) != 0;
1238         if (wasRequiredForSystemUser) {
1239             pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
1240         } else {
1241             pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
1242         }
1243         pkgSetting.setPrivateFlags(pkgPrivateFlags);
1244     }
1245 
1246     /**
1247      * Registers a user ID with the system. Potentially allocates a new user ID.
1248      * @return {@code true} if a new app ID was created in the process. {@code false} can be
1249      *         returned in the case that a shared user ID already exists or the explicit app ID is
1250      *         already registered.
1251      * @throws PackageManagerException If a user ID could not be allocated.
1252      */
1253     boolean registerAppIdLPw(PackageSetting p, boolean forceNew) throws PackageManagerException {
1254         final boolean createdNew;
1255         if (p.getAppId() == 0 || forceNew) {
1256             // Assign new user ID
1257             p.setAppId(mAppIds.acquireAndRegisterNewAppId(p));
1258             createdNew = true;
1259         } else {
1260             // Add new setting to list of user IDs
1261             createdNew = mAppIds.registerExistingAppId(p.getAppId(), p, p.getPackageName());
1262         }
1263         if (p.getAppId() < 0) {
1264             PackageManagerService.reportSettingsProblem(Log.WARN,
1265                     "Package " + p.getPackageName() + " could not be assigned a valid UID");
1266             throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
1267                     "Package " + p.getPackageName() + " could not be assigned a valid UID");
1268         }
1269         return createdNew;
1270     }
1271 
1272     /**
1273      * Writes per-user package restrictions if the user state has changed. If the user
1274      * state has not changed, this does nothing.
1275      */
1276     void writeUserRestrictionsLPw(PackageSetting newPackage, PackageSetting oldPackage) {
1277         // package doesn't exist; do nothing
1278         if (getPackageLPr(newPackage.getPackageName()) == null) {
1279             return;
1280         }
1281         // no users defined; do nothing
1282         final List<UserInfo> allUsers = getAllUsers(UserManagerService.getInstance());
1283         if (allUsers == null) {
1284             return;
1285         }
1286         for (UserInfo user : allUsers) {
1287             final PackageUserState oldUserState = oldPackage == null
1288                     ? PackageUserState.DEFAULT
1289                     : oldPackage.readUserState(user.id);
1290             if (!oldUserState.equals(newPackage.readUserState(user.id))) {
1291                 writePackageRestrictionsLPr(user.id);
1292             }
1293         }
1294     }
1295 
1296     static boolean isAdbInstallDisallowed(UserManagerService userManager, int userId) {
1297         return userManager.hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES,
1298                 userId);
1299     }
1300 
1301     // TODO: Move to scanPackageOnlyLI() after verifying signatures are setup correctly
1302     // by that time.
1303     void insertPackageSettingLPw(PackageSetting p, AndroidPackage pkg) {
1304         // Update signatures if needed.
1305         if (p.getSigningDetails().getSignatures() == null) {
1306             p.setSigningDetails(pkg.getSigningDetails());
1307         }
1308         // If this app defines a shared user id initialize
1309         // the shared user signatures as well.
1310         SharedUserSetting sharedUserSetting = getSharedUserSettingLPr(p);
1311         if (sharedUserSetting != null) {
1312             if (sharedUserSetting.signatures.mSigningDetails.getSignatures() == null) {
1313                 sharedUserSetting.signatures.mSigningDetails = pkg.getSigningDetails();
1314             }
1315         }
1316         addPackageSettingLPw(p, sharedUserSetting);
1317     }
1318 
1319     // Utility method that adds a PackageSetting to mPackages and
1320     // completes updating the shared user attributes and any restored
1321     // app link verification state
1322     @VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE)
1323     void addPackageSettingLPw(PackageSetting p, SharedUserSetting sharedUser) {
1324         mPackages.put(p.getPackageName(), p);
1325         if (sharedUser != null) {
1326             SharedUserSetting existingSharedUserSetting = getSharedUserSettingLPr(p);
1327             if (existingSharedUserSetting != null && existingSharedUserSetting != sharedUser) {
1328                 PackageManagerService.reportSettingsProblem(Log.ERROR,
1329                         "Package " + p.getPackageName() + " was user "
1330                         + existingSharedUserSetting + " but is now " + sharedUser
1331                         + "; I am not changing its files so it will probably fail!");
1332                 sharedUser.removePackage(p);
1333             } else if (p.getAppId() != sharedUser.mAppId) {
1334                 PackageManagerService.reportSettingsProblem(Log.ERROR,
1335                         "Package " + p.getPackageName() + " was user id " + p.getAppId()
1336                                 + " but is now user " + sharedUser
1337                                 + " with id " + sharedUser.mAppId
1338                                 + "; I am not changing its files so it will probably fail!");
1339             }
1340 
1341             sharedUser.addPackage(p);
1342             p.setSharedUserAppId(sharedUser.mAppId);
1343             p.setAppId(sharedUser.mAppId);
1344         }
1345 
1346         // If we know about this user id, we have to update it as it
1347         // has to point to the same PackageSetting instance as the package.
1348         Object userIdPs = getSettingLPr(p.getAppId());
1349         if (sharedUser == null) {
1350             if (userIdPs != null && userIdPs != p) {
1351                 mAppIds.replaceSetting(p.getAppId(), p);
1352             }
1353         } else {
1354             if (userIdPs != null && userIdPs != sharedUser) {
1355                 mAppIds.replaceSetting(p.getAppId(), sharedUser);
1356             }
1357         }
1358     }
1359 
1360     boolean checkAndPruneSharedUserLPw(SharedUserSetting s, boolean skipCheck) {
1361         if (skipCheck || (s.getPackageStates().isEmpty()
1362                 && s.getDisabledPackageStates().isEmpty())) {
1363             if (mSharedUsers.remove(s.name) != null) {
1364                 removeAppIdLPw(s.mAppId);
1365                 return true;
1366             }
1367         }
1368         return false;
1369     }
1370 
1371     int removePackageLPw(String name) {
1372         final PackageSetting p = mPackages.remove(name);
1373         if (p != null) {
1374             removeInstallerPackageStatus(name);
1375             SharedUserSetting sharedUserSetting = getSharedUserSettingLPr(p);
1376             if (sharedUserSetting != null) {
1377                 sharedUserSetting.removePackage(p);
1378                 if (checkAndPruneSharedUserLPw(sharedUserSetting, false)) {
1379                     return sharedUserSetting.mAppId;
1380                 }
1381             } else {
1382                 removeAppIdLPw(p.getAppId());
1383                 return p.getAppId();
1384             }
1385         }
1386         return -1;
1387     }
1388 
1389     /**
1390      * Checks if {@param packageName} is an installer package and if so, clear the installer
1391      * package name of the packages that are installed by this.
1392      */
1393     private void removeInstallerPackageStatus(String packageName) {
1394         // Check if the package to be removed is an installer package.
1395         if (!mInstallerPackages.contains(packageName)) {
1396             return;
1397         }
1398         for (int i = 0; i < mPackages.size(); i++) {
1399             mPackages.valueAt(i).removeInstallerPackage(packageName);
1400         }
1401         mInstallerPackages.remove(packageName);
1402     }
1403 
1404     /** Gets the setting associated with the provided App ID */
1405     public SettingBase getSettingLPr(int appId) {
1406         return mAppIds.getSetting(appId);
1407     }
1408 
1409     /** Unregisters the provided app ID. */
1410     void removeAppIdLPw(int appId) {
1411         mAppIds.removeSetting(appId);
1412     }
1413     /**
1414      * Transparently convert a SharedUserSetting into PackageSettings without changing appId.
1415      * The sharedUser passed to this method has to be {@link SharedUserSetting#isSingleUser()}.
1416      */
1417     void convertSharedUserSettingsLPw(SharedUserSetting sharedUser) {
1418         final PackageSetting ps = sharedUser.getPackageSettings().valueAt(0);
1419         mAppIds.replaceSetting(sharedUser.getAppId(), ps);
1420 
1421         // Unlink the SharedUserSetting
1422         ps.setSharedUserAppId(INVALID_UID);
1423         if (!sharedUser.getDisabledPackageSettings().isEmpty()) {
1424             final PackageSetting disabledPs = sharedUser.getDisabledPackageSettings().valueAt(0);
1425             disabledPs.setSharedUserAppId(INVALID_UID);
1426         }
1427         mSharedUsers.remove(sharedUser.getName());
1428     }
1429 
1430     /**
1431      * Check and convert eligible SharedUserSettings to PackageSettings.
1432      */
1433     void checkAndConvertSharedUserSettingsLPw(SharedUserSetting sharedUser) {
1434         if (!sharedUser.isSingleUser()) return;
1435         final AndroidPackage pkg = sharedUser.getPackageSettings().valueAt(0).getPkg();
1436         if (pkg != null && pkg.isLeavingSharedUid()
1437                 && SharedUidMigration.applyStrategy(BEST_EFFORT)) {
1438             convertSharedUserSettingsLPw(sharedUser);
1439         }
1440     }
1441 
1442     PreferredIntentResolver editPreferredActivitiesLPw(int userId) {
1443         PreferredIntentResolver pir = mPreferredActivities.get(userId);
1444         if (pir == null) {
1445             pir = new PreferredIntentResolver();
1446             mPreferredActivities.put(userId, pir);
1447         }
1448         return pir;
1449     }
1450 
1451     PersistentPreferredIntentResolver editPersistentPreferredActivitiesLPw(int userId) {
1452         PersistentPreferredIntentResolver ppir = mPersistentPreferredActivities.get(userId);
1453         if (ppir == null) {
1454             ppir = new PersistentPreferredIntentResolver();
1455             mPersistentPreferredActivities.put(userId, ppir);
1456         }
1457         return ppir;
1458     }
1459 
1460     CrossProfileIntentResolver editCrossProfileIntentResolverLPw(int userId) {
1461         CrossProfileIntentResolver cpir = mCrossProfileIntentResolvers.get(userId);
1462         if (cpir == null) {
1463             cpir = new CrossProfileIntentResolver();
1464             mCrossProfileIntentResolvers.put(userId, cpir);
1465         }
1466         return cpir;
1467     }
1468 
1469     String removeDefaultBrowserPackageNameLPw(int userId) {
1470         return (userId == UserHandle.USER_ALL) ? null : mDefaultBrowserApp.removeReturnOld(userId);
1471     }
1472 
1473     private File getUserPackagesStateFile(int userId) {
1474         // TODO: Implement a cleaner solution when adding tests.
1475         // This instead of Environment.getUserSystemDirectory(userId) to support testing.
1476         File userDir = new File(new File(mSystemDir, "users"), Integer.toString(userId));
1477         return new File(userDir, "package-restrictions.xml");
1478     }
1479 
1480     private File getUserRuntimePermissionsFile(int userId) {
1481         // TODO: Implement a cleaner solution when adding tests.
1482         // This instead of Environment.getUserSystemDirectory(userId) to support testing.
1483         File userDir = new File(new File(mSystemDir, "users"), Integer.toString(userId));
1484         return new File(userDir, RUNTIME_PERMISSIONS_FILE_NAME);
1485     }
1486 
1487     private File getUserPackagesStateBackupFile(int userId) {
1488         return new File(Environment.getUserSystemDirectory(userId),
1489                 "package-restrictions-backup.xml");
1490     }
1491 
1492     void writeAllUsersPackageRestrictionsLPr() {
1493         List<UserInfo> users = getAllUsers(UserManagerService.getInstance());
1494         if (users == null) return;
1495 
1496         for (UserInfo user : users) {
1497             writePackageRestrictionsLPr(user.id);
1498         }
1499     }
1500 
1501     void writeAllRuntimePermissionsLPr() {
1502         for (int userId : UserManagerService.getInstance().getUserIds()) {
1503             mRuntimePermissionsPersistence.writeStateForUserAsync(userId);
1504         }
1505     }
1506 
1507     boolean isPermissionUpgradeNeeded(int userId) {
1508         return mRuntimePermissionsPersistence.isPermissionUpgradeNeeded(userId);
1509     }
1510 
1511     void updateRuntimePermissionsFingerprint(@UserIdInt int userId) {
1512         mRuntimePermissionsPersistence.updateRuntimePermissionsFingerprint(userId);
1513     }
1514 
1515     int getDefaultRuntimePermissionsVersion(int userId) {
1516         return mRuntimePermissionsPersistence.getVersion(userId);
1517     }
1518 
1519     void setDefaultRuntimePermissionsVersion(int version, int userId) {
1520         mRuntimePermissionsPersistence.setVersion(version, userId);
1521     }
1522 
1523     void setPermissionControllerVersion(long version) {
1524         mRuntimePermissionsPersistence.setPermissionControllerVersion(version);
1525     }
1526 
1527     public VersionInfo findOrCreateVersion(String volumeUuid) {
1528         VersionInfo ver = mVersion.get(volumeUuid);
1529         if (ver == null) {
1530             ver = new VersionInfo();
1531             mVersion.put(volumeUuid, ver);
1532         }
1533         return ver;
1534     }
1535 
1536     public VersionInfo getInternalVersion() {
1537         return mVersion.get(StorageManager.UUID_PRIVATE_INTERNAL);
1538     }
1539 
1540     public VersionInfo getExternalVersion() {
1541         return mVersion.get(StorageManager.UUID_PRIMARY_PHYSICAL);
1542     }
1543 
1544     public void onVolumeForgotten(String fsUuid) {
1545         mVersion.remove(fsUuid);
1546     }
1547 
1548     /**
1549      * Applies the preferred activity state described by the given XML.  This code
1550      * also supports the restore-from-backup code path.
1551      *
1552      * @see PreferredActivityBackupHelper
1553      */
1554     void readPreferredActivitiesLPw(TypedXmlPullParser parser, int userId)
1555             throws XmlPullParserException, IOException {
1556         int outerDepth = parser.getDepth();
1557         int type;
1558         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1559                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1560             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1561                 continue;
1562             }
1563 
1564             String tagName = parser.getName();
1565             if (tagName.equals(TAG_ITEM)) {
1566                 PreferredActivity pa = new PreferredActivity(parser);
1567                 if (pa.mPref.getParseError() == null) {
1568                     final PreferredIntentResolver resolver = editPreferredActivitiesLPw(userId);
1569                     if (resolver.shouldAddPreferredActivity(pa)) {
1570                         resolver.addFilter(null, pa);
1571                     }
1572                 } else {
1573                     PackageManagerService.reportSettingsProblem(Log.WARN,
1574                             "Error in package manager settings: <preferred-activity> "
1575                                     + pa.mPref.getParseError() + " at "
1576                                     + parser.getPositionDescription());
1577                 }
1578             } else {
1579                 PackageManagerService.reportSettingsProblem(Log.WARN,
1580                         "Unknown element under <preferred-activities>: " + parser.getName());
1581                 XmlUtils.skipCurrentTag(parser);
1582             }
1583         }
1584     }
1585 
1586     private void readPersistentPreferredActivitiesLPw(TypedXmlPullParser parser, int userId)
1587             throws XmlPullParserException, IOException {
1588         int outerDepth = parser.getDepth();
1589         int type;
1590         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1591                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1592             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1593                 continue;
1594             }
1595             String tagName = parser.getName();
1596             if (tagName.equals(TAG_ITEM)) {
1597                 PersistentPreferredActivity ppa = new PersistentPreferredActivity(parser);
1598                 editPersistentPreferredActivitiesLPw(userId).addFilter(null, ppa);
1599             } else {
1600                 PackageManagerService.reportSettingsProblem(Log.WARN,
1601                         "Unknown element under <" + TAG_PERSISTENT_PREFERRED_ACTIVITIES + ">: "
1602                         + parser.getName());
1603                 XmlUtils.skipCurrentTag(parser);
1604             }
1605         }
1606     }
1607 
1608     private void readCrossProfileIntentFiltersLPw(TypedXmlPullParser parser, int userId)
1609             throws XmlPullParserException, IOException {
1610         int outerDepth = parser.getDepth();
1611         int type;
1612         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1613                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1614             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1615                 continue;
1616             }
1617             final String tagName = parser.getName();
1618             if (tagName.equals(TAG_ITEM)) {
1619                 CrossProfileIntentFilter cpif = new CrossProfileIntentFilter(parser);
1620                 editCrossProfileIntentResolverLPw(userId).addFilter(null, cpif);
1621             } else {
1622                 String msg = "Unknown element under " +  TAG_CROSS_PROFILE_INTENT_FILTERS + ": " +
1623                         tagName;
1624                 PackageManagerService.reportSettingsProblem(Log.WARN, msg);
1625                 XmlUtils.skipCurrentTag(parser);
1626             }
1627         }
1628     }
1629 
1630     void readDefaultAppsLPw(XmlPullParser parser, int userId)
1631             throws XmlPullParserException, IOException {
1632         int outerDepth = parser.getDepth();
1633         int type;
1634         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1635                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1636             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1637                 continue;
1638             }
1639             String tagName = parser.getName();
1640             if (tagName.equals(TAG_DEFAULT_BROWSER)) {
1641                 String packageName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
1642                 mDefaultBrowserApp.put(userId, packageName);
1643             } else if (tagName.equals(TAG_DEFAULT_DIALER)) {
1644                 // Ignored.
1645             } else {
1646                 String msg = "Unknown element under " +  TAG_DEFAULT_APPS + ": " +
1647                         parser.getName();
1648                 PackageManagerService.reportSettingsProblem(Log.WARN, msg);
1649                 XmlUtils.skipCurrentTag(parser);
1650             }
1651         }
1652     }
1653 
1654     void readBlockUninstallPackagesLPw(TypedXmlPullParser parser, int userId)
1655             throws XmlPullParserException, IOException {
1656         int outerDepth = parser.getDepth();
1657         int type;
1658         ArraySet<String> packages = new ArraySet<>();
1659         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1660                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1661             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1662                 continue;
1663             }
1664             String tagName = parser.getName();
1665             if (tagName.equals(TAG_BLOCK_UNINSTALL)) {
1666                 String packageName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
1667                 packages.add(packageName);
1668             } else {
1669                 String msg = "Unknown element under " +  TAG_BLOCK_UNINSTALL_PACKAGES + ": " +
1670                         parser.getName();
1671                 PackageManagerService.reportSettingsProblem(Log.WARN, msg);
1672                 XmlUtils.skipCurrentTag(parser);
1673             }
1674         }
1675         if (packages.isEmpty()) {
1676             mBlockUninstallPackages.remove(userId);
1677         } else {
1678             mBlockUninstallPackages.put(userId, packages);
1679         }
1680     }
1681 
1682     void readPackageRestrictionsLPr(int userId,
1683             @NonNull ArrayMap<String, Long> origFirstInstallTimes) {
1684         if (DEBUG_MU) {
1685             Log.i(TAG, "Reading package restrictions for user=" + userId);
1686         }
1687         FileInputStream str = null;
1688         File userPackagesStateFile = getUserPackagesStateFile(userId);
1689         File backupFile = getUserPackagesStateBackupFile(userId);
1690         if (backupFile.exists()) {
1691             try {
1692                 str = new FileInputStream(backupFile);
1693                 mReadMessages.append("Reading from backup stopped packages file\n");
1694                 PackageManagerService.reportSettingsProblem(Log.INFO,
1695                         "Need to read from backup stopped packages file");
1696                 if (userPackagesStateFile.exists()) {
1697                     // If both the backup and normal file exist, we
1698                     // ignore the normal one since it might have been
1699                     // corrupted.
1700                     Slog.w(PackageManagerService.TAG, "Cleaning up stopped packages file "
1701                             + userPackagesStateFile);
1702                     userPackagesStateFile.delete();
1703                 }
1704             } catch (java.io.IOException e) {
1705                 // We'll try for the normal settings file.
1706             }
1707         }
1708 
1709         try {
1710             if (str == null) {
1711                 if (!userPackagesStateFile.exists()) {
1712                     mReadMessages.append("No stopped packages file found\n");
1713                     PackageManagerService.reportSettingsProblem(Log.INFO,
1714                             "No stopped packages file; "
1715                             + "assuming all started");
1716                     // At first boot, make sure no packages are stopped.
1717                     // We usually want to have third party apps initialize
1718                     // in the stopped state, but not at first boot.  Also
1719                     // consider all applications to be installed.
1720                     for (PackageSetting pkg : mPackages.values()) {
1721                         pkg.setUserState(userId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
1722                                 true  /*installed*/,
1723                                 false /*stopped*/,
1724                                 false /*notLaunched*/,
1725                                 false /*hidden*/,
1726                                 0 /*distractionFlags*/,
1727                                 null /*suspendParams*/,
1728                                 false /*instantApp*/,
1729                                 false /*virtualPreload*/,
1730                                 null /*lastDisableAppCaller*/,
1731                                 null /*enabledComponents*/,
1732                                 null /*disabledComponents*/,
1733                                 PackageManager.INSTALL_REASON_UNKNOWN,
1734                                 PackageManager.UNINSTALL_REASON_UNKNOWN,
1735                                 null /*harmfulAppWarning*/,
1736                                 null /* splashScreenTheme*/,
1737                                 0 /*firstInstallTime*/
1738                         );
1739                     }
1740                     return;
1741                 }
1742                 str = new FileInputStream(userPackagesStateFile);
1743                 if (DEBUG_MU) Log.i(TAG, "Reading " + userPackagesStateFile);
1744             }
1745             final TypedXmlPullParser parser = Xml.resolvePullParser(str);
1746 
1747             int type;
1748             while ((type=parser.next()) != XmlPullParser.START_TAG
1749                        && type != XmlPullParser.END_DOCUMENT) {
1750                 ;
1751             }
1752 
1753             if (type != XmlPullParser.START_TAG) {
1754                 mReadMessages.append("No start tag found in package restrictions file\n");
1755                 PackageManagerService.reportSettingsProblem(Log.WARN,
1756                         "No start tag found in package manager stopped packages");
1757                 return;
1758             }
1759 
1760             int outerDepth = parser.getDepth();
1761             PackageSetting ps = null;
1762             while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1763                    && (type != XmlPullParser.END_TAG
1764                            || parser.getDepth() > outerDepth)) {
1765                 if (type == XmlPullParser.END_TAG
1766                         || type == XmlPullParser.TEXT) {
1767                     continue;
1768                 }
1769 
1770                 String tagName = parser.getName();
1771                 if (tagName.equals(TAG_PACKAGE)) {
1772                     String name = parser.getAttributeValue(null, ATTR_NAME);
1773                     ps = mPackages.get(name);
1774                     if (ps == null) {
1775                         Slog.w(PackageManagerService.TAG, "No package known for stopped package "
1776                                 + name);
1777                         XmlUtils.skipCurrentTag(parser);
1778                         continue;
1779                     }
1780 
1781                     final long ceDataInode =
1782                             parser.getAttributeLong(null, ATTR_CE_DATA_INODE, 0);
1783                     final boolean installed =
1784                             parser.getAttributeBoolean(null, ATTR_INSTALLED, true);
1785                     final boolean stopped =
1786                             parser.getAttributeBoolean(null, ATTR_STOPPED, false);
1787                     final boolean notLaunched =
1788                             parser.getAttributeBoolean(null, ATTR_NOT_LAUNCHED, false);
1789 
1790                     // For backwards compatibility with the previous name of "blocked", which
1791                     // now means hidden, read the old attribute as well.
1792                     boolean hidden = parser.getAttributeBoolean(null, ATTR_HIDDEN, false);
1793                     if (!hidden) {
1794                         hidden = parser.getAttributeBoolean(null, ATTR_BLOCKED, false);
1795                     }
1796 
1797                     final int distractionFlags = parser.getAttributeInt(null, ATTR_DISTRACTION_FLAGS, 0);
1798                     final boolean suspended = parser.getAttributeBoolean(null, ATTR_SUSPENDED, false);
1799                     String oldSuspendingPackage = parser.getAttributeValue(null,
1800                             ATTR_SUSPENDING_PACKAGE);
1801                     final String dialogMessage = parser.getAttributeValue(null,
1802                             ATTR_SUSPEND_DIALOG_MESSAGE);
1803                     if (suspended && oldSuspendingPackage == null) {
1804                         oldSuspendingPackage = PLATFORM_PACKAGE_NAME;
1805                     }
1806 
1807                     final boolean blockUninstall =
1808                             parser.getAttributeBoolean(null, ATTR_BLOCK_UNINSTALL, false);
1809                     final boolean instantApp =
1810                             parser.getAttributeBoolean(null, ATTR_INSTANT_APP, false);
1811                     final boolean virtualPreload =
1812                             parser.getAttributeBoolean(null, ATTR_VIRTUAL_PRELOAD, false);
1813                     final int enabled = parser.getAttributeInt(null, ATTR_ENABLED,
1814                             COMPONENT_ENABLED_STATE_DEFAULT);
1815                     final String enabledCaller = parser.getAttributeValue(null,
1816                             ATTR_ENABLED_CALLER);
1817                     final String harmfulAppWarning =
1818                             parser.getAttributeValue(null, ATTR_HARMFUL_APP_WARNING);
1819                     final int verifState = parser.getAttributeInt(null,
1820                             ATTR_DOMAIN_VERIFICATON_STATE,
1821                             PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
1822                     final int installReason = parser.getAttributeInt(null, ATTR_INSTALL_REASON,
1823                             PackageManager.INSTALL_REASON_UNKNOWN);
1824                     final int uninstallReason = parser.getAttributeInt(null, ATTR_UNINSTALL_REASON,
1825                             PackageManager.UNINSTALL_REASON_UNKNOWN);
1826                     final String splashScreenTheme = parser.getAttributeValue(null,
1827                             ATTR_SPLASH_SCREEN_THEME);
1828                     final long firstInstallTime = parser.getAttributeLongHex(null,
1829                             ATTR_FIRST_INSTALL_TIME, 0);
1830 
1831                     ArraySet<String> enabledComponents = null;
1832                     ArraySet<String> disabledComponents = null;
1833                     PersistableBundle suspendedAppExtras = null;
1834                     PersistableBundle suspendedLauncherExtras = null;
1835                     SuspendDialogInfo oldSuspendDialogInfo = null;
1836 
1837                     int packageDepth = parser.getDepth();
1838                     ArrayMap<String, SuspendParams> suspendParamsMap = null;
1839                     while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1840                             && (type != XmlPullParser.END_TAG
1841                             || parser.getDepth() > packageDepth)) {
1842                         if (type == XmlPullParser.END_TAG
1843                                 || type == XmlPullParser.TEXT) {
1844                             continue;
1845                         }
1846                         switch (parser.getName()) {
1847                             case TAG_ENABLED_COMPONENTS:
1848                                 enabledComponents = readComponentsLPr(parser);
1849                                 break;
1850                             case TAG_DISABLED_COMPONENTS:
1851                                 disabledComponents = readComponentsLPr(parser);
1852                                 break;
1853                             case TAG_SUSPENDED_APP_EXTRAS:
1854                                 suspendedAppExtras = PersistableBundle.restoreFromXml(parser);
1855                                 break;
1856                             case TAG_SUSPENDED_LAUNCHER_EXTRAS:
1857                                 suspendedLauncherExtras = PersistableBundle.restoreFromXml(parser);
1858                                 break;
1859                             case TAG_SUSPENDED_DIALOG_INFO:
1860                                 oldSuspendDialogInfo = SuspendDialogInfo.restoreFromXml(parser);
1861                                 break;
1862                             case TAG_SUSPEND_PARAMS:
1863                                 final String suspendingPackage = parser.getAttributeValue(null,
1864                                         ATTR_SUSPENDING_PACKAGE);
1865                                 if (suspendingPackage == null) {
1866                                     Slog.wtf(TAG, "No suspendingPackage found inside tag "
1867                                             + TAG_SUSPEND_PARAMS);
1868                                     continue;
1869                                 }
1870                                 if (suspendParamsMap == null) {
1871                                     suspendParamsMap = new ArrayMap<>();
1872                                 }
1873                                 suspendParamsMap.put(suspendingPackage,
1874                                         SuspendParams.restoreFromXml(parser));
1875                                 break;
1876                             default:
1877                                 Slog.wtf(TAG, "Unknown tag " + parser.getName() + " under tag "
1878                                         + TAG_PACKAGE);
1879                         }
1880                     }
1881                     if (oldSuspendDialogInfo == null && !TextUtils.isEmpty(dialogMessage)) {
1882                         oldSuspendDialogInfo = new SuspendDialogInfo.Builder()
1883                                 .setMessage(dialogMessage)
1884                                 .build();
1885                     }
1886                     if (suspended && suspendParamsMap == null) {
1887                         final SuspendParams suspendParams = new SuspendParams(
1888                                         oldSuspendDialogInfo,
1889                                         suspendedAppExtras,
1890                                         suspendedLauncherExtras);
1891                         suspendParamsMap = new ArrayMap<>();
1892                         suspendParamsMap.put(oldSuspendingPackage, suspendParams);
1893                     }
1894 
1895                     if (blockUninstall) {
1896                         setBlockUninstallLPw(userId, name, true);
1897                     }
1898                     ps.setUserState(userId, ceDataInode, enabled, installed, stopped, notLaunched,
1899                             hidden, distractionFlags, suspendParamsMap, instantApp, virtualPreload,
1900                             enabledCaller, enabledComponents, disabledComponents, installReason,
1901                             uninstallReason, harmfulAppWarning, splashScreenTheme,
1902                             firstInstallTime != 0 ? firstInstallTime :
1903                                     origFirstInstallTimes.getOrDefault(name, 0L));
1904 
1905                     mDomainVerificationManager.setLegacyUserState(name, userId, verifState);
1906                 } else if (tagName.equals("preferred-activities")) {
1907                     readPreferredActivitiesLPw(parser, userId);
1908                 } else if (tagName.equals(TAG_PERSISTENT_PREFERRED_ACTIVITIES)) {
1909                     readPersistentPreferredActivitiesLPw(parser, userId);
1910                 } else if (tagName.equals(TAG_CROSS_PROFILE_INTENT_FILTERS)) {
1911                     readCrossProfileIntentFiltersLPw(parser, userId);
1912                 } else if (tagName.equals(TAG_DEFAULT_APPS)) {
1913                     readDefaultAppsLPw(parser, userId);
1914                 } else if (tagName.equals(TAG_BLOCK_UNINSTALL_PACKAGES)) {
1915                     readBlockUninstallPackagesLPw(parser, userId);
1916                 } else {
1917                     Slog.w(PackageManagerService.TAG, "Unknown element under <stopped-packages>: "
1918                           + parser.getName());
1919                     XmlUtils.skipCurrentTag(parser);
1920                 }
1921             }
1922 
1923             str.close();
1924         } catch (XmlPullParserException e) {
1925             mReadMessages.append("Error reading: " + e.toString());
1926             PackageManagerService.reportSettingsProblem(Log.ERROR,
1927                     "Error reading stopped packages: " + e);
1928             Slog.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages",
1929                     e);
1930 
1931         } catch (java.io.IOException e) {
1932             mReadMessages.append("Error reading: " + e.toString());
1933             PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
1934             Slog.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages",
1935                     e);
1936         }
1937     }
1938 
1939     void setBlockUninstallLPw(int userId, String packageName, boolean blockUninstall) {
1940         ArraySet<String> packages = mBlockUninstallPackages.get(userId);
1941         if (blockUninstall) {
1942             if (packages == null) {
1943                 packages = new ArraySet<String>();
1944                 mBlockUninstallPackages.put(userId, packages);
1945             }
1946             packages.add(packageName);
1947         } else if (packages != null) {
1948             packages.remove(packageName);
1949             if (packages.isEmpty()) {
1950                 mBlockUninstallPackages.remove(userId);
1951             }
1952         }
1953     }
1954 
1955     void clearBlockUninstallLPw(int userId) {
1956         mBlockUninstallPackages.remove(userId);
1957     }
1958 
1959     boolean getBlockUninstallLPr(int userId, String packageName) {
1960         ArraySet<String> packages = mBlockUninstallPackages.get(userId);
1961         if (packages == null) {
1962             return false;
1963         }
1964         return packages.contains(packageName);
1965     }
1966 
1967     private ArraySet<String> readComponentsLPr(TypedXmlPullParser parser)
1968             throws IOException, XmlPullParserException {
1969         ArraySet<String> components = null;
1970         int type;
1971         int outerDepth = parser.getDepth();
1972         String tagName;
1973         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1974                 && (type != XmlPullParser.END_TAG
1975                 || parser.getDepth() > outerDepth)) {
1976             if (type == XmlPullParser.END_TAG
1977                     || type == XmlPullParser.TEXT) {
1978                 continue;
1979             }
1980             tagName = parser.getName();
1981             if (tagName.equals(TAG_ITEM)) {
1982                 String componentName = parser.getAttributeValue(null, ATTR_NAME);
1983                 if (componentName != null) {
1984                     if (components == null) {
1985                         components = new ArraySet<String>();
1986                     }
1987                     components.add(componentName);
1988                 }
1989             }
1990         }
1991         return components;
1992     }
1993 
1994     /**
1995      * Record the state of preferred activity configuration into XML.  This is used both
1996      * for recording packages.xml internally and for supporting backup/restore of the
1997      * preferred activity configuration.
1998      */
1999     void writePreferredActivitiesLPr(TypedXmlSerializer serializer, int userId, boolean full)
2000             throws IllegalArgumentException, IllegalStateException, IOException {
2001         serializer.startTag(null, "preferred-activities");
2002         PreferredIntentResolver pir = mPreferredActivities.get(userId);
2003         if (pir != null) {
2004             for (final PreferredActivity pa : pir.filterSet()) {
2005                 serializer.startTag(null, TAG_ITEM);
2006                 pa.writeToXml(serializer, full);
2007                 serializer.endTag(null, TAG_ITEM);
2008             }
2009         }
2010         serializer.endTag(null, "preferred-activities");
2011     }
2012 
2013     void writePersistentPreferredActivitiesLPr(TypedXmlSerializer serializer, int userId)
2014             throws IllegalArgumentException, IllegalStateException, IOException {
2015         serializer.startTag(null, TAG_PERSISTENT_PREFERRED_ACTIVITIES);
2016         PersistentPreferredIntentResolver ppir = mPersistentPreferredActivities.get(userId);
2017         if (ppir != null) {
2018             for (final PersistentPreferredActivity ppa : ppir.filterSet()) {
2019                 serializer.startTag(null, TAG_ITEM);
2020                 ppa.writeToXml(serializer);
2021                 serializer.endTag(null, TAG_ITEM);
2022             }
2023         }
2024         serializer.endTag(null, TAG_PERSISTENT_PREFERRED_ACTIVITIES);
2025     }
2026 
2027     void writeCrossProfileIntentFiltersLPr(TypedXmlSerializer serializer, int userId)
2028             throws IllegalArgumentException, IllegalStateException, IOException {
2029         serializer.startTag(null, TAG_CROSS_PROFILE_INTENT_FILTERS);
2030         CrossProfileIntentResolver cpir = mCrossProfileIntentResolvers.get(userId);
2031         if (cpir != null) {
2032             for (final CrossProfileIntentFilter cpif : cpir.filterSet()) {
2033                 serializer.startTag(null, TAG_ITEM);
2034                 cpif.writeToXml(serializer);
2035                 serializer.endTag(null, TAG_ITEM);
2036             }
2037         }
2038         serializer.endTag(null, TAG_CROSS_PROFILE_INTENT_FILTERS);
2039     }
2040 
2041     void writeDefaultAppsLPr(XmlSerializer serializer, int userId)
2042             throws IllegalArgumentException, IllegalStateException, IOException {
2043         serializer.startTag(null, TAG_DEFAULT_APPS);
2044         String defaultBrowser = mDefaultBrowserApp.get(userId);
2045         if (!TextUtils.isEmpty(defaultBrowser)) {
2046             serializer.startTag(null, TAG_DEFAULT_BROWSER);
2047             serializer.attribute(null, ATTR_PACKAGE_NAME, defaultBrowser);
2048             serializer.endTag(null, TAG_DEFAULT_BROWSER);
2049         }
2050         serializer.endTag(null, TAG_DEFAULT_APPS);
2051     }
2052 
2053     void writeBlockUninstallPackagesLPr(TypedXmlSerializer serializer, int userId)
2054             throws IOException  {
2055         ArraySet<String> packages = mBlockUninstallPackages.get(userId);
2056         if (packages != null) {
2057             serializer.startTag(null, TAG_BLOCK_UNINSTALL_PACKAGES);
2058             for (int i = 0; i < packages.size(); i++) {
2059                  serializer.startTag(null, TAG_BLOCK_UNINSTALL);
2060                  serializer.attribute(null, ATTR_PACKAGE_NAME, packages.valueAt(i));
2061                  serializer.endTag(null, TAG_BLOCK_UNINSTALL);
2062             }
2063             serializer.endTag(null, TAG_BLOCK_UNINSTALL_PACKAGES);
2064         }
2065     }
2066 
2067     void writePackageRestrictionsLPr(int userId) {
2068         invalidatePackageCache();
2069 
2070         if (DEBUG_MU) {
2071             Log.i(TAG, "Writing package restrictions for user=" + userId);
2072         }
2073         final long startTime = SystemClock.uptimeMillis();
2074 
2075         // Keep the old stopped packages around until we know the new ones have
2076         // been successfully written.
2077         File userPackagesStateFile = getUserPackagesStateFile(userId);
2078         File backupFile = getUserPackagesStateBackupFile(userId);
2079         new File(userPackagesStateFile.getParent()).mkdirs();
2080         if (userPackagesStateFile.exists()) {
2081             // Presence of backup settings file indicates that we failed
2082             // to persist packages earlier. So preserve the older
2083             // backup for future reference since the current packages
2084             // might have been corrupted.
2085             if (!backupFile.exists()) {
2086                 if (!userPackagesStateFile.renameTo(backupFile)) {
2087                     Slog.wtf(PackageManagerService.TAG,
2088                             "Unable to backup user packages state file, "
2089                             + "current changes will be lost at reboot");
2090                     return;
2091                 }
2092             } else {
2093                 userPackagesStateFile.delete();
2094                 Slog.w(PackageManagerService.TAG, "Preserving older stopped packages backup");
2095             }
2096         }
2097 
2098         try {
2099             final FileOutputStream fstr = new FileOutputStream(userPackagesStateFile);
2100             final TypedXmlSerializer serializer = Xml.resolveSerializer(fstr);
2101             serializer.startDocument(null, true);
2102             serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2103 
2104             serializer.startTag(null, TAG_PACKAGE_RESTRICTIONS);
2105 
2106             if (DEBUG_MU) {
2107                 Slogf.i(TAG, "Writing %s (%d packages)", userPackagesStateFile,
2108                         mPackages.values().size());
2109             }
2110             for (final PackageSetting pkg : mPackages.values()) {
2111                 final PackageUserStateInternal ustate = pkg.readUserState(userId);
2112                 if (DEBUG_MU) {
2113                     Log.v(TAG, "  pkg=" + pkg.getPackageName()
2114                             + ", installed=" + ustate.isInstalled()
2115                             + ", state=" + ustate.getEnabledState());
2116                 }
2117 
2118                 serializer.startTag(null, TAG_PACKAGE);
2119                 serializer.attribute(null, ATTR_NAME, pkg.getPackageName());
2120                 if (ustate.getCeDataInode() != 0) {
2121                     serializer.attributeLong(null, ATTR_CE_DATA_INODE, ustate.getCeDataInode());
2122                 }
2123                 if (!ustate.isInstalled()) {
2124                     serializer.attributeBoolean(null, ATTR_INSTALLED, false);
2125                 }
2126                 if (ustate.isStopped()) {
2127                     serializer.attributeBoolean(null, ATTR_STOPPED, true);
2128                 }
2129                 if (ustate.isNotLaunched()) {
2130                     serializer.attributeBoolean(null, ATTR_NOT_LAUNCHED, true);
2131                 }
2132                 if (ustate.isHidden()) {
2133                     serializer.attributeBoolean(null, ATTR_HIDDEN, true);
2134                 }
2135                 if (ustate.getDistractionFlags() != 0) {
2136                     serializer.attributeInt(null, ATTR_DISTRACTION_FLAGS,
2137                             ustate.getDistractionFlags());
2138                 }
2139                 if (ustate.isSuspended()) {
2140                     serializer.attributeBoolean(null, ATTR_SUSPENDED, true);
2141                 }
2142                 if (ustate.isInstantApp()) {
2143                     serializer.attributeBoolean(null, ATTR_INSTANT_APP, true);
2144                 }
2145                 if (ustate.isVirtualPreload()) {
2146                     serializer.attributeBoolean(null, ATTR_VIRTUAL_PRELOAD, true);
2147                 }
2148                 if (ustate.getEnabledState() != COMPONENT_ENABLED_STATE_DEFAULT) {
2149                     serializer.attributeInt(null, ATTR_ENABLED, ustate.getEnabledState());
2150                     if (ustate.getLastDisableAppCaller() != null) {
2151                         serializer.attribute(null, ATTR_ENABLED_CALLER,
2152                                 ustate.getLastDisableAppCaller());
2153                     }
2154                 }
2155                 if (ustate.getInstallReason() != PackageManager.INSTALL_REASON_UNKNOWN) {
2156                     serializer.attributeInt(null, ATTR_INSTALL_REASON,
2157                             ustate.getInstallReason());
2158                 }
2159                 serializer.attributeLongHex(null, ATTR_FIRST_INSTALL_TIME,
2160                         ustate.getFirstInstallTime());
2161                 if (ustate.getUninstallReason() != PackageManager.UNINSTALL_REASON_UNKNOWN) {
2162                     serializer.attributeInt(null, ATTR_UNINSTALL_REASON,
2163                             ustate.getUninstallReason());
2164                 }
2165                 if (ustate.getHarmfulAppWarning() != null) {
2166                     serializer.attribute(null, ATTR_HARMFUL_APP_WARNING,
2167                             ustate.getHarmfulAppWarning());
2168                 }
2169                 if (ustate.getSplashScreenTheme() != null) {
2170                     serializer.attribute(null, ATTR_SPLASH_SCREEN_THEME,
2171                             ustate.getSplashScreenTheme());
2172                 }
2173                 if (ustate.isSuspended()) {
2174                     for (int i = 0; i < ustate.getSuspendParams().size(); i++) {
2175                         final String suspendingPackage = ustate.getSuspendParams().keyAt(i);
2176                         serializer.startTag(null, TAG_SUSPEND_PARAMS);
2177                         serializer.attribute(null, ATTR_SUSPENDING_PACKAGE, suspendingPackage);
2178                         final SuspendParams params =
2179                                 ustate.getSuspendParams().valueAt(i);
2180                         if (params != null) {
2181                             params.saveToXml(serializer);
2182                         }
2183                         serializer.endTag(null, TAG_SUSPEND_PARAMS);
2184                     }
2185                 }
2186                 final ArraySet<String> enabledComponents = ustate.getEnabledComponents();
2187                 if (enabledComponents != null && enabledComponents.size() > 0) {
2188                     serializer.startTag(null, TAG_ENABLED_COMPONENTS);
2189                     for (int i = 0; i < enabledComponents.size(); i++) {
2190                         serializer.startTag(null, TAG_ITEM);
2191                         serializer.attribute(null, ATTR_NAME,
2192                                 enabledComponents.valueAt(i));
2193                         serializer.endTag(null, TAG_ITEM);
2194                     }
2195                     serializer.endTag(null, TAG_ENABLED_COMPONENTS);
2196                 }
2197                 final ArraySet<String> disabledComponents = ustate.getDisabledComponents();
2198                 if (disabledComponents != null && disabledComponents.size() > 0) {
2199                     serializer.startTag(null, TAG_DISABLED_COMPONENTS);
2200                     for (int i = 0; i < disabledComponents.size(); i++) {
2201                         serializer.startTag(null, TAG_ITEM);
2202                         serializer.attribute(null, ATTR_NAME,
2203                                 disabledComponents.valueAt(i));
2204                         serializer.endTag(null, TAG_ITEM);
2205                     }
2206                     serializer.endTag(null, TAG_DISABLED_COMPONENTS);
2207                 }
2208 
2209                 serializer.endTag(null, TAG_PACKAGE);
2210             }
2211 
2212             writePreferredActivitiesLPr(serializer, userId, true);
2213             writePersistentPreferredActivitiesLPr(serializer, userId);
2214             writeCrossProfileIntentFiltersLPr(serializer, userId);
2215             writeDefaultAppsLPr(serializer, userId);
2216             writeBlockUninstallPackagesLPr(serializer, userId);
2217 
2218             serializer.endTag(null, TAG_PACKAGE_RESTRICTIONS);
2219 
2220             serializer.endDocument();
2221 
2222             fstr.flush();
2223             FileUtils.sync(fstr);
2224             fstr.close();
2225 
2226             // New settings successfully written, old ones are no longer
2227             // needed.
2228             backupFile.delete();
2229             FileUtils.setPermissions(userPackagesStateFile.toString(),
2230                     FileUtils.S_IRUSR|FileUtils.S_IWUSR
2231                     |FileUtils.S_IRGRP|FileUtils.S_IWGRP,
2232                     -1, -1);
2233 
2234             com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
2235                     "package-user-" + userId, SystemClock.uptimeMillis() - startTime);
2236 
2237             // Done, all is good!
2238             return;
2239         } catch(java.io.IOException e) {
2240             Slog.wtf(PackageManagerService.TAG,
2241                     "Unable to write package manager user packages state, "
2242                     + " current changes will be lost at reboot", e);
2243         }
2244 
2245         // Clean up partially written files
2246         if (userPackagesStateFile.exists()) {
2247             if (!userPackagesStateFile.delete()) {
2248                 Log.i(PackageManagerService.TAG, "Failed to clean up mangled file: "
2249                         + mStoppedPackagesFilename);
2250             }
2251         }
2252     }
2253 
2254     void readInstallPermissionsLPr(TypedXmlPullParser parser,
2255             LegacyPermissionState permissionsState, List<UserInfo> users)
2256             throws IOException, XmlPullParserException {
2257         int outerDepth = parser.getDepth();
2258         int type;
2259         while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2260                 && (type != XmlPullParser.END_TAG
2261                 || parser.getDepth() > outerDepth)) {
2262             if (type == XmlPullParser.END_TAG
2263                     || type == XmlPullParser.TEXT) {
2264                 continue;
2265             }
2266             String tagName = parser.getName();
2267             if (tagName.equals(TAG_ITEM)) {
2268                 String name = parser.getAttributeValue(null, ATTR_NAME);
2269                 final boolean granted = parser.getAttributeBoolean(null, ATTR_GRANTED, true);
2270                 final int flags = parser.getAttributeIntHex(null, ATTR_FLAGS, 0);
2271                 for (final UserInfo user : users) {
2272                     permissionsState.putPermissionState(new PermissionState(name, false, granted,
2273                             flags), user.id);
2274                 }
2275             } else {
2276                 Slog.w(PackageManagerService.TAG, "Unknown element under <permissions>: "
2277                         + parser.getName());
2278                 XmlUtils.skipCurrentTag(parser);
2279             }
2280         }
2281     }
2282 
2283     void readUsesSdkLibLPw(TypedXmlPullParser parser, PackageSetting outPs)
2284             throws IOException, XmlPullParserException {
2285         String libName = parser.getAttributeValue(null, ATTR_NAME);
2286         long libVersion = parser.getAttributeLong(null, ATTR_VERSION, -1);
2287 
2288         if (libName != null && libVersion >= 0) {
2289             outPs.setUsesSdkLibraries(ArrayUtils.appendElement(String.class,
2290                     outPs.getUsesSdkLibraries(), libName));
2291             outPs.setUsesSdkLibrariesVersionsMajor(ArrayUtils.appendLong(
2292                     outPs.getUsesSdkLibrariesVersionsMajor(), libVersion));
2293         }
2294 
2295         XmlUtils.skipCurrentTag(parser);
2296     }
2297 
2298     void readUsesStaticLibLPw(TypedXmlPullParser parser, PackageSetting outPs)
2299             throws IOException, XmlPullParserException {
2300         String libName = parser.getAttributeValue(null, ATTR_NAME);
2301         long libVersion = parser.getAttributeLong(null, ATTR_VERSION, -1);
2302 
2303         if (libName != null && libVersion >= 0) {
2304             outPs.setUsesStaticLibraries(ArrayUtils.appendElement(String.class,
2305                     outPs.getUsesStaticLibraries(), libName));
2306             outPs.setUsesStaticLibrariesVersions(ArrayUtils.appendLong(
2307                     outPs.getUsesStaticLibrariesVersions(), libVersion));
2308         }
2309 
2310         XmlUtils.skipCurrentTag(parser);
2311     }
2312 
2313     void writeUsesSdkLibLPw(TypedXmlSerializer serializer, String[] usesSdkLibraries,
2314             long[] usesSdkLibraryVersions) throws IOException {
2315         if (ArrayUtils.isEmpty(usesSdkLibraries) || ArrayUtils.isEmpty(usesSdkLibraryVersions)
2316                 || usesSdkLibraries.length != usesSdkLibraryVersions.length) {
2317             return;
2318         }
2319         final int libCount = usesSdkLibraries.length;
2320         for (int i = 0; i < libCount; i++) {
2321             final String libName = usesSdkLibraries[i];
2322             final long libVersion = usesSdkLibraryVersions[i];
2323             serializer.startTag(null, TAG_USES_SDK_LIB);
2324             serializer.attribute(null, ATTR_NAME, libName);
2325             serializer.attributeLong(null, ATTR_VERSION, libVersion);
2326             serializer.endTag(null, TAG_USES_SDK_LIB);
2327         }
2328     }
2329 
2330     void writeUsesStaticLibLPw(TypedXmlSerializer serializer, String[] usesStaticLibraries,
2331             long[] usesStaticLibraryVersions) throws IOException {
2332         if (ArrayUtils.isEmpty(usesStaticLibraries) || ArrayUtils.isEmpty(usesStaticLibraryVersions)
2333                 || usesStaticLibraries.length != usesStaticLibraryVersions.length) {
2334             return;
2335         }
2336         final int libCount = usesStaticLibraries.length;
2337         for (int i = 0; i < libCount; i++) {
2338             final String libName = usesStaticLibraries[i];
2339             final long libVersion = usesStaticLibraryVersions[i];
2340             serializer.startTag(null, TAG_USES_STATIC_LIB);
2341             serializer.attribute(null, ATTR_NAME, libName);
2342             serializer.attributeLong(null, ATTR_VERSION, libVersion);
2343             serializer.endTag(null, TAG_USES_STATIC_LIB);
2344         }
2345     }
2346 
2347     // Note: assumed "stopped" field is already cleared in all packages.
2348     // Legacy reader, used to read in the old file format after an upgrade. Not used after that.
2349     void readStoppedLPw() {
2350         FileInputStream str = null;
2351         if (mBackupStoppedPackagesFilename.exists()) {
2352             try {
2353                 str = new FileInputStream(mBackupStoppedPackagesFilename);
2354                 mReadMessages.append("Reading from backup stopped packages file\n");
2355                 PackageManagerService.reportSettingsProblem(Log.INFO,
2356                         "Need to read from backup stopped packages file");
2357                 if (mSettingsFilename.exists()) {
2358                     // If both the backup and normal file exist, we
2359                     // ignore the normal one since it might have been
2360                     // corrupted.
2361                     Slog.w(PackageManagerService.TAG, "Cleaning up stopped packages file "
2362                             + mStoppedPackagesFilename);
2363                     mStoppedPackagesFilename.delete();
2364                 }
2365             } catch (java.io.IOException e) {
2366                 // We'll try for the normal settings file.
2367             }
2368         }
2369 
2370         try {
2371             if (str == null) {
2372                 if (!mStoppedPackagesFilename.exists()) {
2373                     mReadMessages.append("No stopped packages file found\n");
2374                     PackageManagerService.reportSettingsProblem(Log.INFO,
2375                             "No stopped packages file file; assuming all started");
2376                     // At first boot, make sure no packages are stopped.
2377                     // We usually want to have third party apps initialize
2378                     // in the stopped state, but not at first boot.
2379                     for (PackageSetting pkg : mPackages.values()) {
2380                         pkg.setStopped(false, 0);
2381                         pkg.setNotLaunched(false, 0);
2382                     }
2383                     return;
2384                 }
2385                 str = new FileInputStream(mStoppedPackagesFilename);
2386             }
2387             final TypedXmlPullParser parser = Xml.resolvePullParser(str);
2388 
2389             int type;
2390             while ((type=parser.next()) != XmlPullParser.START_TAG
2391                        && type != XmlPullParser.END_DOCUMENT) {
2392                 ;
2393             }
2394 
2395             if (type != XmlPullParser.START_TAG) {
2396                 mReadMessages.append("No start tag found in stopped packages file\n");
2397                 PackageManagerService.reportSettingsProblem(Log.WARN,
2398                         "No start tag found in package manager stopped packages");
2399                 return;
2400             }
2401 
2402             int outerDepth = parser.getDepth();
2403             while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2404                    && (type != XmlPullParser.END_TAG
2405                            || parser.getDepth() > outerDepth)) {
2406                 if (type == XmlPullParser.END_TAG
2407                         || type == XmlPullParser.TEXT) {
2408                     continue;
2409                 }
2410 
2411                 String tagName = parser.getName();
2412                 if (tagName.equals(TAG_PACKAGE)) {
2413                     String name = parser.getAttributeValue(null, ATTR_NAME);
2414                     PackageSetting ps = mPackages.get(name);
2415                     if (ps != null) {
2416                         ps.setStopped(true, 0);
2417                         if ("1".equals(parser.getAttributeValue(null, ATTR_NOT_LAUNCHED))) {
2418                             ps.setNotLaunched(true, 0);
2419                         }
2420                     } else {
2421                         Slog.w(PackageManagerService.TAG,
2422                                 "No package known for stopped package " + name);
2423                     }
2424                     XmlUtils.skipCurrentTag(parser);
2425                 } else {
2426                     Slog.w(PackageManagerService.TAG, "Unknown element under <stopped-packages>: "
2427                           + parser.getName());
2428                     XmlUtils.skipCurrentTag(parser);
2429                 }
2430             }
2431 
2432             str.close();
2433 
2434         } catch (XmlPullParserException e) {
2435             mReadMessages.append("Error reading: " + e.toString());
2436             PackageManagerService.reportSettingsProblem(Log.ERROR,
2437                     "Error reading stopped packages: " + e);
2438             Slog.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages",
2439                     e);
2440 
2441         } catch (java.io.IOException e) {
2442             mReadMessages.append("Error reading: " + e.toString());
2443             PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
2444             Slog.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages",
2445                     e);
2446 
2447         }
2448     }
2449 
2450     void writeLPr(@NonNull Computer computer) {
2451         //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
2452 
2453         final long startTime = SystemClock.uptimeMillis();
2454 
2455         // Whenever package manager changes something on the system, it writes out whatever it
2456         // changed in the form of a settings object change, and it does so under its internal
2457         // lock --- so if we invalidate the package cache here, we end up invalidating at the
2458         // right time.
2459         invalidatePackageCache();
2460 
2461         // Keep the old settings around until we know the new ones have
2462         // been successfully written.
2463         if (mSettingsFilename.exists()) {
2464             // Presence of backup settings file indicates that we failed
2465             // to persist settings earlier. So preserve the older
2466             // backup for future reference since the current settings
2467             // might have been corrupted.
2468             if (!mBackupSettingsFilename.exists()) {
2469                 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
2470                     Slog.wtf(PackageManagerService.TAG,
2471                             "Unable to backup package manager settings, "
2472                             + " current changes will be lost at reboot");
2473                     return;
2474                 }
2475             } else {
2476                 mSettingsFilename.delete();
2477                 Slog.w(PackageManagerService.TAG, "Preserving older settings backup");
2478             }
2479         }
2480 
2481         mPastSignatures.clear();
2482 
2483         try {
2484             final FileOutputStream fstr = new FileOutputStream(mSettingsFilename);
2485             final TypedXmlSerializer serializer = Xml.resolveSerializer(fstr);
2486             serializer.startDocument(null, true);
2487             serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2488 
2489             serializer.startTag(null, "packages");
2490 
2491             for (int i = 0; i < mVersion.size(); i++) {
2492                 final String volumeUuid = mVersion.keyAt(i);
2493                 final VersionInfo ver = mVersion.valueAt(i);
2494 
2495                 serializer.startTag(null, TAG_VERSION);
2496                 XmlUtils.writeStringAttribute(serializer, ATTR_VOLUME_UUID, volumeUuid);
2497                 serializer.attributeInt(null, ATTR_SDK_VERSION, ver.sdkVersion);
2498                 serializer.attributeInt(null, ATTR_DATABASE_VERSION, ver.databaseVersion);
2499                 XmlUtils.writeStringAttribute(serializer, ATTR_FINGERPRINT, ver.fingerprint);
2500                 serializer.endTag(null, TAG_VERSION);
2501             }
2502 
2503             if (mVerifierDeviceIdentity != null) {
2504                 serializer.startTag(null, "verifier");
2505                 serializer.attribute(null, "device", mVerifierDeviceIdentity.toString());
2506                 serializer.endTag(null, "verifier");
2507             }
2508 
2509             serializer.startTag(null, "permission-trees");
2510             mPermissions.writePermissionTrees(serializer);
2511             serializer.endTag(null, "permission-trees");
2512 
2513             serializer.startTag(null, "permissions");
2514             mPermissions.writePermissions(serializer);
2515             serializer.endTag(null, "permissions");
2516 
2517             for (final PackageSetting pkg : mPackages.values()) {
2518                 writePackageLPr(serializer, pkg);
2519             }
2520 
2521             for (final PackageSetting pkg : mDisabledSysPackages.values()) {
2522                 writeDisabledSysPackageLPr(serializer, pkg);
2523             }
2524 
2525             for (final SharedUserSetting usr : mSharedUsers.values()) {
2526                 serializer.startTag(null, "shared-user");
2527                 serializer.attribute(null, ATTR_NAME, usr.name);
2528                 serializer.attributeInt(null, "userId", usr.mAppId);
2529                 usr.signatures.writeXml(serializer, "sigs", mPastSignatures.untrackedStorage());
2530                 serializer.endTag(null, "shared-user");
2531             }
2532 
2533             if (mRenamedPackages.size() > 0) {
2534                 for (Map.Entry<String, String> e : mRenamedPackages.entrySet()) {
2535                     serializer.startTag(null, "renamed-package");
2536                     serializer.attribute(null, "new", e.getKey());
2537                     serializer.attribute(null, "old", e.getValue());
2538                     serializer.endTag(null, "renamed-package");
2539                 }
2540             }
2541 
2542             mDomainVerificationManager.writeSettings(computer, serializer,
2543                     false /* includeSignatures */, UserHandle.USER_ALL);
2544 
2545             mKeySetManagerService.writeKeySetManagerServiceLPr(serializer);
2546 
2547             serializer.endTag(null, "packages");
2548 
2549             serializer.endDocument();
2550 
2551             fstr.flush();
2552             FileUtils.sync(fstr);
2553             fstr.close();
2554 
2555             // New settings successfully written, old ones are no longer
2556             // needed.
2557             mBackupSettingsFilename.delete();
2558             FileUtils.setPermissions(mSettingsFilename.toString(),
2559                     FileUtils.S_IRUSR|FileUtils.S_IWUSR
2560                     |FileUtils.S_IRGRP|FileUtils.S_IWGRP,
2561                     -1, -1);
2562 
2563             writeKernelMappingLPr();
2564             writePackageListLPr();
2565             writeAllUsersPackageRestrictionsLPr();
2566             writeAllRuntimePermissionsLPr();
2567             com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
2568                     "package", SystemClock.uptimeMillis() - startTime);
2569             return;
2570 
2571         } catch(java.io.IOException e) {
2572             Slog.wtf(PackageManagerService.TAG, "Unable to write package manager settings, "
2573                     + "current changes will be lost at reboot", e);
2574         }
2575         // Clean up partially written files
2576         if (mSettingsFilename.exists()) {
2577             if (!mSettingsFilename.delete()) {
2578                 Slog.wtf(PackageManagerService.TAG, "Failed to clean up mangled file: "
2579                         + mSettingsFilename);
2580             }
2581         }
2582         //Debug.stopMethodTracing();
2583     }
2584 
2585     private void writeKernelRemoveUserLPr(int userId) {
2586         if (mKernelMappingFilename == null) return;
2587 
2588         File removeUserIdFile = new File(mKernelMappingFilename, "remove_userid");
2589         if (DEBUG_KERNEL) Slog.d(TAG, "Writing " + userId + " to " + removeUserIdFile
2590                 .getAbsolutePath());
2591         writeIntToFile(removeUserIdFile, userId);
2592     }
2593 
2594     void writeKernelMappingLPr() {
2595         if (mKernelMappingFilename == null) return;
2596 
2597         final String[] known = mKernelMappingFilename.list();
2598         final ArraySet<String> knownSet = new ArraySet<>(known.length);
2599         for (String name : known) {
2600             knownSet.add(name);
2601         }
2602 
2603         for (final PackageSetting ps : mPackages.values()) {
2604             // Package is actively claimed
2605             knownSet.remove(ps.getPackageName());
2606             writeKernelMappingLPr(ps);
2607         }
2608 
2609         // Remove any unclaimed mappings
2610         for (int i = 0; i < knownSet.size(); i++) {
2611             final String name = knownSet.valueAt(i);
2612             if (DEBUG_KERNEL) Slog.d(TAG, "Dropping mapping " + name);
2613 
2614             mKernelMapping.remove(name);
2615             new File(mKernelMappingFilename, name).delete();
2616         }
2617     }
2618 
2619     void writeKernelMappingLPr(PackageSetting ps) {
2620         if (mKernelMappingFilename == null || ps == null || ps.getPackageName() == null) return;
2621 
2622         writeKernelMappingLPr(ps.getPackageName(), ps.getAppId(), ps.getNotInstalledUserIds());
2623     }
2624 
2625     void writeKernelMappingLPr(String name, int appId, int[] excludedUserIds) {
2626         KernelPackageState cur = mKernelMapping.get(name);
2627         final boolean firstTime = cur == null;
2628         final boolean userIdsChanged = firstTime
2629                 || !Arrays.equals(excludedUserIds, cur.excludedUserIds);
2630 
2631         // Package directory
2632         final File dir = new File(mKernelMappingFilename, name);
2633 
2634         if (firstTime) {
2635             dir.mkdir();
2636             // Create a new mapping state
2637             cur = new KernelPackageState();
2638             mKernelMapping.put(name, cur);
2639         }
2640 
2641         // If mapping is incorrect or non-existent, write the appid file
2642         if (cur.appId != appId) {
2643             final File appIdFile = new File(dir, "appid");
2644             writeIntToFile(appIdFile, appId);
2645             if (DEBUG_KERNEL) Slog.d(TAG, "Mapping " + name + " to " + appId);
2646         }
2647 
2648         if (userIdsChanged) {
2649             // Build the exclusion list -- the ids to add to the exclusion list
2650             for (int i = 0; i < excludedUserIds.length; i++) {
2651                 if (cur.excludedUserIds == null || !ArrayUtils.contains(cur.excludedUserIds,
2652                         excludedUserIds[i])) {
2653                     writeIntToFile(new File(dir, "excluded_userids"), excludedUserIds[i]);
2654                     if (DEBUG_KERNEL) Slog.d(TAG, "Writing " + excludedUserIds[i] + " to "
2655                             + name + "/excluded_userids");
2656                 }
2657             }
2658             // Build the inclusion list -- the ids to remove from the exclusion list
2659             if (cur.excludedUserIds != null) {
2660                 for (int i = 0; i < cur.excludedUserIds.length; i++) {
2661                     if (!ArrayUtils.contains(excludedUserIds, cur.excludedUserIds[i])) {
2662                         writeIntToFile(new File(dir, "clear_userid"),
2663                                 cur.excludedUserIds[i]);
2664                         if (DEBUG_KERNEL) Slog.d(TAG, "Writing " + cur.excludedUserIds[i] + " to "
2665                                 + name + "/clear_userid");
2666 
2667                     }
2668                 }
2669             }
2670             cur.excludedUserIds = excludedUserIds;
2671         }
2672     }
2673 
2674     private void writeIntToFile(File file, int value) {
2675         try {
2676             FileUtils.bytesToFile(file.getAbsolutePath(),
2677                     Integer.toString(value).getBytes(StandardCharsets.US_ASCII));
2678         } catch (IOException ignored) {
2679             Slog.w(TAG, "Couldn't write " + value + " to " + file.getAbsolutePath());
2680         }
2681     }
2682 
2683     void writePackageListLPr() {
2684         writePackageListLPr(-1);
2685     }
2686 
2687     void writePackageListLPr(int creatingUserId) {
2688         String filename = mPackageListFilename.getAbsolutePath();
2689         String ctx = SELinux.fileSelabelLookup(filename);
2690         if (ctx == null) {
2691             Slog.wtf(TAG, "Failed to get SELinux context for " +
2692                 mPackageListFilename.getAbsolutePath());
2693         }
2694 
2695         if (!SELinux.setFSCreateContext(ctx)) {
2696             Slog.wtf(TAG, "Failed to set packages.list SELinux context");
2697         }
2698         try {
2699             writePackageListLPrInternal(creatingUserId);
2700         } finally {
2701             SELinux.setFSCreateContext(null);
2702         }
2703     }
2704 
2705     private void writePackageListLPrInternal(int creatingUserId) {
2706         // Only derive GIDs for active users (not dying)
2707         final List<UserInfo> users = getActiveUsers(UserManagerService.getInstance(), true);
2708         int[] userIds = new int[users.size()];
2709         for (int i = 0; i < userIds.length; i++) {
2710             userIds[i] = users.get(i).id;
2711         }
2712         if (creatingUserId != -1) {
2713             userIds = ArrayUtils.appendInt(userIds, creatingUserId);
2714         }
2715 
2716         // Write package list file now, use a JournaledFile.
2717         File tempFile = new File(mPackageListFilename.getAbsolutePath() + ".tmp");
2718         JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
2719 
2720         final File writeTarget = journal.chooseForWrite();
2721         FileOutputStream fstr;
2722         BufferedWriter writer = null;
2723         try {
2724             fstr = new FileOutputStream(writeTarget);
2725             writer = new BufferedWriter(new OutputStreamWriter(fstr, Charset.defaultCharset()));
2726             FileUtils.setPermissions(fstr.getFD(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
2727 
2728             StringBuilder sb = new StringBuilder();
2729             for (final PackageSetting pkg : mPackages.values()) {
2730                 // TODO(b/135203078): This doesn't handle multiple users
2731                 final String dataPath = pkg.getPkg() == null ? null :
2732                         PackageInfoWithoutStateUtils.getDataDir(pkg.getPkg(),
2733                                 UserHandle.USER_SYSTEM).getAbsolutePath();
2734 
2735                 if (pkg.getPkg() == null || dataPath == null) {
2736                     if (!"android".equals(pkg.getPackageName())) {
2737                         Slog.w(TAG, "Skipping " + pkg + " due to missing metadata");
2738                     }
2739                     continue;
2740                 }
2741 
2742                 final boolean isDebug = pkg.getPkg().isDebuggable();
2743                 final IntArray gids = new IntArray();
2744                 for (final int userId : userIds) {
2745                     gids.addAll(mPermissionDataProvider.getGidsForUid(UserHandle.getUid(userId,
2746                             pkg.getAppId())));
2747                 }
2748 
2749                 // Avoid any application that has a space in its path.
2750                 if (dataPath.indexOf(' ') >= 0)
2751                     continue;
2752 
2753                 // we store on each line the following information for now:
2754                 //
2755                 // pkgName    - package name
2756                 // userId     - application-specific user id
2757                 // debugFlag  - 0 or 1 if the package is debuggable.
2758                 // dataPath   - path to package's data path
2759                 // seinfo     - seinfo label for the app (assigned at install time)
2760                 // gids       - supplementary gids this app launches with
2761                 // profileableFromShellFlag  - 0 or 1 if the package is profileable from shell.
2762                 // longVersionCode - integer version of the package.
2763                 // profileable - 0 or 1 if the package is profileable by the platform.
2764                 // packageInstaller - the package that installed this app, or @system, @product or
2765                 //                    @null.
2766                 //
2767                 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
2768                 //
2769                 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
2770                 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
2771                 //   system/core/libpackagelistparser
2772                 //
2773                 sb.setLength(0);
2774                 sb.append(pkg.getPkg().getPackageName());
2775                 sb.append(" ");
2776                 sb.append(pkg.getPkg().getUid());
2777                 sb.append(isDebug ? " 1 " : " 0 ");
2778                 sb.append(dataPath);
2779                 sb.append(" ");
2780                 sb.append(AndroidPackageUtils.getSeInfo(pkg.getPkg(), pkg));
2781                 sb.append(" ");
2782                 final int gidsSize = gids.size();
2783                 if (gids != null && gids.size() > 0) {
2784                     sb.append(gids.get(0));
2785                     for (int i = 1; i < gidsSize; i++) {
2786                         sb.append(",");
2787                         sb.append(gids.get(i));
2788                     }
2789                 } else {
2790                     sb.append("none");
2791                 }
2792                 sb.append(" ");
2793                 sb.append(pkg.getPkg().isProfileableByShell() ? "1" : "0");
2794                 sb.append(" ");
2795                 sb.append(pkg.getPkg().getLongVersionCode());
2796                 sb.append(" ");
2797                 sb.append(pkg.getPkg().isProfileable() ? "1" : "0");
2798                 sb.append(" ");
2799                 if (pkg.isSystem()) {
2800                     sb.append("@system");
2801                 } else if (pkg.isProduct()) {
2802                     sb.append("@product");
2803                 } else if (pkg.getInstallSource().installerPackageName != null
2804                            && !pkg.getInstallSource().installerPackageName.isEmpty()) {
2805                     sb.append(pkg.getInstallSource().installerPackageName);
2806                 } else {
2807                     sb.append("@null");
2808                 }
2809                 sb.append("\n");
2810                 writer.append(sb);
2811             }
2812             writer.flush();
2813             FileUtils.sync(fstr);
2814             writer.close();
2815             journal.commit();
2816         } catch (Exception e) {
2817             Slog.wtf(TAG, "Failed to write packages.list", e);
2818             IoUtils.closeQuietly(writer);
2819             journal.rollback();
2820         }
2821     }
2822 
2823     void writeDisabledSysPackageLPr(TypedXmlSerializer serializer, final PackageSetting pkg)
2824             throws java.io.IOException {
2825         serializer.startTag(null, "updated-package");
2826         serializer.attribute(null, ATTR_NAME, pkg.getPackageName());
2827         if (pkg.getRealName() != null) {
2828             serializer.attribute(null, "realName", pkg.getRealName());
2829         }
2830         serializer.attribute(null, "codePath", pkg.getPathString());
2831         serializer.attributeLongHex(null, "ft", pkg.getLastModifiedTime());
2832         serializer.attributeLongHex(null, "ut", pkg.getLastUpdateTime());
2833         serializer.attributeLong(null, "version", pkg.getVersionCode());
2834         if (pkg.getLegacyNativeLibraryPath() != null) {
2835             serializer.attribute(null, "nativeLibraryPath", pkg.getLegacyNativeLibraryPath());
2836         }
2837         if (pkg.getPrimaryCpuAbi() != null) {
2838            serializer.attribute(null, "primaryCpuAbi", pkg.getPrimaryCpuAbi());
2839         }
2840         if (pkg.getSecondaryCpuAbi() != null) {
2841             serializer.attribute(null, "secondaryCpuAbi", pkg.getSecondaryCpuAbi());
2842         }
2843         if (pkg.getCpuAbiOverride() != null) {
2844             serializer.attribute(null, "cpuAbiOverride", pkg.getCpuAbiOverride());
2845         }
2846 
2847         if (!pkg.hasSharedUser()) {
2848             serializer.attributeInt(null, "userId", pkg.getAppId());
2849         } else {
2850             serializer.attributeInt(null, "sharedUserId", pkg.getAppId());
2851         }
2852         serializer.attributeFloat(null, "loadingProgress", pkg.getLoadingProgress());
2853 
2854         writeUsesSdkLibLPw(serializer, pkg.getUsesSdkLibraries(),
2855                 pkg.getUsesSdkLibrariesVersionsMajor());
2856 
2857         writeUsesStaticLibLPw(serializer, pkg.getUsesStaticLibraries(),
2858                 pkg.getUsesStaticLibrariesVersions());
2859 
2860         serializer.endTag(null, "updated-package");
2861     }
2862 
2863     void writePackageLPr(TypedXmlSerializer serializer, final PackageSetting pkg)
2864             throws java.io.IOException {
2865         serializer.startTag(null, "package");
2866         serializer.attribute(null, ATTR_NAME, pkg.getPackageName());
2867         if (pkg.getRealName() != null) {
2868             serializer.attribute(null, "realName", pkg.getRealName());
2869         }
2870         serializer.attribute(null, "codePath", pkg.getPathString());
2871 
2872         if (pkg.getLegacyNativeLibraryPath() != null) {
2873             serializer.attribute(null, "nativeLibraryPath", pkg.getLegacyNativeLibraryPath());
2874         }
2875         if (pkg.getPrimaryCpuAbi() != null) {
2876             serializer.attribute(null, "primaryCpuAbi", pkg.getPrimaryCpuAbi());
2877         }
2878         if (pkg.getSecondaryCpuAbi() != null) {
2879             serializer.attribute(null, "secondaryCpuAbi", pkg.getSecondaryCpuAbi());
2880         }
2881         if (pkg.getCpuAbiOverride() != null) {
2882             serializer.attribute(null, "cpuAbiOverride", pkg.getCpuAbiOverride());
2883         }
2884 
2885         serializer.attributeInt(null, "publicFlags", pkg.getFlags());
2886         serializer.attributeInt(null, "privateFlags", pkg.getPrivateFlags());
2887         serializer.attributeLongHex(null, "ft", pkg.getLastModifiedTime());
2888         serializer.attributeLongHex(null, "ut", pkg.getLastUpdateTime());
2889         serializer.attributeLong(null, "version", pkg.getVersionCode());
2890         if (!pkg.hasSharedUser()) {
2891             serializer.attributeInt(null, "userId", pkg.getAppId());
2892         } else {
2893             serializer.attributeInt(null, "sharedUserId", pkg.getAppId());
2894         }
2895         InstallSource installSource = pkg.getInstallSource();
2896         if (installSource.installerPackageName != null) {
2897             serializer.attribute(null, "installer", installSource.installerPackageName);
2898         }
2899         if (installSource.installerAttributionTag != null) {
2900             serializer.attribute(null, "installerAttributionTag",
2901                     installSource.installerAttributionTag);
2902         }
2903         serializer.attributeInt(null, "packageSource",
2904                 installSource.packageSource);
2905         if (installSource.isOrphaned) {
2906             serializer.attributeBoolean(null, "isOrphaned", true);
2907         }
2908         if (installSource.initiatingPackageName != null) {
2909             serializer.attribute(null, "installInitiator", installSource.initiatingPackageName);
2910         }
2911         if (installSource.isInitiatingPackageUninstalled) {
2912             serializer.attributeBoolean(null, "installInitiatorUninstalled", true);
2913         }
2914         if (installSource.originatingPackageName != null) {
2915             serializer.attribute(null, "installOriginator", installSource.originatingPackageName);
2916         }
2917         if (pkg.getVolumeUuid() != null) {
2918             serializer.attribute(null, "volumeUuid", pkg.getVolumeUuid());
2919         }
2920         if (pkg.getCategoryOverride() != ApplicationInfo.CATEGORY_UNDEFINED) {
2921             serializer.attributeInt(null, "categoryHint", pkg.getCategoryOverride());
2922         }
2923         if (pkg.isUpdateAvailable()) {
2924             serializer.attributeBoolean(null, "updateAvailable", true);
2925         }
2926         if (pkg.isForceQueryableOverride()) {
2927             serializer.attributeBoolean(null, "forceQueryable", true);
2928         }
2929         if (pkg.isLoading()) {
2930             serializer.attributeBoolean(null, "isLoading", true);
2931         }
2932         serializer.attributeFloat(null, "loadingProgress", pkg.getLoadingProgress());
2933 
2934         serializer.attribute(null, "domainSetId", pkg.getDomainSetId().toString());
2935 
2936         writeUsesSdkLibLPw(serializer, pkg.getUsesSdkLibraries(),
2937                 pkg.getUsesSdkLibrariesVersionsMajor());
2938 
2939         writeUsesStaticLibLPw(serializer, pkg.getUsesStaticLibraries(),
2940                 pkg.getUsesStaticLibrariesVersions());
2941 
2942         pkg.getSignatures().writeXml(serializer, "sigs", mPastSignatures.untrackedStorage());
2943 
2944         if (installSource.initiatingPackageSignatures != null) {
2945             installSource.initiatingPackageSignatures.writeXml(
2946                     serializer, "install-initiator-sigs", mPastSignatures.untrackedStorage());
2947         }
2948 
2949         writeSigningKeySetLPr(serializer, pkg.getKeySetData());
2950         writeUpgradeKeySetsLPr(serializer, pkg.getKeySetData());
2951         writeKeySetAliasesLPr(serializer, pkg.getKeySetData());
2952         writeMimeGroupLPr(serializer, pkg.getMimeGroups());
2953 
2954         serializer.endTag(null, "package");
2955     }
2956 
2957     void writeSigningKeySetLPr(TypedXmlSerializer serializer,
2958             PackageKeySetData data) throws IOException {
2959         serializer.startTag(null, "proper-signing-keyset");
2960         serializer.attributeLong(null, "identifier", data.getProperSigningKeySet());
2961         serializer.endTag(null, "proper-signing-keyset");
2962     }
2963 
2964     void writeUpgradeKeySetsLPr(TypedXmlSerializer serializer,
2965             PackageKeySetData data) throws IOException {
2966         if (data.isUsingUpgradeKeySets()) {
2967             for (long id : data.getUpgradeKeySets()) {
2968                 serializer.startTag(null, "upgrade-keyset");
2969                 serializer.attributeLong(null, "identifier", id);
2970                 serializer.endTag(null, "upgrade-keyset");
2971             }
2972         }
2973     }
2974 
2975     void writeKeySetAliasesLPr(TypedXmlSerializer serializer,
2976             PackageKeySetData data) throws IOException {
2977         for (Map.Entry<String, Long> e: data.getAliases().entrySet()) {
2978             serializer.startTag(null, "defined-keyset");
2979             serializer.attribute(null, "alias", e.getKey());
2980             serializer.attributeLong(null, "identifier", e.getValue());
2981             serializer.endTag(null, "defined-keyset");
2982         }
2983     }
2984 
2985     boolean readLPw(@NonNull Computer computer, @NonNull List<UserInfo> users) {
2986         FileInputStream str = null;
2987         if (mBackupSettingsFilename.exists()) {
2988             try {
2989                 str = new FileInputStream(mBackupSettingsFilename);
2990                 mReadMessages.append("Reading from backup settings file\n");
2991                 PackageManagerService.reportSettingsProblem(Log.INFO,
2992                         "Need to read from backup settings file");
2993                 if (mSettingsFilename.exists()) {
2994                     // If both the backup and settings file exist, we
2995                     // ignore the settings since it might have been
2996                     // corrupted.
2997                     Slog.w(PackageManagerService.TAG, "Cleaning up settings file "
2998                             + mSettingsFilename);
2999                     mSettingsFilename.delete();
3000                 }
3001             } catch (java.io.IOException e) {
3002                 // We'll try for the normal settings file.
3003             }
3004         }
3005 
3006         mPendingPackages.clear();
3007         mPastSignatures.clear();
3008         mKeySetRefs.clear();
3009         mInstallerPackages.clear();
3010 
3011         // If any user state doesn't have a first install time, e.g., after an OTA,
3012         // use the pre OTA firstInstallTime timestamp. This is because we migrated from per package
3013         // firstInstallTime to per user-state. Without this, OTA can cause this info to be lost.
3014         final ArrayMap<String, Long> originalFirstInstallTimes = new ArrayMap<>();
3015 
3016         try {
3017             if (str == null) {
3018                 if (!mSettingsFilename.exists()) {
3019                     mReadMessages.append("No settings file found\n");
3020                     PackageManagerService.reportSettingsProblem(Log.INFO,
3021                             "No settings file; creating initial state");
3022                     // It's enough to just touch version details to create them
3023                     // with default values
3024                     findOrCreateVersion(StorageManager.UUID_PRIVATE_INTERNAL).forceCurrent();
3025                     findOrCreateVersion(StorageManager.UUID_PRIMARY_PHYSICAL).forceCurrent();
3026                     return false;
3027                 }
3028                 str = new FileInputStream(mSettingsFilename);
3029             }
3030             final TypedXmlPullParser parser = Xml.resolvePullParser(str);
3031 
3032             int type;
3033             while ((type = parser.next()) != XmlPullParser.START_TAG
3034                     && type != XmlPullParser.END_DOCUMENT) {
3035                 ;
3036             }
3037 
3038             if (type != XmlPullParser.START_TAG) {
3039                 mReadMessages.append("No start tag found in settings file\n");
3040                 PackageManagerService.reportSettingsProblem(Log.WARN,
3041                         "No start tag found in package manager settings");
3042                 Slog.wtf(PackageManagerService.TAG,
3043                         "No start tag found in package manager settings");
3044                 return false;
3045             }
3046 
3047             int outerDepth = parser.getDepth();
3048             while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3049                     && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3050                 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3051                     continue;
3052                 }
3053 
3054                 String tagName = parser.getName();
3055                 if (tagName.equals("package")) {
3056                     readPackageLPw(parser, users, originalFirstInstallTimes);
3057                 } else if (tagName.equals("permissions")) {
3058                     mPermissions.readPermissions(parser);
3059                 } else if (tagName.equals("permission-trees")) {
3060                     mPermissions.readPermissionTrees(parser);
3061                 } else if (tagName.equals("shared-user")) {
3062                     readSharedUserLPw(parser, users);
3063                 } else if (tagName.equals("preferred-packages")) {
3064                     // no longer used.
3065                 } else if (tagName.equals("preferred-activities")) {
3066                     // Upgrading from old single-user implementation;
3067                     // these are the preferred activities for user 0.
3068                     readPreferredActivitiesLPw(parser, 0);
3069                 } else if (tagName.equals(TAG_PERSISTENT_PREFERRED_ACTIVITIES)) {
3070                     // TODO: check whether this is okay! as it is very
3071                     // similar to how preferred-activities are treated
3072                     readPersistentPreferredActivitiesLPw(parser, 0);
3073                 } else if (tagName.equals(TAG_CROSS_PROFILE_INTENT_FILTERS)) {
3074                     // TODO: check whether this is okay! as it is very
3075                     // similar to how preferred-activities are treated
3076                     readCrossProfileIntentFiltersLPw(parser, 0);
3077                 } else if (tagName.equals(TAG_DEFAULT_BROWSER)) {
3078                     readDefaultAppsLPw(parser, 0);
3079                 } else if (tagName.equals("updated-package")) {
3080                     readDisabledSysPackageLPw(parser, users);
3081                 } else if (tagName.equals("renamed-package")) {
3082                     String nname = parser.getAttributeValue(null, "new");
3083                     String oname = parser.getAttributeValue(null, "old");
3084                     if (nname != null && oname != null) {
3085                         mRenamedPackages.put(nname, oname);
3086                     }
3087                 } else if (tagName.equals("last-platform-version")) {
3088                     // Upgrade from older XML schema
3089                     final VersionInfo internal = findOrCreateVersion(
3090                             StorageManager.UUID_PRIVATE_INTERNAL);
3091                     final VersionInfo external = findOrCreateVersion(
3092                             StorageManager.UUID_PRIMARY_PHYSICAL);
3093 
3094                     internal.sdkVersion = parser.getAttributeInt(null, "internal", 0);
3095                     external.sdkVersion = parser.getAttributeInt(null, "external", 0);
3096                     internal.fingerprint = external.fingerprint =
3097                             XmlUtils.readStringAttribute(parser, "fingerprint");
3098 
3099                 } else if (tagName.equals("database-version")) {
3100                     // Upgrade from older XML schema
3101                     final VersionInfo internal = findOrCreateVersion(
3102                             StorageManager.UUID_PRIVATE_INTERNAL);
3103                     final VersionInfo external = findOrCreateVersion(
3104                             StorageManager.UUID_PRIMARY_PHYSICAL);
3105 
3106                     internal.databaseVersion = parser.getAttributeInt(null, "internal", 0);
3107                     external.databaseVersion = parser.getAttributeInt(null, "external", 0);
3108 
3109                 } else if (tagName.equals("verifier")) {
3110                     final String deviceIdentity = parser.getAttributeValue(null, "device");
3111                     try {
3112                         mVerifierDeviceIdentity = VerifierDeviceIdentity.parse(deviceIdentity);
3113                     } catch (IllegalArgumentException e) {
3114                         Slog.w(PackageManagerService.TAG, "Discard invalid verifier device id: "
3115                                 + e.getMessage());
3116                     }
3117                 } else if (TAG_READ_EXTERNAL_STORAGE.equals(tagName)) {
3118                     // No longer used.
3119                 } else if (tagName.equals("keyset-settings")) {
3120                     mKeySetManagerService.readKeySetsLPw(parser, mKeySetRefs.untrackedStorage());
3121                 } else if (TAG_VERSION.equals(tagName)) {
3122                     final String volumeUuid = XmlUtils.readStringAttribute(parser,
3123                             ATTR_VOLUME_UUID);
3124                     final VersionInfo ver = findOrCreateVersion(volumeUuid);
3125                     ver.sdkVersion = parser.getAttributeInt(null, ATTR_SDK_VERSION);
3126                     ver.databaseVersion = parser.getAttributeInt(null, ATTR_DATABASE_VERSION);
3127                     ver.fingerprint = XmlUtils.readStringAttribute(parser, ATTR_FINGERPRINT);
3128                 } else if (tagName.equals(DomainVerificationPersistence.TAG_DOMAIN_VERIFICATIONS)) {
3129                     mDomainVerificationManager.readSettings(computer, parser);
3130                 } else if (tagName.equals(
3131                         DomainVerificationLegacySettings.TAG_DOMAIN_VERIFICATIONS_LEGACY)) {
3132                     mDomainVerificationManager.readLegacySettings(parser);
3133                 } else {
3134                     Slog.w(PackageManagerService.TAG, "Unknown element under <packages>: "
3135                             + parser.getName());
3136                     XmlUtils.skipCurrentTag(parser);
3137                 }
3138             }
3139 
3140             str.close();
3141         } catch (IOException | XmlPullParserException e) {
3142             mReadMessages.append("Error reading: " + e.toString());
3143             PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
3144             Slog.wtf(PackageManagerService.TAG, "Error reading package manager settings", e);
3145         } finally {
3146             if (!mVersion.containsKey(StorageManager.UUID_PRIVATE_INTERNAL)) {
3147                 Slog.wtf(PackageManagerService.TAG,
3148                         "No internal VersionInfo found in settings, using current.");
3149                 findOrCreateVersion(StorageManager.UUID_PRIVATE_INTERNAL).forceCurrent();
3150             }
3151             if (!mVersion.containsKey(StorageManager.UUID_PRIMARY_PHYSICAL)) {
3152                 Slog.wtf(PackageManagerService.TAG,
3153                         "No external VersionInfo found in settings, using current.");
3154                 findOrCreateVersion(StorageManager.UUID_PRIMARY_PHYSICAL).forceCurrent();
3155             }
3156         }
3157 
3158         final int N = mPendingPackages.size();
3159 
3160         for (int i = 0; i < N; i++) {
3161             final PackageSetting p = mPendingPackages.get(i);
3162             final int sharedUserAppId = p.getSharedUserAppId();
3163             if (sharedUserAppId <= 0) {
3164                 continue;
3165             }
3166             final Object idObj = getSettingLPr(sharedUserAppId);
3167             if (idObj instanceof SharedUserSetting) {
3168                 final SharedUserSetting sharedUser = (SharedUserSetting) idObj;
3169                 addPackageSettingLPw(p, sharedUser);
3170             } else if (idObj != null) {
3171                 String msg = "Bad package setting: package " + p.getPackageName()
3172                         + " has shared uid " + sharedUserAppId + " that is not a shared uid\n";
3173                 mReadMessages.append(msg);
3174                 PackageManagerService.reportSettingsProblem(Log.ERROR, msg);
3175             } else {
3176                 String msg = "Bad package setting: package " + p.getPackageName()
3177                         + " has shared uid " + sharedUserAppId + " that is not defined\n";
3178                 mReadMessages.append(msg);
3179                 PackageManagerService.reportSettingsProblem(Log.ERROR, msg);
3180             }
3181         }
3182         mPendingPackages.clear();
3183 
3184         if (mBackupStoppedPackagesFilename.exists()
3185                 || mStoppedPackagesFilename.exists()) {
3186             // Read old file
3187             readStoppedLPw();
3188             mBackupStoppedPackagesFilename.delete();
3189             mStoppedPackagesFilename.delete();
3190             // Migrate to new file format
3191             writePackageRestrictionsLPr(UserHandle.USER_SYSTEM);
3192         } else {
3193             for (UserInfo user : users) {
3194                 readPackageRestrictionsLPr(user.id, originalFirstInstallTimes);
3195             }
3196         }
3197 
3198         for (UserInfo user : users) {
3199             mRuntimePermissionsPersistence.readStateForUserSync(user.id, getInternalVersion(),
3200                     mPackages, mSharedUsers, getUserRuntimePermissionsFile(user.id));
3201         }
3202 
3203         /*
3204          * Make sure all the updated system packages have their shared users
3205          * associated with them.
3206          */
3207         for (PackageSetting disabledPs : mDisabledSysPackages.values()) {
3208             final Object id = getSettingLPr(disabledPs.getAppId());
3209             if (id instanceof SharedUserSetting) {
3210                 SharedUserSetting sharedUserSetting = (SharedUserSetting) id;
3211                 sharedUserSetting.mDisabledPackages.add(disabledPs);
3212                 disabledPs.setSharedUserAppId(sharedUserSetting.mAppId);
3213             }
3214         }
3215 
3216         mReadMessages.append("Read completed successfully: ").append(mPackages.size())
3217                 .append(" packages, ").append(mSharedUsers.size()).append(" shared uids\n");
3218 
3219         writeKernelMappingLPr();
3220 
3221         return true;
3222     }
3223 
3224     void readPermissionStateForUserSyncLPr(@UserIdInt int userId) {
3225         mRuntimePermissionsPersistence.readStateForUserSync(userId, getInternalVersion(),
3226                 mPackages, mSharedUsers, getUserRuntimePermissionsFile(userId));
3227     }
3228 
3229     void applyDefaultPreferredAppsLPw(int userId) {
3230         // First pull data from any pre-installed apps.
3231         final PackageManagerInternal pmInternal =
3232                 LocalServices.getService(PackageManagerInternal.class);
3233         for (PackageSetting ps : mPackages.values()) {
3234             if ((ps.getFlags() & ApplicationInfo.FLAG_SYSTEM) != 0 && ps.getPkg() != null
3235                     && !ps.getPkg().getPreferredActivityFilters().isEmpty()) {
3236                 List<Pair<String, ParsedIntentInfo>> intents
3237                         = ps.getPkg().getPreferredActivityFilters();
3238                 for (int i=0; i<intents.size(); i++) {
3239                     Pair<String, ParsedIntentInfo> pair = intents.get(i);
3240                     applyDefaultPreferredActivityLPw(pmInternal,
3241                             pair.second.getIntentFilter(),
3242                             new ComponentName(ps.getPackageName(), pair.first), userId);
3243                 }
3244             }
3245         }
3246 
3247         // Read preferred apps from .../etc/preferred-apps directories.
3248         int size = PackageManagerService.SYSTEM_PARTITIONS.size();
3249         for (int index = 0; index < size; index++) {
3250             ScanPartition partition = PackageManagerService.SYSTEM_PARTITIONS.get(index);
3251 
3252             File preferredDir = new File(partition.getFolder(), "etc/preferred-apps");
3253             if (!preferredDir.exists() || !preferredDir.isDirectory()) {
3254                 continue;
3255             }
3256 
3257             if (!preferredDir.canRead()) {
3258                 Slog.w(TAG, "Directory " + preferredDir + " cannot be read");
3259                 continue;
3260             }
3261 
3262             // Iterate over the files in the directory and scan .xml files
3263             File[] files = preferredDir.listFiles();
3264             if (ArrayUtils.isEmpty(files)) {
3265                 continue;
3266             }
3267 
3268             for (File f : files) {
3269                 if (!f.getPath().endsWith(".xml")) {
3270                     Slog.i(TAG, "Non-xml file " + f + " in " + preferredDir
3271                             + " directory, ignoring");
3272                     continue;
3273                 }
3274                 if (!f.canRead()) {
3275                     Slog.w(TAG, "Preferred apps file " + f + " cannot be read");
3276                     continue;
3277                 }
3278                 if (PackageManagerService.DEBUG_PREFERRED) {
3279                     Log.d(TAG, "Reading default preferred " + f);
3280                 }
3281 
3282                 try (InputStream str = new FileInputStream(f)) {
3283                     final TypedXmlPullParser parser = Xml.resolvePullParser(str);
3284 
3285                     int type;
3286                     while ((type = parser.next()) != XmlPullParser.START_TAG
3287                             && type != XmlPullParser.END_DOCUMENT) {
3288                         ;
3289                     }
3290 
3291                     if (type != XmlPullParser.START_TAG) {
3292                         Slog.w(TAG, "Preferred apps file " + f + " does not have start tag");
3293                         continue;
3294                     }
3295                     if (!"preferred-activities".equals(parser.getName())) {
3296                         Slog.w(TAG, "Preferred apps file " + f
3297                                 + " does not start with 'preferred-activities'");
3298                         continue;
3299                     }
3300                     readDefaultPreferredActivitiesLPw(parser, userId);
3301                 } catch (XmlPullParserException e) {
3302                     Slog.w(TAG, "Error reading apps file " + f, e);
3303                 } catch (IOException e) {
3304                     Slog.w(TAG, "Error reading apps file " + f, e);
3305                 }
3306             }
3307         }
3308     }
3309 
3310     static void removeFilters(@NonNull PreferredIntentResolver pir,
3311             @NonNull WatchedIntentFilter filter, @NonNull List<PreferredActivity> existing) {
3312         if (PackageManagerService.DEBUG_PREFERRED) {
3313             Slog.i(TAG, existing.size() + " preferred matches for:");
3314             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
3315         }
3316         for (int i = existing.size() - 1; i >= 0; --i) {
3317             final PreferredActivity pa = existing.get(i);
3318             if (PackageManagerService.DEBUG_PREFERRED) {
3319                 Slog.i(TAG, "Removing preferred activity " + pa.mPref.mComponent + ":");
3320                 pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
3321             }
3322             pir.removeFilter(pa);
3323         }
3324     }
3325 
3326     private void applyDefaultPreferredActivityLPw(PackageManagerInternal pmInternal,
3327             IntentFilter tmpPa, ComponentName cn, int userId) {
3328         // The initial preferences only specify the target activity
3329         // component and intent-filter, not the set of matches.  So we
3330         // now need to query for the matches to build the correct
3331         // preferred activity entry.
3332         if (PackageManagerService.DEBUG_PREFERRED) {
3333             Log.d(TAG, "Processing preferred:");
3334             tmpPa.dump(new LogPrinter(Log.DEBUG, TAG), "  ");
3335         }
3336         Intent intent = new Intent();
3337         int flags = PackageManager.MATCH_DIRECT_BOOT_AWARE
3338                 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
3339         intent.setAction(tmpPa.getAction(0));
3340         for (int i=0; i<tmpPa.countCategories(); i++) {
3341             String cat = tmpPa.getCategory(i);
3342             if (cat.equals(Intent.CATEGORY_DEFAULT)) {
3343                 flags |= MATCH_DEFAULT_ONLY;
3344             } else {
3345                 intent.addCategory(cat);
3346             }
3347         }
3348 
3349         boolean doNonData = true;
3350         boolean hasSchemes = false;
3351 
3352         final int dataSchemesCount = tmpPa.countDataSchemes();
3353         for (int ischeme = 0; ischeme < dataSchemesCount; ischeme++) {
3354             boolean doScheme = true;
3355             final String scheme = tmpPa.getDataScheme(ischeme);
3356             if (scheme != null && !scheme.isEmpty()) {
3357                 hasSchemes = true;
3358             }
3359             final int dataSchemeSpecificPartsCount = tmpPa.countDataSchemeSpecificParts();
3360             for (int issp = 0; issp < dataSchemeSpecificPartsCount; issp++) {
3361                 Uri.Builder builder = new Uri.Builder();
3362                 builder.scheme(scheme);
3363                 PatternMatcher ssp = tmpPa.getDataSchemeSpecificPart(issp);
3364                 builder.opaquePart(ssp.getPath());
3365                 Intent finalIntent = new Intent(intent);
3366                 finalIntent.setData(builder.build());
3367                 applyDefaultPreferredActivityLPw(pmInternal, finalIntent, flags, cn,
3368                         scheme, ssp, null, null, userId);
3369                 doScheme = false;
3370             }
3371             final int dataAuthoritiesCount = tmpPa.countDataAuthorities();
3372             for (int iauth = 0; iauth < dataAuthoritiesCount; iauth++) {
3373                 boolean doAuth = true;
3374                 final IntentFilter.AuthorityEntry auth = tmpPa.getDataAuthority(iauth);
3375                 final int dataPathsCount = tmpPa.countDataPaths();
3376                 for (int ipath = 0; ipath < dataPathsCount; ipath++) {
3377                     Uri.Builder builder = new Uri.Builder();
3378                     builder.scheme(scheme);
3379                     if (auth.getHost() != null) {
3380                         builder.authority(auth.getHost());
3381                     }
3382                     PatternMatcher path = tmpPa.getDataPath(ipath);
3383                     builder.path(path.getPath());
3384                     Intent finalIntent = new Intent(intent);
3385                     finalIntent.setData(builder.build());
3386                     applyDefaultPreferredActivityLPw(pmInternal, finalIntent, flags, cn,
3387                             scheme, null, auth, path, userId);
3388                     doAuth = doScheme = false;
3389                 }
3390                 if (doAuth) {
3391                     Uri.Builder builder = new Uri.Builder();
3392                     builder.scheme(scheme);
3393                     if (auth.getHost() != null) {
3394                         builder.authority(auth.getHost());
3395                     }
3396                     Intent finalIntent = new Intent(intent);
3397                     finalIntent.setData(builder.build());
3398                     applyDefaultPreferredActivityLPw(pmInternal, finalIntent, flags, cn,
3399                             scheme, null, auth, null, userId);
3400                     doScheme = false;
3401                 }
3402             }
3403             if (doScheme) {
3404                 Uri.Builder builder = new Uri.Builder();
3405                 builder.scheme(scheme);
3406                 Intent finalIntent = new Intent(intent);
3407                 finalIntent.setData(builder.build());
3408                 applyDefaultPreferredActivityLPw(pmInternal, finalIntent, flags, cn,
3409                         scheme, null, null, null, userId);
3410             }
3411             doNonData = false;
3412         }
3413 
3414         for (int idata=0; idata<tmpPa.countDataTypes(); idata++) {
3415             String mimeType = tmpPa.getDataType(idata);
3416             if (hasSchemes) {
3417                 Uri.Builder builder = new Uri.Builder();
3418                 for (int ischeme=0; ischeme<tmpPa.countDataSchemes(); ischeme++) {
3419                     String scheme = tmpPa.getDataScheme(ischeme);
3420                     if (scheme != null && !scheme.isEmpty()) {
3421                         Intent finalIntent = new Intent(intent);
3422                         builder.scheme(scheme);
3423                         finalIntent.setDataAndType(builder.build(), mimeType);
3424                         applyDefaultPreferredActivityLPw(pmInternal, finalIntent, flags, cn,
3425                                 scheme, null, null, null, userId);
3426                     }
3427                 }
3428             } else {
3429                 Intent finalIntent = new Intent(intent);
3430                 finalIntent.setType(mimeType);
3431                 applyDefaultPreferredActivityLPw(pmInternal, finalIntent, flags, cn,
3432                         null, null, null, null, userId);
3433             }
3434             doNonData = false;
3435         }
3436 
3437         if (doNonData) {
3438             applyDefaultPreferredActivityLPw(pmInternal, intent, flags, cn,
3439                     null, null, null, null, userId);
3440         }
3441     }
3442 
3443     private void applyDefaultPreferredActivityLPw(PackageManagerInternal pmInternal, Intent intent,
3444             int flags, ComponentName cn, String scheme, PatternMatcher ssp,
3445             IntentFilter.AuthorityEntry auth, PatternMatcher path, int userId) {
3446         final List<ResolveInfo> ri =
3447                 pmInternal.queryIntentActivities(
3448                         intent, intent.getType(), flags, Binder.getCallingUid(), userId);
3449         if (PackageManagerService.DEBUG_PREFERRED) {
3450             Log.d(TAG, "Queried " + intent + " results: " + ri);
3451         }
3452         int systemMatch = 0;
3453         int thirdPartyMatch = 0;
3454         final int numMatches = (ri == null ? 0 : ri.size());
3455         if (numMatches < 1) {
3456             Slog.w(TAG, "No potential matches found for " + intent
3457                     + " while setting preferred " + cn.flattenToShortString());
3458             return;
3459         }
3460         boolean haveAct = false;
3461         ComponentName haveNonSys = null;
3462         ComponentName[] set = new ComponentName[ri.size()];
3463         for (int i = 0; i < numMatches; i++) {
3464             final ActivityInfo ai = ri.get(i).activityInfo;
3465             set[i] = new ComponentName(ai.packageName, ai.name);
3466             if ((ai.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
3467                 if (ri.get(i).match >= thirdPartyMatch) {
3468                     // Keep track of the best match we find of all third
3469                     // party apps, for use later to determine if we actually
3470                     // want to set a preferred app for this intent.
3471                     if (PackageManagerService.DEBUG_PREFERRED) {
3472                         Log.d(TAG, "Result " + ai.packageName + "/" + ai.name + ": non-system!");
3473                     }
3474                     haveNonSys = set[i];
3475                     break;
3476                 }
3477             } else if (cn.getPackageName().equals(ai.packageName)
3478                     && cn.getClassName().equals(ai.name)) {
3479                 if (PackageManagerService.DEBUG_PREFERRED) {
3480                     Log.d(TAG, "Result " + ai.packageName + "/" + ai.name + ": default!");
3481                 }
3482                 haveAct = true;
3483                 systemMatch = ri.get(i).match;
3484             } else {
3485                 if (PackageManagerService.DEBUG_PREFERRED) {
3486                     Log.d(TAG, "Result " + ai.packageName + "/" + ai.name + ": skipped");
3487                 }
3488             }
3489         }
3490         if (haveNonSys != null && thirdPartyMatch < systemMatch) {
3491             // If we have a matching third party app, but its match is not as
3492             // good as the built-in system app, then we don't want to actually
3493             // consider it a match because presumably the built-in app is still
3494             // the thing we want users to see by default.
3495             haveNonSys = null;
3496         }
3497         if (haveAct && haveNonSys == null) {
3498             WatchedIntentFilter filter = new WatchedIntentFilter();
3499             if (intent.getAction() != null) {
3500                 filter.addAction(intent.getAction());
3501             }
3502             if (intent.getCategories() != null) {
3503                 for (String cat : intent.getCategories()) {
3504                     filter.addCategory(cat);
3505                 }
3506             }
3507             if ((flags & MATCH_DEFAULT_ONLY) != 0) {
3508                 filter.addCategory(Intent.CATEGORY_DEFAULT);
3509             }
3510             if (scheme != null) {
3511                 filter.addDataScheme(scheme);
3512             }
3513             if (ssp != null) {
3514                 filter.addDataSchemeSpecificPart(ssp.getPath(), ssp.getType());
3515             }
3516             if (auth != null) {
3517                 filter.addDataAuthority(auth);
3518             }
3519             if (path != null) {
3520                 filter.addDataPath(path);
3521             }
3522             if (intent.getType() != null) {
3523                 try {
3524                     filter.addDataType(intent.getType());
3525                 } catch (IntentFilter.MalformedMimeTypeException ex) {
3526                     Slog.w(TAG, "Malformed mimetype " + intent.getType() + " for " + cn);
3527                 }
3528             }
3529             final PreferredIntentResolver pir = editPreferredActivitiesLPw(userId);
3530             final List<PreferredActivity> existing = pir.findFilters(filter);
3531             if (existing != null) {
3532                 removeFilters(pir, filter, existing);
3533             }
3534             PreferredActivity pa = new PreferredActivity(filter, systemMatch, set, cn, true);
3535             pir.addFilter(null, pa);
3536         } else if (haveNonSys == null) {
3537             StringBuilder sb = new StringBuilder();
3538             sb.append("No component ");
3539             sb.append(cn.flattenToShortString());
3540             sb.append(" found setting preferred ");
3541             sb.append(intent);
3542             sb.append("; possible matches are ");
3543             for (int i = 0; i < set.length; i++) {
3544                 if (i > 0) sb.append(", ");
3545                 sb.append(set[i].flattenToShortString());
3546             }
3547             Slog.w(TAG, sb.toString());
3548         } else {
3549             Slog.i(TAG, "Not setting preferred " + intent + "; found third party match "
3550                     + haveNonSys.flattenToShortString());
3551         }
3552     }
3553 
3554     private void readDefaultPreferredActivitiesLPw(TypedXmlPullParser parser, int userId)
3555             throws XmlPullParserException, IOException {
3556         final PackageManagerInternal pmInternal =
3557                 LocalServices.getService(PackageManagerInternal.class);
3558         int outerDepth = parser.getDepth();
3559         int type;
3560         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3561                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3562             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3563                 continue;
3564             }
3565 
3566             String tagName = parser.getName();
3567             if (tagName.equals(TAG_ITEM)) {
3568                 PreferredActivity tmpPa = new PreferredActivity(parser);
3569                 if (tmpPa.mPref.getParseError() == null) {
3570                     applyDefaultPreferredActivityLPw(
3571                             pmInternal, tmpPa.getIntentFilter(), tmpPa.mPref.mComponent, userId);
3572                 } else {
3573                     PackageManagerService.reportSettingsProblem(Log.WARN,
3574                             "Error in package manager settings: <preferred-activity> "
3575                                     + tmpPa.mPref.getParseError() + " at "
3576                                     + parser.getPositionDescription());
3577                 }
3578             } else {
3579                 PackageManagerService.reportSettingsProblem(Log.WARN,
3580                         "Unknown element under <preferred-activities>: " + parser.getName());
3581                 XmlUtils.skipCurrentTag(parser);
3582             }
3583         }
3584     }
3585 
3586     private void readDisabledSysPackageLPw(TypedXmlPullParser parser, List<UserInfo> users)
3587             throws XmlPullParserException, IOException {
3588         String name = parser.getAttributeValue(null, ATTR_NAME);
3589         String realName = parser.getAttributeValue(null, "realName");
3590         String codePathStr = parser.getAttributeValue(null, "codePath");
3591 
3592         String legacyCpuAbiStr = parser.getAttributeValue(null, "requiredCpuAbi");
3593         String legacyNativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
3594 
3595         String primaryCpuAbiStr = parser.getAttributeValue(null, "primaryCpuAbi");
3596         String secondaryCpuAbiStr = parser.getAttributeValue(null, "secondaryCpuAbi");
3597         String cpuAbiOverrideStr = parser.getAttributeValue(null, "cpuAbiOverride");
3598 
3599         if (primaryCpuAbiStr == null && legacyCpuAbiStr != null) {
3600             primaryCpuAbiStr = legacyCpuAbiStr;
3601         }
3602 
3603         long versionCode = parser.getAttributeLong(null, "version", 0);
3604 
3605         int pkgFlags = 0;
3606         int pkgPrivateFlags = 0;
3607         pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
3608         if (codePathStr.contains("/priv-app/")) {
3609             pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
3610         }
3611 
3612         // When reading a disabled setting, use a disabled domainSetId, which makes it easier to
3613         // debug invalid entries. The actual logic for migrating to a new ID is done in other
3614         // methods that use DomainVerificationManagerInternal#generateNewId
3615         UUID domainSetId = DomainVerificationManagerInternal.DISABLED_ID;
3616         PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
3617                 legacyNativeLibraryPathStr, primaryCpuAbiStr, secondaryCpuAbiStr, cpuAbiOverrideStr,
3618                 versionCode, pkgFlags, pkgPrivateFlags, 0 /*sharedUserId*/, null, null, null, null,
3619                 null, domainSetId);
3620         long timeStamp = parser.getAttributeLongHex(null, "ft", 0);
3621         if (timeStamp == 0) {
3622             timeStamp = parser.getAttributeLong(null, "ts", 0);
3623         }
3624         ps.setLastModifiedTime(timeStamp);
3625         ps.setLastUpdateTime(parser.getAttributeLongHex(null, "ut", 0));
3626         ps.setAppId(parser.getAttributeInt(null, "userId", 0));
3627         if (ps.getAppId() <= 0) {
3628             final int sharedUserAppId = parser.getAttributeInt(null, "sharedUserId", 0);
3629             ps.setAppId(sharedUserAppId);
3630             ps.setSharedUserAppId(sharedUserAppId);
3631         }
3632         final float loadingProgress =
3633                 parser.getAttributeFloat(null, "loadingProgress", 0);
3634         ps.setLoadingProgress(loadingProgress);
3635 
3636         int outerDepth = parser.getDepth();
3637         int type;
3638         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3639                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3640             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3641                 continue;
3642             }
3643 
3644             if (parser.getName().equals(TAG_PERMISSIONS)) {
3645                 final LegacyPermissionState legacyState;
3646                 if (ps.hasSharedUser()) {
3647                     legacyState = getSettingLPr(ps.getSharedUserAppId()).getLegacyPermissionState();
3648                 } else {
3649                     legacyState = ps.getLegacyPermissionState();
3650                 }
3651                 readInstallPermissionsLPr(parser, legacyState, users);
3652             } else if (parser.getName().equals(TAG_USES_STATIC_LIB)) {
3653                 readUsesStaticLibLPw(parser, ps);
3654             } else if (parser.getName().equals(TAG_USES_SDK_LIB)) {
3655                 readUsesSdkLibLPw(parser, ps);
3656             } else {
3657                 PackageManagerService.reportSettingsProblem(Log.WARN,
3658                         "Unknown element under <updated-package>: " + parser.getName());
3659                 XmlUtils.skipCurrentTag(parser);
3660             }
3661         }
3662 
3663         mDisabledSysPackages.put(name, ps);
3664     }
3665 
3666     private static int PRE_M_APP_INFO_FLAG_HIDDEN = 1<<27;
3667     private static int PRE_M_APP_INFO_FLAG_CANT_SAVE_STATE = 1<<28;
3668     private static int PRE_M_APP_INFO_FLAG_PRIVILEGED = 1<<30;
3669 
3670     private void readPackageLPw(TypedXmlPullParser parser, List<UserInfo> users,
3671             ArrayMap<String, Long> originalFirstInstallTimes)
3672             throws XmlPullParserException, IOException {
3673         String name = null;
3674         String realName = null;
3675         int userId = 0;
3676         int sharedUserAppId = 0;
3677         String codePathStr = null;
3678         String legacyCpuAbiString = null;
3679         String legacyNativeLibraryPathStr = null;
3680         String primaryCpuAbiString = null;
3681         String secondaryCpuAbiString = null;
3682         String cpuAbiOverrideString = null;
3683         String systemStr = null;
3684         String installerPackageName = null;
3685         String installerAttributionTag = null;
3686         int packageSource = PackageInstaller.PACKAGE_SOURCE_UNSPECIFIED;
3687         boolean isOrphaned = false;
3688         String installOriginatingPackageName = null;
3689         String installInitiatingPackageName = null;
3690         boolean installInitiatorUninstalled = false;
3691         String volumeUuid = null;
3692         boolean updateAvailable = false;
3693         int categoryHint = ApplicationInfo.CATEGORY_UNDEFINED;
3694         int pkgFlags = 0;
3695         int pkgPrivateFlags = 0;
3696         long timeStamp = 0;
3697         long firstInstallTime = 0;
3698         long lastUpdateTime = 0;
3699         PackageSetting packageSetting = null;
3700         long versionCode = 0;
3701         boolean installedForceQueryable = false;
3702         float loadingProgress = 0;
3703         UUID domainSetId;
3704         try {
3705             name = parser.getAttributeValue(null, ATTR_NAME);
3706             realName = parser.getAttributeValue(null, "realName");
3707             userId = parser.getAttributeInt(null, "userId", 0);
3708             sharedUserAppId = parser.getAttributeInt(null, "sharedUserId", 0);
3709             codePathStr = parser.getAttributeValue(null, "codePath");
3710 
3711             legacyCpuAbiString = parser.getAttributeValue(null, "requiredCpuAbi");
3712 
3713             legacyNativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
3714             primaryCpuAbiString = parser.getAttributeValue(null, "primaryCpuAbi");
3715             secondaryCpuAbiString = parser.getAttributeValue(null, "secondaryCpuAbi");
3716             cpuAbiOverrideString = parser.getAttributeValue(null, "cpuAbiOverride");
3717             updateAvailable = parser.getAttributeBoolean(null, "updateAvailable", false);
3718             installedForceQueryable = parser.getAttributeBoolean(null, "forceQueryable", false);
3719             loadingProgress = parser.getAttributeFloat(null, "loadingProgress", 0);
3720 
3721             if (primaryCpuAbiString == null && legacyCpuAbiString != null) {
3722                 primaryCpuAbiString = legacyCpuAbiString;
3723             }
3724 
3725             versionCode = parser.getAttributeLong(null, "version", 0);
3726             installerPackageName = parser.getAttributeValue(null, "installer");
3727             installerAttributionTag = parser.getAttributeValue(null, "installerAttributionTag");
3728             packageSource = parser.getAttributeInt(null, "packageSource",
3729                     PackageInstaller.PACKAGE_SOURCE_UNSPECIFIED);
3730             isOrphaned = parser.getAttributeBoolean(null, "isOrphaned", false);
3731             installInitiatingPackageName = parser.getAttributeValue(null, "installInitiator");
3732             installOriginatingPackageName = parser.getAttributeValue(null, "installOriginator");
3733             installInitiatorUninstalled = parser.getAttributeBoolean(null,
3734                     "installInitiatorUninstalled", false);
3735             volumeUuid = parser.getAttributeValue(null, "volumeUuid");
3736             categoryHint = parser.getAttributeInt(null, "categoryHint",
3737                     ApplicationInfo.CATEGORY_UNDEFINED);
3738 
3739             String domainSetIdString = parser.getAttributeValue(null, "domainSetId");
3740 
3741             if (TextUtils.isEmpty(domainSetIdString)) {
3742                 // If empty, assume restoring from previous platform version and generate an ID
3743                 domainSetId = mDomainVerificationManager.generateNewId();
3744             } else {
3745                 domainSetId = UUID.fromString(domainSetIdString);
3746             }
3747 
3748             systemStr = parser.getAttributeValue(null, "publicFlags");
3749             if (systemStr != null) {
3750                 try {
3751                     pkgFlags = Integer.parseInt(systemStr);
3752                 } catch (NumberFormatException e) {
3753                 }
3754                 systemStr = parser.getAttributeValue(null, "privateFlags");
3755                 if (systemStr != null) {
3756                     try {
3757                         pkgPrivateFlags = Integer.parseInt(systemStr);
3758                     } catch (NumberFormatException e) {
3759                     }
3760                 }
3761             } else {
3762                 // Pre-M -- both public and private flags were stored in one "flags" field.
3763                 systemStr = parser.getAttributeValue(null, "flags");
3764                 if (systemStr != null) {
3765                     try {
3766                         pkgFlags = Integer.parseInt(systemStr);
3767                     } catch (NumberFormatException e) {
3768                     }
3769                     if ((pkgFlags & PRE_M_APP_INFO_FLAG_HIDDEN) != 0) {
3770                         pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_HIDDEN;
3771                     }
3772                     if ((pkgFlags & PRE_M_APP_INFO_FLAG_CANT_SAVE_STATE) != 0) {
3773                         pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE;
3774                     }
3775                     if ((pkgFlags & PRE_M_APP_INFO_FLAG_PRIVILEGED) != 0) {
3776                         pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
3777                     }
3778                     pkgFlags &= ~(PRE_M_APP_INFO_FLAG_HIDDEN
3779                             | PRE_M_APP_INFO_FLAG_CANT_SAVE_STATE
3780                             | PRE_M_APP_INFO_FLAG_PRIVILEGED);
3781                 } else {
3782                     // For backward compatibility
3783                     systemStr = parser.getAttributeValue(null, "system");
3784                     if (systemStr != null) {
3785                         pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM
3786                                 : 0;
3787                     } else {
3788                         // Old settings that don't specify system... just treat
3789                         // them as system, good enough.
3790                         pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
3791                     }
3792                 }
3793             }
3794             timeStamp = parser.getAttributeLongHex(null, "ft", 0);
3795             if (timeStamp == 0) {
3796                 timeStamp = parser.getAttributeLong(null, "ts", 0);
3797             }
3798             firstInstallTime = parser.getAttributeLongHex(null, "it", 0);
3799             lastUpdateTime = parser.getAttributeLongHex(null, "ut", 0);
3800             if (PackageManagerService.DEBUG_SETTINGS)
3801                 Log.v(PackageManagerService.TAG, "Reading package: " + name + " userId=" + userId
3802                         + " sharedUserId=" + sharedUserAppId);
3803             if (realName != null) {
3804                 realName = realName.intern();
3805             }
3806             if (name == null) {
3807                 PackageManagerService.reportSettingsProblem(Log.WARN,
3808                         "Error in package manager settings: <package> has no name at "
3809                                 + parser.getPositionDescription());
3810             } else if (codePathStr == null) {
3811                 PackageManagerService.reportSettingsProblem(Log.WARN,
3812                         "Error in package manager settings: <package> has no codePath at "
3813                                 + parser.getPositionDescription());
3814             } else if (userId > 0) {
3815                 packageSetting = addPackageLPw(name.intern(), realName, new File(codePathStr),
3816                         legacyNativeLibraryPathStr, primaryCpuAbiString, secondaryCpuAbiString,
3817                         cpuAbiOverrideString, userId, versionCode, pkgFlags, pkgPrivateFlags,
3818                         null /* usesSdkLibraries */, null /* usesSdkLibraryVersions */,
3819                         null /* usesStaticLibraries */, null /* usesStaticLibraryVersions */,
3820                         null /* mimeGroups */, domainSetId);
3821                 if (PackageManagerService.DEBUG_SETTINGS)
3822                     Log.i(PackageManagerService.TAG, "Reading package " + name + ": userId="
3823                             + userId + " pkg=" + packageSetting);
3824                 if (packageSetting == null) {
3825                     PackageManagerService.reportSettingsProblem(Log.ERROR, "Failure adding uid "
3826                             + userId + " while parsing settings at "
3827                             + parser.getPositionDescription());
3828                 } else {
3829                     packageSetting.setLastModifiedTime(timeStamp);
3830                     packageSetting.setLastUpdateTime(lastUpdateTime);
3831                 }
3832             } else if (sharedUserAppId != 0) {
3833                 if (sharedUserAppId > 0) {
3834                     packageSetting = new PackageSetting(name.intern(), realName,
3835                             new File(codePathStr), legacyNativeLibraryPathStr,
3836                             primaryCpuAbiString, secondaryCpuAbiString, cpuAbiOverrideString,
3837                             versionCode, pkgFlags, pkgPrivateFlags, sharedUserAppId,
3838                             null /* usesSdkLibraries */,
3839                             null /* usesSdkLibrariesVersions */,
3840                             null /* usesStaticLibraries */,
3841                             null /* usesStaticLibraryVersions */,
3842                             null /* mimeGroups */, domainSetId);
3843                     packageSetting.setLastModifiedTime(timeStamp);
3844                     packageSetting.setLastUpdateTime(lastUpdateTime);
3845                     mPendingPackages.add(packageSetting);
3846                     if (PackageManagerService.DEBUG_SETTINGS)
3847                         Log.i(PackageManagerService.TAG, "Reading package " + name
3848                                 + ": sharedUserId=" + sharedUserAppId + " pkg=" + packageSetting);
3849                 } else {
3850                     PackageManagerService.reportSettingsProblem(Log.WARN,
3851                             "Error in package manager settings: package " + name
3852                                     + " has bad sharedId " + sharedUserAppId + " at "
3853                                     + parser.getPositionDescription());
3854                 }
3855             } else {
3856                 PackageManagerService.reportSettingsProblem(Log.WARN,
3857                         "Error in package manager settings: package " + name + " has bad userId "
3858                                 + userId + " at " + parser.getPositionDescription());
3859             }
3860         } catch (NumberFormatException e) {
3861             PackageManagerService.reportSettingsProblem(Log.WARN,
3862                     "Error in package manager settings: package " + name + " has bad userId "
3863                             + userId + " at " + parser.getPositionDescription());
3864         }
3865         if (packageSetting != null) {
3866             InstallSource installSource = InstallSource.create(
3867                     installInitiatingPackageName, installOriginatingPackageName,
3868                     installerPackageName, installerAttributionTag, packageSource, isOrphaned,
3869                     installInitiatorUninstalled);
3870             packageSetting.setInstallSource(installSource)
3871                     .setVolumeUuid(volumeUuid)
3872                     .setCategoryOverride(categoryHint)
3873                     .setLegacyNativeLibraryPath(legacyNativeLibraryPathStr)
3874                     .setPrimaryCpuAbi(primaryCpuAbiString)
3875                     .setSecondaryCpuAbi(secondaryCpuAbiString)
3876                     .setUpdateAvailable(updateAvailable)
3877                     .setForceQueryableOverride(installedForceQueryable)
3878                     .setLoadingProgress(loadingProgress);
3879             // Handle legacy string here for single-user mode
3880             final String enabledStr = parser.getAttributeValue(null, ATTR_ENABLED);
3881             if (enabledStr != null) {
3882                 try {
3883                     packageSetting.setEnabled(Integer.parseInt(enabledStr), 0 /* userId */, null);
3884                 } catch (NumberFormatException e) {
3885                     if (enabledStr.equalsIgnoreCase("true")) {
3886                         packageSetting.setEnabled(COMPONENT_ENABLED_STATE_ENABLED, 0, null);
3887                     } else if (enabledStr.equalsIgnoreCase("false")) {
3888                         packageSetting.setEnabled(COMPONENT_ENABLED_STATE_DISABLED, 0, null);
3889                     } else if (enabledStr.equalsIgnoreCase("default")) {
3890                         packageSetting.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 0, null);
3891                     } else {
3892                         PackageManagerService.reportSettingsProblem(Log.WARN,
3893                                 "Error in package manager settings: package " + name
3894                                         + " has bad enabled value: " + enabledStr + " at "
3895                                         + parser.getPositionDescription());
3896                     }
3897                 }
3898             } else {
3899                 packageSetting.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 0, null);
3900             }
3901 
3902             addInstallerPackageNames(installSource);
3903 
3904             int outerDepth = parser.getDepth();
3905             int type;
3906             while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3907                     && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3908                 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3909                     continue;
3910                 }
3911 
3912                 String tagName = parser.getName();
3913                 // Legacy
3914                 if (tagName.equals(TAG_DISABLED_COMPONENTS)) {
3915                     readDisabledComponentsLPw(packageSetting, parser, 0);
3916                 } else if (tagName.equals(TAG_ENABLED_COMPONENTS)) {
3917                     readEnabledComponentsLPw(packageSetting, parser, 0);
3918                 } else if (tagName.equals("sigs")) {
3919                     packageSetting.getSignatures()
3920                             .readXml(parser,mPastSignatures.untrackedStorage());
3921                 } else if (tagName.equals(TAG_PERMISSIONS)) {
3922                     final LegacyPermissionState legacyState;
3923                     if (packageSetting.hasSharedUser()) {
3924                         final SettingBase sharedUserSettings = getSettingLPr(
3925                                 packageSetting.getSharedUserAppId());
3926                         legacyState = sharedUserSettings != null
3927                                 ? sharedUserSettings.getLegacyPermissionState() : null;
3928                     } else {
3929                         legacyState = packageSetting.getLegacyPermissionState();
3930                     }
3931                     if (legacyState != null) {
3932                         readInstallPermissionsLPr(parser, legacyState, users);
3933                         packageSetting.setInstallPermissionsFixed(true);
3934                     }
3935                 } else if (tagName.equals("proper-signing-keyset")) {
3936                     long id = parser.getAttributeLong(null, "identifier");
3937                     Integer refCt = mKeySetRefs.get(id);
3938                     if (refCt != null) {
3939                         mKeySetRefs.put(id, refCt + 1);
3940                     } else {
3941                         mKeySetRefs.put(id, 1);
3942                     }
3943                     packageSetting.getKeySetData().setProperSigningKeySet(id);
3944                 } else if (tagName.equals("signing-keyset")) {
3945                     // from v1 of keysetmanagerservice - no longer used
3946                 } else if (tagName.equals("upgrade-keyset")) {
3947                     long id = parser.getAttributeLong(null, "identifier");
3948                     packageSetting.getKeySetData().addUpgradeKeySetById(id);
3949                 } else if (tagName.equals("defined-keyset")) {
3950                     long id = parser.getAttributeLong(null, "identifier");
3951                     String alias = parser.getAttributeValue(null, "alias");
3952                     Integer refCt = mKeySetRefs.get(id);
3953                     if (refCt != null) {
3954                         mKeySetRefs.put(id, refCt + 1);
3955                     } else {
3956                         mKeySetRefs.put(id, 1);
3957                     }
3958                     packageSetting.getKeySetData().addDefinedKeySet(id, alias);
3959                 } else if (tagName.equals("install-initiator-sigs")) {
3960                     final PackageSignatures signatures = new PackageSignatures();
3961                     signatures.readXml(parser, mPastSignatures.untrackedStorage());
3962                     packageSetting.setInstallSource(
3963                             packageSetting.getInstallSource()
3964                                     .setInitiatingPackageSignatures(signatures));
3965                 } else if (tagName.equals(TAG_DOMAIN_VERIFICATION)) {
3966                     IntentFilterVerificationInfo ivi = new IntentFilterVerificationInfo(parser);
3967                     mDomainVerificationManager.addLegacySetting(packageSetting.getPackageName(),
3968                             ivi);
3969                     if (DEBUG_PARSER) {
3970                         Log.d(TAG, "Read domain verification for package: " + ivi.getPackageName());
3971                     }
3972                 } else if (tagName.equals(TAG_MIME_GROUP)) {
3973                     final Pair<String, Set<String>> groupToMimeTypes = readMimeGroupLPw(parser);
3974                     if (groupToMimeTypes != null) {
3975                         packageSetting.addMimeTypes(groupToMimeTypes.first,
3976                                 groupToMimeTypes.second);
3977                     }
3978                 } else if (tagName.equals(TAG_USES_STATIC_LIB)) {
3979                     readUsesStaticLibLPw(parser, packageSetting);
3980                 } else if (tagName.equals(TAG_USES_SDK_LIB)) {
3981                     readUsesSdkLibLPw(parser, packageSetting);
3982                 } else {
3983                     PackageManagerService.reportSettingsProblem(Log.WARN,
3984                             "Unknown element under <package>: " + parser.getName());
3985                     XmlUtils.skipCurrentTag(parser);
3986                 }
3987             }
3988             if (firstInstallTime != 0) {
3989                 originalFirstInstallTimes.put(packageSetting.getPackageName(), firstInstallTime);
3990             }
3991         } else {
3992             XmlUtils.skipCurrentTag(parser);
3993         }
3994     }
3995 
3996     void addInstallerPackageNames(InstallSource installSource) {
3997         if (installSource.installerPackageName != null) {
3998             mInstallerPackages.add(installSource.installerPackageName);
3999         }
4000         if (installSource.initiatingPackageName != null) {
4001             mInstallerPackages.add(installSource.initiatingPackageName);
4002         }
4003         if (installSource.originatingPackageName != null) {
4004             mInstallerPackages.add(installSource.originatingPackageName);
4005         }
4006     }
4007 
4008     @Nullable
4009     private Pair<String, Set<String>> readMimeGroupLPw(TypedXmlPullParser parser)
4010             throws XmlPullParserException, IOException {
4011         String groupName = parser.getAttributeValue(null, ATTR_NAME);
4012         if (groupName == null) {
4013             XmlUtils.skipCurrentTag(parser);
4014             return null;
4015         }
4016 
4017         Set<String> mimeTypes = new ArraySet<>();
4018         int outerDepth = parser.getDepth();
4019         int type;
4020         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
4021                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
4022             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
4023                 continue;
4024             }
4025 
4026             String tagName = parser.getName();
4027             if (tagName.equals(TAG_MIME_TYPE)) {
4028                 String typeName = parser.getAttributeValue(null, ATTR_VALUE);
4029                 if (typeName != null) {
4030                     mimeTypes.add(typeName);
4031                 }
4032             } else {
4033                 PackageManagerService.reportSettingsProblem(Log.WARN,
4034                         "Unknown element under <mime-group>: " + parser.getName());
4035                 XmlUtils.skipCurrentTag(parser);
4036             }
4037         }
4038 
4039         return Pair.create(groupName, mimeTypes);
4040     }
4041 
4042     private void writeMimeGroupLPr(TypedXmlSerializer serializer,
4043             Map<String, Set<String>> mimeGroups) throws IOException {
4044         if (mimeGroups == null) {
4045             return;
4046         }
4047 
4048         for (String mimeGroup: mimeGroups.keySet()) {
4049             serializer.startTag(null, TAG_MIME_GROUP);
4050             serializer.attribute(null, ATTR_NAME, mimeGroup);
4051 
4052             for (String mimeType: mimeGroups.get(mimeGroup)) {
4053                 serializer.startTag(null, TAG_MIME_TYPE);
4054                 serializer.attribute(null, ATTR_VALUE, mimeType);
4055                 serializer.endTag(null, TAG_MIME_TYPE);
4056             }
4057 
4058             serializer.endTag(null, TAG_MIME_GROUP);
4059         }
4060     }
4061 
4062     private void readDisabledComponentsLPw(PackageSetting packageSetting, TypedXmlPullParser parser,
4063             int userId) throws IOException, XmlPullParserException {
4064         int outerDepth = parser.getDepth();
4065         int type;
4066         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
4067                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
4068             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
4069                 continue;
4070             }
4071 
4072             String tagName = parser.getName();
4073             if (tagName.equals(TAG_ITEM)) {
4074                 String name = parser.getAttributeValue(null, ATTR_NAME);
4075                 if (name != null) {
4076                     packageSetting.addDisabledComponent(name.intern(), userId);
4077                 } else {
4078                     PackageManagerService.reportSettingsProblem(Log.WARN,
4079                             "Error in package manager settings: <disabled-components> has"
4080                                     + " no name at " + parser.getPositionDescription());
4081                 }
4082             } else {
4083                 PackageManagerService.reportSettingsProblem(Log.WARN,
4084                         "Unknown element under <disabled-components>: " + parser.getName());
4085             }
4086             XmlUtils.skipCurrentTag(parser);
4087         }
4088     }
4089 
4090     private void readEnabledComponentsLPw(PackageSetting packageSetting, TypedXmlPullParser parser,
4091             int userId) throws IOException, XmlPullParserException {
4092         int outerDepth = parser.getDepth();
4093         int type;
4094         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
4095                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
4096             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
4097                 continue;
4098             }
4099 
4100             String tagName = parser.getName();
4101             if (tagName.equals(TAG_ITEM)) {
4102                 String name = parser.getAttributeValue(null, ATTR_NAME);
4103                 if (name != null) {
4104                     packageSetting.addEnabledComponent(name.intern(), userId);
4105                 } else {
4106                     PackageManagerService.reportSettingsProblem(Log.WARN,
4107                             "Error in package manager settings: <enabled-components> has"
4108                                     + " no name at " + parser.getPositionDescription());
4109                 }
4110             } else {
4111                 PackageManagerService.reportSettingsProblem(Log.WARN,
4112                         "Unknown element under <enabled-components>: " + parser.getName());
4113             }
4114             XmlUtils.skipCurrentTag(parser);
4115         }
4116     }
4117 
4118     private void readSharedUserLPw(TypedXmlPullParser parser, List<UserInfo> users)
4119             throws XmlPullParserException, IOException {
4120         String name = null;
4121         int pkgFlags = 0;
4122         int pkgPrivateFlags = 0;
4123         SharedUserSetting su = null;
4124         {
4125             name = parser.getAttributeValue(null, ATTR_NAME);
4126             int userId = parser.getAttributeInt(null, "userId", 0);
4127             if (parser.getAttributeBoolean(null, "system", false)) {
4128                 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
4129             }
4130             if (name == null) {
4131                 PackageManagerService.reportSettingsProblem(Log.WARN,
4132                         "Error in package manager settings: <shared-user> has no name at "
4133                                 + parser.getPositionDescription());
4134             } else if (userId == 0) {
4135                 PackageManagerService.reportSettingsProblem(Log.WARN,
4136                         "Error in package manager settings: shared-user " + name
4137                                 + " has bad userId " + userId + " at "
4138                                 + parser.getPositionDescription());
4139             } else {
4140                 if ((su = addSharedUserLPw(name.intern(), userId, pkgFlags, pkgPrivateFlags))
4141                         == null) {
4142                     PackageManagerService
4143                             .reportSettingsProblem(Log.ERROR, "Occurred while parsing settings at "
4144                                     + parser.getPositionDescription());
4145                 }
4146             }
4147         }
4148 
4149         if (su != null) {
4150             int outerDepth = parser.getDepth();
4151             int type;
4152             while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
4153                     && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
4154                 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
4155                     continue;
4156                 }
4157 
4158                 String tagName = parser.getName();
4159                 if (tagName.equals("sigs")) {
4160                     su.signatures.readXml(parser, mPastSignatures.untrackedStorage());
4161                 } else if (tagName.equals("perms")) {
4162                     readInstallPermissionsLPr(parser, su.getLegacyPermissionState(), users);
4163                 } else {
4164                     PackageManagerService.reportSettingsProblem(Log.WARN,
4165                             "Unknown element under <shared-user>: " + parser.getName());
4166                     XmlUtils.skipCurrentTag(parser);
4167                 }
4168             }
4169         } else {
4170             XmlUtils.skipCurrentTag(parser);
4171         }
4172     }
4173 
4174     void createNewUserLI(@NonNull PackageManagerService service, @NonNull Installer installer,
4175             @UserIdInt int userHandle, @Nullable Set<String> userTypeInstallablePackages,
4176             String[] disallowedPackages) {
4177         final TimingsTraceAndSlog t = new TimingsTraceAndSlog(TAG + "Timing",
4178                 Trace.TRACE_TAG_PACKAGE_MANAGER);
4179         t.traceBegin("createNewUser-" + userHandle);
4180         Installer.Batch batch = new Installer.Batch();
4181         final boolean skipPackageAllowList = userTypeInstallablePackages == null;
4182         synchronized (mLock) {
4183             final int size = mPackages.size();
4184             for (int i = 0; i < size; i++) {
4185                 final PackageSetting ps = mPackages.valueAt(i);
4186                 if (ps.getPkg() == null) {
4187                     continue;
4188                 }
4189                 final boolean shouldMaybeInstall = ps.isSystem() &&
4190                         !ArrayUtils.contains(disallowedPackages, ps.getPackageName()) &&
4191                         !ps.getPkgState().isHiddenUntilInstalled();
4192                 final boolean shouldReallyInstall = shouldMaybeInstall &&
4193                         (skipPackageAllowList || userTypeInstallablePackages.contains(
4194                                 ps.getPackageName()));
4195                 // Only system apps are initially installed.
4196                 ps.setInstalled(shouldReallyInstall, userHandle);
4197                 // If userTypeInstallablePackages is the *only* reason why we're not installing,
4198                 // then uninstallReason is USER_TYPE. If there's a different reason, or if we
4199                 // actually are installing, put UNKNOWN.
4200                 final int uninstallReason = (shouldMaybeInstall && !shouldReallyInstall) ?
4201                         UNINSTALL_REASON_USER_TYPE : UNINSTALL_REASON_UNKNOWN;
4202                 ps.setUninstallReason(uninstallReason, userHandle);
4203                 if (shouldReallyInstall) {
4204                     // Need to create a data directory for all apps installed for this user.
4205                     // Accumulate all required args and call the installer after mPackages lock
4206                     // has been released
4207                     final String seInfo = AndroidPackageUtils.getSeInfo(ps.getPkg(), ps);
4208                     final boolean usesSdk = !ps.getPkg().getUsesSdkLibraries().isEmpty();
4209                     final CreateAppDataArgs args = Installer.buildCreateAppDataArgs(
4210                             ps.getVolumeUuid(), ps.getPackageName(), userHandle,
4211                             StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE,
4212                             ps.getAppId(), seInfo, ps.getPkg().getTargetSdkVersion(), usesSdk);
4213                     batch.createAppData(args);
4214                 } else {
4215                     // Make sure the app is excluded from storage mapping for this user
4216                     writeKernelMappingLPr(ps);
4217                 }
4218             }
4219         }
4220         t.traceBegin("createAppData");
4221         try {
4222             batch.execute(installer);
4223         } catch (InstallerException e) {
4224             Slog.w(TAG, "Failed to prepare app data", e);
4225         }
4226         t.traceEnd(); // createAppData
4227         synchronized (mLock) {
4228             applyDefaultPreferredAppsLPw(userHandle);
4229         }
4230         t.traceEnd(); // createNewUser
4231     }
4232 
4233     void removeUserLPw(int userId) {
4234         Set<Entry<String, PackageSetting>> entries = mPackages.entrySet();
4235         for (Entry<String, PackageSetting> entry : entries) {
4236             entry.getValue().removeUser(userId);
4237         }
4238         mPreferredActivities.remove(userId);
4239         File file = getUserPackagesStateFile(userId);
4240         file.delete();
4241         file = getUserPackagesStateBackupFile(userId);
4242         file.delete();
4243         removeCrossProfileIntentFiltersLPw(userId);
4244 
4245         mRuntimePermissionsPersistence.onUserRemoved(userId);
4246         mDomainVerificationManager.clearUser(userId);
4247 
4248         writePackageListLPr();
4249 
4250         // Inform kernel that the user was removed, so that packages are marked uninstalled
4251         // for sdcardfs
4252         writeKernelRemoveUserLPr(userId);
4253     }
4254 
4255     void removeCrossProfileIntentFiltersLPw(int userId) {
4256         synchronized (mCrossProfileIntentResolvers) {
4257             // userId is the source user
4258             if (mCrossProfileIntentResolvers.get(userId) != null) {
4259                 mCrossProfileIntentResolvers.remove(userId);
4260                 writePackageRestrictionsLPr(userId);
4261             }
4262             // userId is the target user
4263             int count = mCrossProfileIntentResolvers.size();
4264             for (int i = 0; i < count; i++) {
4265                 int sourceUserId = mCrossProfileIntentResolvers.keyAt(i);
4266                 CrossProfileIntentResolver cpir = mCrossProfileIntentResolvers.get(sourceUserId);
4267                 boolean needsWriting = false;
4268                 ArraySet<CrossProfileIntentFilter> cpifs =
4269                         new ArraySet<CrossProfileIntentFilter>(cpir.filterSet());
4270                 for (CrossProfileIntentFilter cpif : cpifs) {
4271                     if (cpif.getTargetUserId() == userId) {
4272                         needsWriting = true;
4273                         cpir.removeFilter(cpif);
4274                     }
4275                 }
4276                 if (needsWriting) {
4277                     writePackageRestrictionsLPr(sourceUserId);
4278                 }
4279             }
4280         }
4281     }
4282 
4283     public VerifierDeviceIdentity getVerifierDeviceIdentityLPw(@NonNull Computer computer) {
4284         if (mVerifierDeviceIdentity == null) {
4285             mVerifierDeviceIdentity = VerifierDeviceIdentity.generate();
4286 
4287             writeLPr(computer);
4288         }
4289 
4290         return mVerifierDeviceIdentity;
4291     }
4292 
4293     /**
4294      * Returns the disabled {@link PackageSetting} for the provided package name if one exists,
4295      * {@code null} otherwise.
4296      */
4297     @Nullable
4298     public PackageSetting getDisabledSystemPkgLPr(String name) {
4299         PackageSetting ps = mDisabledSysPackages.get(name);
4300         return ps;
4301     }
4302 
4303     /**
4304      * Returns the disabled {@link PackageSetting} for the provided enabled {@link PackageSetting}
4305      * if one exists, {@code null} otherwise.
4306      */
4307     @Nullable
4308     public PackageSetting getDisabledSystemPkgLPr(PackageSetting enabledPackageSetting) {
4309         if (enabledPackageSetting == null) {
4310             return null;
4311         }
4312         return getDisabledSystemPkgLPr(enabledPackageSetting.getPackageName());
4313     }
4314 
4315     int getApplicationEnabledSettingLPr(String packageName, int userId)
4316             throws PackageManager.NameNotFoundException {
4317         final PackageSetting pkg = mPackages.get(packageName);
4318         if (pkg == null) {
4319             throw new PackageManager.NameNotFoundException(packageName);
4320         }
4321         return pkg.getEnabled(userId);
4322     }
4323 
4324     int getComponentEnabledSettingLPr(ComponentName componentName, int userId)
4325             throws PackageManager.NameNotFoundException {
4326         final String packageName = componentName.getPackageName();
4327         final PackageSetting pkg = mPackages.get(packageName);
4328         if (pkg == null) {
4329             throw new PackageManager.NameNotFoundException(componentName.getPackageName());
4330         }
4331         final String classNameStr = componentName.getClassName();
4332         return pkg.getCurrentEnabledStateLPr(classNameStr, userId);
4333     }
4334 
4335     SharedUserSetting getSharedUserSettingLPr(String packageName) {
4336         final PackageSetting ps = mPackages.get(packageName);
4337         return getSharedUserSettingLPr(ps);
4338     }
4339 
4340     @Nullable
4341     SharedUserSetting getSharedUserSettingLPr(PackageSetting ps) {
4342         if (ps == null || !ps.hasSharedUser()) {
4343             return null;
4344         }
4345         return (SharedUserSetting) getSettingLPr(ps.getSharedUserAppId());
4346     }
4347 
4348     /**
4349      * Returns all users on the device, including pre-created and dying users.
4350      *
4351      * @param userManager UserManagerService instance
4352      * @return the list of users
4353      */
4354     private static List<UserInfo> getAllUsers(UserManagerService userManager) {
4355         return getUsers(userManager, /* excludeDying= */ false, /* excludePreCreated= */ false);
4356     }
4357 
4358     /**
4359      * Returns the list of users on the device, excluding pre-created ones.
4360      *
4361      * @param userManager UserManagerService instance
4362      * @param excludeDying Indicates whether to exclude any users marked for deletion.
4363      *
4364      * @return the list of users
4365      */
4366     private static List<UserInfo> getActiveUsers(UserManagerService userManager,
4367             boolean excludeDying) {
4368         return getUsers(userManager, excludeDying, /* excludePreCreated= */ true);
4369     }
4370 
4371     /**
4372      * Returns the list of users on the device.
4373      *
4374      * @param userManager UserManagerService instance
4375      * @param excludeDying Indicates whether to exclude any users marked for deletion.
4376      * @param excludePreCreated Indicates whether to exclude any pre-created users.
4377      *
4378      * @return the list of users
4379      */
4380     private static List<UserInfo> getUsers(UserManagerService userManager, boolean excludeDying,
4381             boolean excludePreCreated) {
4382         final long id = Binder.clearCallingIdentity();
4383         try {
4384             return userManager.getUsers(/* excludePartial= */ true, excludeDying,
4385                     excludePreCreated);
4386         } catch (NullPointerException npe) {
4387             // packagemanager not yet initialized
4388         } finally {
4389             Binder.restoreCallingIdentity(id);
4390         }
4391         return null;
4392     }
4393 
4394     /**
4395      * Return all {@link PackageSetting} that are actively installed on the
4396      * given {@link VolumeInfo#fsUuid}.
4397      */
4398     List<? extends PackageStateInternal> getVolumePackagesLPr(String volumeUuid) {
4399         ArrayList<PackageStateInternal> res = new ArrayList<>();
4400         for (int i = 0; i < mPackages.size(); i++) {
4401             final PackageSetting setting = mPackages.valueAt(i);
4402             if (Objects.equals(volumeUuid, setting.getVolumeUuid())) {
4403                 res.add(setting);
4404             }
4405         }
4406         return res;
4407     }
4408 
4409     static void printFlags(PrintWriter pw, int val, Object[] spec) {
4410         pw.print("[ ");
4411         for (int i=0; i<spec.length; i+=2) {
4412             int mask = (Integer)spec[i];
4413             if ((val & mask) != 0) {
4414                 pw.print(spec[i+1]);
4415                 pw.print(" ");
4416             }
4417         }
4418         pw.print("]");
4419     }
4420 
4421     static final Object[] FLAG_DUMP_SPEC = new Object[] {
4422         ApplicationInfo.FLAG_SYSTEM, "SYSTEM",
4423         ApplicationInfo.FLAG_DEBUGGABLE, "DEBUGGABLE",
4424         ApplicationInfo.FLAG_HAS_CODE, "HAS_CODE",
4425         ApplicationInfo.FLAG_PERSISTENT, "PERSISTENT",
4426         ApplicationInfo.FLAG_FACTORY_TEST, "FACTORY_TEST",
4427         ApplicationInfo.FLAG_ALLOW_TASK_REPARENTING, "ALLOW_TASK_REPARENTING",
4428         ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA, "ALLOW_CLEAR_USER_DATA",
4429         ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, "UPDATED_SYSTEM_APP",
4430         ApplicationInfo.FLAG_TEST_ONLY, "TEST_ONLY",
4431         ApplicationInfo.FLAG_VM_SAFE_MODE, "VM_SAFE_MODE",
4432         ApplicationInfo.FLAG_ALLOW_BACKUP, "ALLOW_BACKUP",
4433         ApplicationInfo.FLAG_KILL_AFTER_RESTORE, "KILL_AFTER_RESTORE",
4434         ApplicationInfo.FLAG_RESTORE_ANY_VERSION, "RESTORE_ANY_VERSION",
4435         ApplicationInfo.FLAG_EXTERNAL_STORAGE, "EXTERNAL_STORAGE",
4436         ApplicationInfo.FLAG_LARGE_HEAP, "LARGE_HEAP",
4437     };
4438 
4439     private static final Object[] PRIVATE_FLAG_DUMP_SPEC = new Object[] {
4440             ApplicationInfo.PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_RESIZEABLE, "PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_RESIZEABLE",
4441             ApplicationInfo.PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION, "PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION",
4442             ApplicationInfo.PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_UNRESIZEABLE, "PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_UNRESIZEABLE",
4443             ApplicationInfo.PRIVATE_FLAG_ALLOW_AUDIO_PLAYBACK_CAPTURE, "ALLOW_AUDIO_PLAYBACK_CAPTURE",
4444             ApplicationInfo.PRIVATE_FLAG_REQUEST_LEGACY_EXTERNAL_STORAGE, "PRIVATE_FLAG_REQUEST_LEGACY_EXTERNAL_STORAGE",
4445             ApplicationInfo.PRIVATE_FLAG_BACKUP_IN_FOREGROUND, "BACKUP_IN_FOREGROUND",
4446             ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE, "CANT_SAVE_STATE",
4447             ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE, "DEFAULT_TO_DEVICE_PROTECTED_STORAGE",
4448             ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE, "DIRECT_BOOT_AWARE",
4449             ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS, "HAS_DOMAIN_URLS",
4450             ApplicationInfo.PRIVATE_FLAG_HIDDEN, "HIDDEN",
4451             ApplicationInfo.PRIVATE_FLAG_INSTANT, "EPHEMERAL",
4452             ApplicationInfo.PRIVATE_FLAG_ISOLATED_SPLIT_LOADING, "ISOLATED_SPLIT_LOADING",
4453             ApplicationInfo.PRIVATE_FLAG_OEM, "OEM",
4454             ApplicationInfo.PRIVATE_FLAG_PARTIALLY_DIRECT_BOOT_AWARE, "PARTIALLY_DIRECT_BOOT_AWARE",
4455             ApplicationInfo.PRIVATE_FLAG_PRIVILEGED, "PRIVILEGED",
4456             ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER, "REQUIRED_FOR_SYSTEM_USER",
4457             ApplicationInfo.PRIVATE_FLAG_STATIC_SHARED_LIBRARY, "STATIC_SHARED_LIBRARY",
4458             ApplicationInfo.PRIVATE_FLAG_VENDOR, "VENDOR",
4459             ApplicationInfo.PRIVATE_FLAG_PRODUCT, "PRODUCT",
4460             ApplicationInfo.PRIVATE_FLAG_SYSTEM_EXT, "SYSTEM_EXT",
4461             ApplicationInfo.PRIVATE_FLAG_VIRTUAL_PRELOAD, "VIRTUAL_PRELOAD",
4462             ApplicationInfo.PRIVATE_FLAG_ODM, "ODM",
4463             ApplicationInfo.PRIVATE_FLAG_ALLOW_NATIVE_HEAP_POINTER_TAGGING, "PRIVATE_FLAG_ALLOW_NATIVE_HEAP_POINTER_TAGGING",
4464     };
4465 
4466     void dumpVersionLPr(IndentingPrintWriter pw) {
4467         pw.increaseIndent();
4468         for (int i= 0; i < mVersion.size(); i++) {
4469             final String volumeUuid = mVersion.keyAt(i);
4470             final VersionInfo ver = mVersion.valueAt(i);
4471             if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
4472                 pw.println("Internal:");
4473             } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
4474                 pw.println("External:");
4475             } else {
4476                 pw.println("UUID " + volumeUuid + ":");
4477             }
4478             pw.increaseIndent();
4479             pw.printPair("sdkVersion", ver.sdkVersion);
4480             pw.printPair("databaseVersion", ver.databaseVersion);
4481             pw.println();
4482             pw.printPair("fingerprint", ver.fingerprint);
4483             pw.println();
4484             pw.decreaseIndent();
4485         }
4486         pw.decreaseIndent();
4487     }
4488 
4489     @NeverCompile // Avoid size overhead of debugging code.
4490     void dumpPackageLPr(PrintWriter pw, String prefix, String checkinTag,
4491             ArraySet<String> permissionNames, PackageSetting ps,
4492             LegacyPermissionState permissionsState, SimpleDateFormat sdf, Date date,
4493             List<UserInfo> users, boolean dumpAll, boolean dumpAllComponents) {
4494         AndroidPackage pkg = ps.getPkg();
4495         if (checkinTag != null) {
4496             pw.print(checkinTag);
4497             pw.print(",");
4498             pw.print(ps.getRealName() != null ? ps.getRealName() : ps.getPackageName());
4499             pw.print(",");
4500             pw.print(ps.getAppId());
4501             pw.print(",");
4502             pw.print(ps.getVersionCode());
4503             pw.print(",");
4504             pw.print(ps.getLastUpdateTime());
4505             pw.print(",");
4506             pw.print(ps.getInstallSource().installerPackageName != null
4507                     ? ps.getInstallSource().installerPackageName : "?");
4508             pw.print(ps.getInstallSource().installerAttributionTag != null
4509                     ? "(" + ps.getInstallSource().installerAttributionTag + ")" : "");
4510             pw.print(",");
4511             pw.print(ps.getInstallSource().packageSource);
4512             pw.println();
4513             if (pkg != null) {
4514                 pw.print(checkinTag); pw.print("-"); pw.print("splt,");
4515                 pw.print("base,");
4516                 pw.println(pkg.getBaseRevisionCode());
4517                 int[] splitRevisionCodes = pkg.getSplitRevisionCodes();
4518                 for (int i = 0; i < pkg.getSplitNames().length; i++) {
4519                     pw.print(checkinTag); pw.print("-"); pw.print("splt,");
4520                     pw.print(pkg.getSplitNames()[i]); pw.print(",");
4521                     pw.println(splitRevisionCodes[i]);
4522                 }
4523             }
4524             for (UserInfo user : users) {
4525                 final PackageUserStateInternal userState = ps.getUserStateOrDefault(user.id);
4526                 pw.print(checkinTag);
4527                 pw.print("-");
4528                 pw.print("usr");
4529                 pw.print(",");
4530                 pw.print(user.id);
4531                 pw.print(",");
4532                 pw.print(userState.isInstalled() ? "I" : "i");
4533                 pw.print(userState.isHidden() ? "B" : "b");
4534                 pw.print(userState.isSuspended() ? "SU" : "su");
4535                 pw.print(userState.isStopped() ? "S" : "s");
4536                 pw.print(userState.isNotLaunched() ? "l" : "L");
4537                 pw.print(userState.isInstantApp() ? "IA" : "ia");
4538                 pw.print(userState.isVirtualPreload() ? "VPI" : "vpi");
4539                 String harmfulAppWarning = userState.getHarmfulAppWarning();
4540                 pw.print(harmfulAppWarning != null ? "HA" : "ha");
4541                 pw.print(",");
4542                 pw.print(userState.getEnabledState());
4543                 String lastDisabledAppCaller = userState.getLastDisableAppCaller();
4544                 pw.print(",");
4545                 pw.print(lastDisabledAppCaller != null ? lastDisabledAppCaller : "?");
4546                 pw.print(",");
4547                 pw.print(ps.readUserState(user.id).getFirstInstallTime());
4548                 pw.print(",");
4549                 pw.println();
4550             }
4551             return;
4552         }
4553 
4554         pw.print(prefix); pw.print("Package [");
4555             pw.print(ps.getRealName() != null ? ps.getRealName() : ps.getPackageName());
4556             pw.print("] (");
4557             pw.print(Integer.toHexString(System.identityHashCode(ps)));
4558             pw.println("):");
4559 
4560         if (ps.getRealName() != null) {
4561             pw.print(prefix); pw.print("  compat name=");
4562             pw.println(ps.getPackageName());
4563         }
4564 
4565         pw.print(prefix); pw.print("  userId="); pw.println(ps.getAppId());
4566 
4567         SharedUserSetting sharedUserSetting = getSharedUserSettingLPr(ps);
4568         if (sharedUserSetting != null) {
4569             pw.print(prefix); pw.print("  sharedUser="); pw.println(sharedUserSetting);
4570         }
4571         pw.print(prefix); pw.print("  pkg="); pw.println(pkg);
4572         pw.print(prefix); pw.print("  codePath="); pw.println(ps.getPathString());
4573         if (permissionNames == null) {
4574             pw.print(prefix); pw.print("  resourcePath="); pw.println(ps.getPathString());
4575             pw.print(prefix); pw.print("  legacyNativeLibraryDir=");
4576             pw.println(ps.getLegacyNativeLibraryPath());
4577             pw.print(prefix); pw.print("  extractNativeLibs=");
4578             pw.println((ps.getFlags() & ApplicationInfo.FLAG_EXTRACT_NATIVE_LIBS) != 0
4579                     ? "true" : "false");
4580             pw.print(prefix); pw.print("  primaryCpuAbi="); pw.println(ps.getPrimaryCpuAbi());
4581             pw.print(prefix); pw.print("  secondaryCpuAbi="); pw.println(ps.getSecondaryCpuAbi());
4582             pw.print(prefix); pw.print("  cpuAbiOverride="); pw.println(ps.getCpuAbiOverride());
4583         }
4584         pw.print(prefix); pw.print("  versionCode="); pw.print(ps.getVersionCode());
4585         if (pkg != null) {
4586             pw.print(" minSdk="); pw.print(pkg.getMinSdkVersion());
4587             pw.print(" targetSdk="); pw.println(pkg.getTargetSdkVersion());
4588 
4589             SparseIntArray minExtensionVersions = pkg.getMinExtensionVersions();
4590 
4591             pw.print(prefix); pw.print("  minExtensionVersions=[");
4592             if (minExtensionVersions != null) {
4593                 List<String> minExtVerStrings = new ArrayList<>();
4594                 int size = minExtensionVersions.size();
4595                 for (int index = 0; index < size; index++) {
4596                     int key = minExtensionVersions.keyAt(index);
4597                     int value = minExtensionVersions.valueAt(index);
4598                     minExtVerStrings.add(key + "=" + value);
4599                 }
4600 
4601                 pw.print(TextUtils.join(", ", minExtVerStrings));
4602             }
4603             pw.print("]");
4604         }
4605         pw.println();
4606         if (pkg != null) {
4607             pw.print(prefix); pw.print("  versionName="); pw.println(pkg.getVersionName());
4608             pw.print(prefix); pw.print("  usesNonSdkApi="); pw.println(pkg.isUsesNonSdkApi());
4609             pw.print(prefix); pw.print("  splits="); dumpSplitNames(pw, pkg); pw.println();
4610             final int apkSigningVersion = pkg.getSigningDetails().getSignatureSchemeVersion();
4611             pw.print(prefix); pw.print("  apkSigningVersion="); pw.println(apkSigningVersion);
4612             pw.print(prefix); pw.print("  flags=");
4613             printFlags(pw, PackageInfoUtils.appInfoFlags(pkg, ps), FLAG_DUMP_SPEC); pw.println();
4614             int privateFlags = PackageInfoUtils.appInfoPrivateFlags(pkg, ps);
4615             if (privateFlags != 0) {
4616                 pw.print(prefix); pw.print("  privateFlags="); printFlags(pw,
4617                         privateFlags, PRIVATE_FLAG_DUMP_SPEC); pw.println();
4618             }
4619             if (pkg.hasPreserveLegacyExternalStorage()) {
4620                 pw.print(prefix); pw.print("  hasPreserveLegacyExternalStorage=true");
4621                 pw.println();
4622             }
4623             pw.print(prefix); pw.print("  forceQueryable=");
4624             pw.print(ps.getPkg().isForceQueryable());
4625             if (ps.isForceQueryableOverride()) {
4626                 pw.print(" (override=true)");
4627             }
4628             pw.println();
4629             if (!ps.getPkg().getQueriesPackages().isEmpty()) {
4630                 pw.append(prefix).append("  queriesPackages=")
4631                         .println(ps.getPkg().getQueriesPackages());
4632             }
4633             if (!ps.getPkg().getQueriesIntents().isEmpty()) {
4634                 pw.append(prefix).append("  queriesIntents=")
4635                         .println(ps.getPkg().getQueriesIntents());
4636             }
4637             File dataDir = PackageInfoWithoutStateUtils.getDataDir(pkg, UserHandle.myUserId());
4638             pw.print(prefix); pw.print("  dataDir="); pw.println(dataDir.getAbsolutePath());
4639             pw.print(prefix); pw.print("  supportsScreens=[");
4640             boolean first = true;
4641             if (pkg.isSupportsSmallScreens()) {
4642                 if (!first)
4643                     pw.print(", ");
4644                 first = false;
4645                 pw.print("small");
4646             }
4647             if (pkg.isSupportsNormalScreens()) {
4648                 if (!first)
4649                     pw.print(", ");
4650                 first = false;
4651                 pw.print("medium");
4652             }
4653             if (pkg.isSupportsLargeScreens()) {
4654                 if (!first)
4655                     pw.print(", ");
4656                 first = false;
4657                 pw.print("large");
4658             }
4659             if (pkg.isSupportsExtraLargeScreens()) {
4660                 if (!first)
4661                     pw.print(", ");
4662                 first = false;
4663                 pw.print("xlarge");
4664             }
4665             if (pkg.isResizeable()) {
4666                 if (!first)
4667                     pw.print(", ");
4668                 first = false;
4669                 pw.print("resizeable");
4670             }
4671             if (pkg.isAnyDensity()) {
4672                 if (!first)
4673                     pw.print(", ");
4674                 first = false;
4675                 pw.print("anyDensity");
4676             }
4677             pw.println("]");
4678             final List<String> libraryNames = pkg.getLibraryNames();
4679             if (libraryNames != null && libraryNames.size() > 0) {
4680                 pw.print(prefix); pw.println("  dynamic libraries:");
4681                 for (int i = 0; i< libraryNames.size(); i++) {
4682                     pw.print(prefix); pw.print("    ");
4683                             pw.println(libraryNames.get(i));
4684                 }
4685             }
4686             if (pkg.getStaticSharedLibName() != null) {
4687                 pw.print(prefix); pw.println("  static library:");
4688                 pw.print(prefix); pw.print("    ");
4689                 pw.print("name:"); pw.print(pkg.getStaticSharedLibName());
4690                 pw.print(" version:"); pw.println(pkg.getStaticSharedLibVersion());
4691             }
4692 
4693             if (pkg.getSdkLibName() != null) {
4694                 pw.print(prefix); pw.println("  SDK library:");
4695                 pw.print(prefix); pw.print("    ");
4696                 pw.print("name:"); pw.print(pkg.getSdkLibName());
4697                 pw.print(" versionMajor:"); pw.println(pkg.getSdkLibVersionMajor());
4698             }
4699 
4700             List<String> usesLibraries = pkg.getUsesLibraries();
4701             if (usesLibraries.size() > 0) {
4702                 pw.print(prefix); pw.println("  usesLibraries:");
4703                 for (int i=0; i< usesLibraries.size(); i++) {
4704                     pw.print(prefix); pw.print("    "); pw.println(usesLibraries.get(i));
4705                 }
4706             }
4707 
4708             List<String> usesStaticLibraries = pkg.getUsesStaticLibraries();
4709             long[] usesStaticLibrariesVersions = pkg.getUsesStaticLibrariesVersions();
4710             if (usesStaticLibraries.size() > 0) {
4711                 pw.print(prefix); pw.println("  usesStaticLibraries:");
4712                 for (int i=0; i< usesStaticLibraries.size(); i++) {
4713                     pw.print(prefix); pw.print("    ");
4714                     pw.print(usesStaticLibraries.get(i)); pw.print(" version:");
4715                             pw.println(usesStaticLibrariesVersions[i]);
4716                 }
4717             }
4718 
4719             List<String> usesSdkLibraries = pkg.getUsesSdkLibraries();
4720             long[] usesSdkLibrariesVersionsMajor = pkg.getUsesSdkLibrariesVersionsMajor();
4721             if (usesSdkLibraries.size() > 0) {
4722                 pw.print(prefix); pw.println("  usesSdkLibraries:");
4723                 for (int i = 0, size = usesSdkLibraries.size(); i < size; ++i) {
4724                     pw.print(prefix); pw.print("    ");
4725                     pw.print(usesSdkLibraries.get(i)); pw.print(" version:");
4726                     pw.println(usesSdkLibrariesVersionsMajor[i]);
4727                 }
4728             }
4729 
4730             List<String> usesOptionalLibraries = pkg.getUsesOptionalLibraries();
4731             if (usesOptionalLibraries.size() > 0) {
4732                 pw.print(prefix); pw.println("  usesOptionalLibraries:");
4733                 for (int i=0; i< usesOptionalLibraries.size(); i++) {
4734                     pw.print(prefix); pw.print("    ");
4735                     pw.println(usesOptionalLibraries.get(i));
4736                 }
4737             }
4738 
4739             List<String> usesNativeLibraries = pkg.getUsesNativeLibraries();
4740             if (usesNativeLibraries.size() > 0) {
4741                 pw.print(prefix); pw.println("  usesNativeLibraries:");
4742                 for (int i=0; i< usesNativeLibraries.size(); i++) {
4743                     pw.print(prefix); pw.print("    "); pw.println(usesNativeLibraries.get(i));
4744                 }
4745             }
4746 
4747             List<String> usesOptionalNativeLibraries = pkg.getUsesOptionalNativeLibraries();
4748             if (usesOptionalNativeLibraries.size() > 0) {
4749                 pw.print(prefix); pw.println("  usesOptionalNativeLibraries:");
4750                 for (int i=0; i< usesOptionalNativeLibraries.size(); i++) {
4751                     pw.print(prefix); pw.print("    ");
4752                     pw.println(usesOptionalNativeLibraries.get(i));
4753                 }
4754             }
4755 
4756             List<String> usesLibraryFiles = ps.getPkgState().getUsesLibraryFiles();
4757             if (usesLibraryFiles.size() > 0) {
4758                 pw.print(prefix); pw.println("  usesLibraryFiles:");
4759                 for (int i=0; i< usesLibraryFiles.size(); i++) {
4760                     pw.print(prefix); pw.print("    "); pw.println(usesLibraryFiles.get(i));
4761                 }
4762             }
4763             final Map<String, ParsedProcess> procs = pkg.getProcesses();
4764             if (!procs.isEmpty()) {
4765                 pw.print(prefix); pw.println("  processes:");
4766                 for (ParsedProcess proc : procs.values()) {
4767                     pw.print(prefix); pw.print("    "); pw.println(proc.getName());
4768                     if (proc.getDeniedPermissions() != null) {
4769                         for (String deniedPermission : proc.getDeniedPermissions()) {
4770                             pw.print(prefix); pw.print("      deny: ");
4771                             pw.println(deniedPermission);
4772                         }
4773                     }
4774                 }
4775             }
4776         }
4777         pw.print(prefix); pw.print("  timeStamp=");
4778             date.setTime(ps.getLastModifiedTime());
4779             pw.println(sdf.format(date));
4780         pw.print(prefix); pw.print("  lastUpdateTime=");
4781             date.setTime(ps.getLastUpdateTime());
4782             pw.println(sdf.format(date));
4783         if (ps.getInstallSource().installerPackageName != null) {
4784             pw.print(prefix); pw.print("  installerPackageName=");
4785             pw.println(ps.getInstallSource().installerPackageName);
4786         }
4787         if (ps.getInstallSource().installerAttributionTag != null) {
4788             pw.print(prefix); pw.print("  installerAttributionTag=");
4789             pw.println(ps.getInstallSource().installerAttributionTag);
4790         }
4791         pw.print(prefix); pw.print("  packageSource=");
4792         pw.println(ps.getInstallSource().packageSource);
4793         if (ps.isLoading()) {
4794             pw.print(prefix); pw.println("  loadingProgress=" +
4795                     (int) (ps.getLoadingProgress() * 100) + "%");
4796         }
4797         if (ps.getVolumeUuid() != null) {
4798             pw.print(prefix); pw.print("  volumeUuid=");
4799                     pw.println(ps.getVolumeUuid());
4800         }
4801         pw.print(prefix); pw.print("  signatures="); pw.println(ps.getSignatures());
4802         pw.print(prefix); pw.print("  installPermissionsFixed=");
4803                 pw.print(ps.isInstallPermissionsFixed());
4804                 pw.println();
4805         pw.print(prefix); pw.print("  pkgFlags="); printFlags(pw, ps.getFlags(), FLAG_DUMP_SPEC);
4806                 pw.println();
4807 
4808         if (pkg != null && pkg.getOverlayTarget() != null) {
4809             pw.print(prefix); pw.print("  overlayTarget="); pw.println(pkg.getOverlayTarget());
4810             pw.print(prefix); pw.print("  overlayCategory="); pw.println(pkg.getOverlayCategory());
4811         }
4812 
4813         if (pkg != null && !pkg.getPermissions().isEmpty()) {
4814             final List<ParsedPermission> perms = pkg.getPermissions();
4815             pw.print(prefix); pw.println("  declared permissions:");
4816             for (int i=0; i<perms.size(); i++) {
4817                 ParsedPermission perm = perms.get(i);
4818                 if (permissionNames != null
4819                         && !permissionNames.contains(perm.getName())) {
4820                     continue;
4821                 }
4822                 pw.print(prefix); pw.print("    "); pw.print(perm.getName());
4823                 pw.print(": prot=");
4824                 pw.print(PermissionInfo.protectionToString(perm.getProtectionLevel()));
4825                 if ((perm.getFlags() &PermissionInfo.FLAG_COSTS_MONEY) != 0) {
4826                     pw.print(", COSTS_MONEY");
4827                 }
4828                 if ((perm.getFlags() &PermissionInfo.FLAG_REMOVED) != 0) {
4829                     pw.print(", HIDDEN");
4830                 }
4831                 if ((perm.getFlags() &PermissionInfo.FLAG_INSTALLED) != 0) {
4832                     pw.print(", INSTALLED");
4833                 }
4834                 pw.println();
4835             }
4836         }
4837 
4838         if ((permissionNames != null || dumpAll) && pkg != null
4839                 && pkg.getRequestedPermissions() != null
4840                 && pkg.getRequestedPermissions().size() > 0) {
4841             final List<String> perms = pkg.getRequestedPermissions();
4842             pw.print(prefix); pw.println("  requested permissions:");
4843             for (int i=0; i<perms.size(); i++) {
4844                 String perm = perms.get(i);
4845                 if (permissionNames != null
4846                         && !permissionNames.contains(perm)) {
4847                     continue;
4848                 }
4849                 pw.print(prefix); pw.print("    "); pw.println(perm);
4850             }
4851         }
4852 
4853         if (!ps.hasSharedUser() || permissionNames != null || dumpAll) {
4854             dumpInstallPermissionsLPr(pw, prefix + "  ", permissionNames, permissionsState, users);
4855         }
4856 
4857         if (dumpAllComponents) {
4858             dumpComponents(pw, prefix + "  ", ps);
4859         }
4860 
4861         for (UserInfo user : users) {
4862             final PackageUserStateInternal userState = ps.getUserStateOrDefault(user.id);
4863             pw.print(prefix); pw.print("  User "); pw.print(user.id); pw.print(": ");
4864             pw.print("ceDataInode=");
4865             pw.print(userState.getCeDataInode());
4866             pw.print(" installed=");
4867             pw.print(userState.isInstalled());
4868             pw.print(" hidden=");
4869             pw.print(userState.isHidden());
4870             pw.print(" suspended=");
4871             pw.print(userState.isSuspended());
4872             pw.print(" distractionFlags=");
4873             pw.print(userState.getDistractionFlags());
4874             pw.print(" stopped=");
4875             pw.print(userState.isStopped());
4876             pw.print(" notLaunched=");
4877             pw.print(userState.isNotLaunched());
4878             pw.print(" enabled=");
4879             pw.print(userState.getEnabledState());
4880             pw.print(" instant=");
4881             pw.print(userState.isInstantApp());
4882             pw.print(" virtual=");
4883             pw.println(userState.isVirtualPreload());
4884             pw.print("      installReason=");
4885             pw.println(userState.getInstallReason());
4886 
4887             final PackageUserStateInternal pus = ps.readUserState(user.id);
4888             pw.print("      firstInstallTime=");
4889             date.setTime(pus.getFirstInstallTime());
4890             pw.println(sdf.format(date));
4891 
4892             pw.print("      uninstallReason=");
4893             pw.println(userState.getUninstallReason());
4894 
4895             if (userState.isSuspended()) {
4896                 pw.print(prefix);
4897                 pw.println("  Suspend params:");
4898                 for (int i = 0; i < userState.getSuspendParams().size(); i++) {
4899                     pw.print(prefix);
4900                     pw.print("    suspendingPackage=");
4901                     pw.print(userState.getSuspendParams().keyAt(i));
4902                     final SuspendParams params = userState.getSuspendParams().valueAt(i);
4903                     if (params != null) {
4904                         pw.print(" dialogInfo=");
4905                         pw.print(params.getDialogInfo());
4906                     }
4907                     pw.println();
4908                 }
4909             }
4910 
4911             final OverlayPaths overlayPaths = userState.getOverlayPaths();
4912             if (overlayPaths != null) {
4913                 if (!overlayPaths.getOverlayPaths().isEmpty()) {
4914                     pw.print(prefix);
4915                     pw.println("    overlay paths:");
4916                     for (String path : overlayPaths.getOverlayPaths()) {
4917                         pw.print(prefix);
4918                         pw.print("      ");
4919                         pw.println(path);
4920                     }
4921                 }
4922                 if (!overlayPaths.getResourceDirs().isEmpty()) {
4923                     pw.print(prefix);
4924                     pw.println("    legacy overlay paths:");
4925                     for (String path : overlayPaths.getResourceDirs()) {
4926                         pw.print(prefix);
4927                         pw.print("      ");
4928                         pw.println(path);
4929                     }
4930                 }
4931             }
4932 
4933             final Map<String, OverlayPaths> sharedLibraryOverlayPaths =
4934                     userState.getSharedLibraryOverlayPaths();
4935             if (sharedLibraryOverlayPaths != null) {
4936                 for (Map.Entry<String, OverlayPaths> libOverlayPaths :
4937                         sharedLibraryOverlayPaths.entrySet()) {
4938                     final OverlayPaths paths = libOverlayPaths.getValue();
4939                     if (paths == null) {
4940                         continue;
4941                     }
4942                     if (!paths.getOverlayPaths().isEmpty()) {
4943                         pw.print(prefix);
4944                         pw.println("    ");
4945                         pw.print(libOverlayPaths.getKey());
4946                         pw.println(" overlay paths:");
4947                         for (String path : paths.getOverlayPaths()) {
4948                             pw.print(prefix);
4949                             pw.print("        ");
4950                             pw.println(path);
4951                         }
4952                     }
4953                     if (!paths.getResourceDirs().isEmpty()) {
4954                         pw.print(prefix);
4955                         pw.println("      ");
4956                         pw.print(libOverlayPaths.getKey());
4957                         pw.println(" legacy overlay paths:");
4958                         for (String path : paths.getResourceDirs()) {
4959                             pw.print(prefix);
4960                             pw.print("      ");
4961                             pw.println(path);
4962                         }
4963                     }
4964                 }
4965             }
4966 
4967             String lastDisabledAppCaller = userState.getLastDisableAppCaller();
4968             if (lastDisabledAppCaller != null) {
4969                 pw.print(prefix); pw.print("    lastDisabledCaller: ");
4970                         pw.println(lastDisabledAppCaller);
4971             }
4972 
4973             if (!ps.hasSharedUser()) {
4974                 dumpGidsLPr(pw, prefix + "    ", mPermissionDataProvider.getGidsForUid(
4975                         UserHandle.getUid(user.id, ps.getAppId())));
4976                 dumpRuntimePermissionsLPr(pw, prefix + "    ", permissionNames, permissionsState
4977                         .getPermissionStates(user.id), dumpAll);
4978             }
4979 
4980             String harmfulAppWarning = userState.getHarmfulAppWarning();
4981             if (harmfulAppWarning != null) {
4982                 pw.print(prefix); pw.print("      harmfulAppWarning: ");
4983                 pw.println(harmfulAppWarning);
4984             }
4985 
4986             if (permissionNames == null) {
4987                 WatchedArraySet<String> cmp = userState.getDisabledComponentsNoCopy();
4988                 if (cmp != null && cmp.size() > 0) {
4989                     pw.print(prefix); pw.println("    disabledComponents:");
4990                     for (int i = 0; i < cmp.size(); i++) {
4991                         pw.print(prefix); pw.print("      "); pw.println(cmp.valueAt(i));
4992                     }
4993                 }
4994                 cmp = userState.getEnabledComponentsNoCopy();
4995                 if (cmp != null && cmp.size() > 0) {
4996                     pw.print(prefix); pw.println("    enabledComponents:");
4997                     for (int i = 0; i < cmp.size(); i++) {
4998                         pw.print(prefix); pw.print("      "); pw.println(cmp.valueAt(i));
4999                     }
5000                 }
5001             }
5002         }
5003     }
5004 
5005     void dumpPackagesLPr(PrintWriter pw, String packageName, ArraySet<String> permissionNames,
5006             DumpState dumpState, boolean checkin) {
5007         final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
5008         final Date date = new Date();
5009         boolean printedSomething = false;
5010         final boolean dumpAllComponents =
5011                 dumpState.isOptionEnabled(DumpState.OPTION_DUMP_ALL_COMPONENTS);
5012         List<UserInfo> users = getAllUsers(UserManagerService.getInstance());
5013         for (final PackageSetting ps : mPackages.values()) {
5014             if (packageName != null && !packageName.equals(ps.getRealName())
5015                     && !packageName.equals(ps.getPackageName())) {
5016                 continue;
5017             }
5018             final LegacyPermissionState permissionsState =
5019                     mPermissionDataProvider.getLegacyPermissionState(ps.getAppId());
5020             if (permissionNames != null
5021                     && !permissionsState.hasPermissionState(permissionNames)) {
5022                 continue;
5023             }
5024 
5025             if (!checkin && packageName != null) {
5026                 dumpState.setSharedUser(getSharedUserSettingLPr(ps));
5027             }
5028 
5029             if (!checkin && !printedSomething) {
5030                 if (dumpState.onTitlePrinted())
5031                     pw.println();
5032                 pw.println("Packages:");
5033                 printedSomething = true;
5034             }
5035             dumpPackageLPr(pw, "  ", checkin ? "pkg" : null, permissionNames, ps, permissionsState,
5036                     sdf, date, users, packageName != null, dumpAllComponents);
5037         }
5038 
5039         printedSomething = false;
5040         if (mRenamedPackages.size() > 0 && permissionNames == null) {
5041             for (final Map.Entry<String, String> e : mRenamedPackages.entrySet()) {
5042                 if (packageName != null && !packageName.equals(e.getKey())
5043                         && !packageName.equals(e.getValue())) {
5044                     continue;
5045                 }
5046                 if (!checkin) {
5047                     if (!printedSomething) {
5048                         if (dumpState.onTitlePrinted())
5049                             pw.println();
5050                         pw.println("Renamed packages:");
5051                         printedSomething = true;
5052                     }
5053                     pw.print("  ");
5054                 } else {
5055                     pw.print("ren,");
5056                 }
5057                 pw.print(e.getKey());
5058                 pw.print(checkin ? " -> " : ",");
5059                 pw.println(e.getValue());
5060             }
5061         }
5062 
5063         printedSomething = false;
5064         if (mDisabledSysPackages.size() > 0 && permissionNames == null) {
5065             for (final PackageSetting ps : mDisabledSysPackages.values()) {
5066                 if (packageName != null && !packageName.equals(ps.getRealName())
5067                         && !packageName.equals(ps.getPackageName())) {
5068                     continue;
5069                 }
5070                 if (!checkin && !printedSomething) {
5071                     if (dumpState.onTitlePrinted())
5072                         pw.println();
5073                     pw.println("Hidden system packages:");
5074                     printedSomething = true;
5075                 }
5076                 final LegacyPermissionState permissionsState =
5077                         mPermissionDataProvider.getLegacyPermissionState(ps.getAppId());
5078                 dumpPackageLPr(pw, "  ", checkin ? "dis" : null, permissionNames, ps,
5079                         permissionsState, sdf, date, users, packageName != null, dumpAllComponents);
5080             }
5081         }
5082     }
5083 
5084     void dumpPackagesProto(ProtoOutputStream proto) {
5085         List<UserInfo> users = getAllUsers(UserManagerService.getInstance());
5086 
5087         final int count = mPackages.size();
5088         for (int i = 0; i < count; i++) {
5089             final PackageSetting ps = mPackages.valueAt(i);
5090             ps.dumpDebug(proto, PackageServiceDumpProto.PACKAGES, users, mPermissionDataProvider);
5091         }
5092     }
5093 
5094     void dumpPermissions(PrintWriter pw, String packageName, ArraySet<String> permissionNames,
5095             DumpState dumpState) {
5096         LegacyPermissionSettings.dumpPermissions(pw, packageName, permissionNames,
5097                 mPermissionDataProvider.getLegacyPermissions(),
5098                 mPermissionDataProvider.getAllAppOpPermissionPackages(), true, dumpState);
5099     }
5100 
5101     void dumpSharedUsersLPr(PrintWriter pw, String packageName, ArraySet<String> permissionNames,
5102             DumpState dumpState, boolean checkin) {
5103         boolean printedSomething = false;
5104         for (SharedUserSetting su : mSharedUsers.values()) {
5105             if (packageName != null && su != dumpState.getSharedUser()) {
5106                 continue;
5107             }
5108             final LegacyPermissionState permissionsState =
5109                     mPermissionDataProvider.getLegacyPermissionState(su.mAppId);
5110             if (permissionNames != null
5111                     && !permissionsState.hasPermissionState(permissionNames)) {
5112                 continue;
5113             }
5114             if (!checkin) {
5115                 if (!printedSomething) {
5116                     if (dumpState.onTitlePrinted())
5117                         pw.println();
5118                     pw.println("Shared users:");
5119                     printedSomething = true;
5120                 }
5121 
5122                 pw.print("  SharedUser [");
5123                 pw.print(su.name);
5124                 pw.print("] (");
5125                 pw.print(Integer.toHexString(System.identityHashCode(su)));
5126                 pw.println("):");
5127 
5128                 String prefix = "    ";
5129                 pw.print(prefix); pw.print("userId="); pw.println(su.mAppId);
5130 
5131                 pw.print(prefix); pw.println("Packages");
5132                 final ArraySet<PackageStateInternal> susPackageStates =
5133                         (ArraySet<PackageStateInternal>) su.getPackageStates();
5134                 final int numPackages = susPackageStates.size();
5135                 for (int i = 0; i < numPackages; i++) {
5136                     final PackageStateInternal ps = susPackageStates.valueAt(i);
5137                     if (ps != null) {
5138                         pw.print(prefix + "  "); pw.println(ps);
5139                     } else {
5140                         pw.print(prefix + "  "); pw.println("NULL?!");
5141                     }
5142                 }
5143 
5144                 if (dumpState.isOptionEnabled(DumpState.OPTION_SKIP_PERMISSIONS)) {
5145                     continue;
5146                 }
5147 
5148                 List<UserInfo> users = getAllUsers(UserManagerService.getInstance());
5149 
5150                 dumpInstallPermissionsLPr(pw, prefix, permissionNames, permissionsState, users);
5151 
5152                 for (UserInfo user : users) {
5153                     final int userId = user.id;
5154                     final int[] gids = mPermissionDataProvider.getGidsForUid(UserHandle.getUid(
5155                             userId, su.mAppId));
5156                     final Collection<PermissionState> permissions =
5157                             permissionsState.getPermissionStates(userId);
5158                     if (!ArrayUtils.isEmpty(gids) || !permissions.isEmpty()) {
5159                         pw.print(prefix); pw.print("User "); pw.print(userId); pw.println(": ");
5160                         dumpGidsLPr(pw, prefix + "  ", gids);
5161                         dumpRuntimePermissionsLPr(pw, prefix + "  ", permissionNames,
5162                                 permissions, packageName != null);
5163                     }
5164                 }
5165             } else {
5166                 pw.print("suid,"); pw.print(su.mAppId); pw.print(","); pw.println(su.name);
5167             }
5168         }
5169     }
5170 
5171     void dumpSharedUsersProto(ProtoOutputStream proto) {
5172         final int count = mSharedUsers.size();
5173         for (int i = 0; i < count; i++) {
5174             mSharedUsers.valueAt(i).dumpDebug(proto, PackageServiceDumpProto.SHARED_USERS);
5175         }
5176     }
5177 
5178     void dumpReadMessages(PrintWriter pw, DumpState dumpState) {
5179         pw.println("Settings parse messages:");
5180         pw.print(mReadMessages.toString());
5181     }
5182 
5183     private static void dumpSplitNames(PrintWriter pw, AndroidPackage pkg) {
5184         if (pkg == null) {
5185             pw.print("unknown");
5186         } else {
5187             // [base:10, config.mdpi, config.xhdpi:12]
5188             pw.print("[");
5189             pw.print("base");
5190             if (pkg.getBaseRevisionCode() != 0) {
5191                 pw.print(":"); pw.print(pkg.getBaseRevisionCode());
5192             }
5193             String[] splitNames = pkg.getSplitNames();
5194             int[] splitRevisionCodes = pkg.getSplitRevisionCodes();
5195             for (int i = 0; i < splitNames.length; i++) {
5196                 pw.print(", ");
5197                 pw.print(splitNames[i]);
5198                 if (splitRevisionCodes[i] != 0) {
5199                     pw.print(":"); pw.print(splitRevisionCodes[i]);
5200                 }
5201             }
5202             pw.print("]");
5203         }
5204     }
5205 
5206     void dumpGidsLPr(PrintWriter pw, String prefix, int[] gids) {
5207         if (!ArrayUtils.isEmpty(gids)) {
5208             pw.print(prefix);
5209             pw.print("gids="); pw.println(
5210                     PackageManagerServiceUtils.arrayToString(gids));
5211         }
5212     }
5213 
5214     void dumpRuntimePermissionsLPr(PrintWriter pw, String prefix, ArraySet<String> permissionNames,
5215             Collection<PermissionState> permissionStates, boolean dumpAll) {
5216         boolean hasRuntimePermissions = false;
5217         for (PermissionState permissionState : permissionStates) {
5218             if (permissionState.isRuntime()) {
5219                 hasRuntimePermissions = true;
5220                 break;
5221             }
5222         }
5223         if (hasRuntimePermissions || dumpAll) {
5224             pw.print(prefix); pw.println("runtime permissions:");
5225             for (PermissionState permissionState : permissionStates) {
5226                 if (!permissionState.isRuntime()) {
5227                     continue;
5228                 }
5229                 if (permissionNames != null
5230                         && !permissionNames.contains(permissionState.getName())) {
5231                     continue;
5232                 }
5233                 pw.print(prefix); pw.print("  "); pw.print(permissionState.getName());
5234                 pw.print(": granted="); pw.print(permissionState.isGranted());
5235                     pw.println(permissionFlagsToString(", flags=",
5236                             permissionState.getFlags()));
5237             }
5238         }
5239     }
5240 
5241     private static String permissionFlagsToString(String prefix, int flags) {
5242         StringBuilder flagsString = null;
5243         while (flags != 0) {
5244             if (flagsString == null) {
5245                 flagsString = new StringBuilder();
5246                 flagsString.append(prefix);
5247                 flagsString.append("[ ");
5248             }
5249             final int flag = 1 << Integer.numberOfTrailingZeros(flags);
5250             flags &= ~flag;
5251             flagsString.append(PackageManager.permissionFlagToString(flag));
5252             if (flags != 0) {
5253                 flagsString.append('|');
5254             }
5255 
5256         }
5257         if (flagsString != null) {
5258             flagsString.append(']');
5259             return flagsString.toString();
5260         } else {
5261             return "";
5262         }
5263     }
5264 
5265     void dumpInstallPermissionsLPr(PrintWriter pw, String prefix,
5266             ArraySet<String> filterPermissionNames, LegacyPermissionState permissionsState,
5267             List<UserInfo> users) {
5268         ArraySet<String> dumpPermissionNames = new ArraySet<>();
5269         for (UserInfo user : users) {
5270             int userId = user.id;
5271             Collection<PermissionState> permissionStates = permissionsState.getPermissionStates(
5272                     userId);
5273             for (PermissionState permissionState : permissionStates) {
5274                 if (permissionState.isRuntime()) {
5275                     continue;
5276                 }
5277                 String permissionName = permissionState.getName();
5278                 if (filterPermissionNames != null
5279                         && !filterPermissionNames.contains(permissionName)) {
5280                     continue;
5281                 }
5282                 dumpPermissionNames.add(permissionName);
5283             }
5284         }
5285         boolean printedSomething = false;
5286         for (String permissionName : dumpPermissionNames) {
5287             PermissionState systemPermissionState = permissionsState.getPermissionState(
5288                     permissionName, UserHandle.USER_SYSTEM);
5289             for (UserInfo user : users) {
5290                 int userId = user.id;
5291                 PermissionState permissionState;
5292                 if (userId == UserHandle.USER_SYSTEM) {
5293                     permissionState = systemPermissionState;
5294                 } else {
5295                     permissionState = permissionsState.getPermissionState(permissionName, userId);
5296                     if (Objects.equals(permissionState, systemPermissionState)) {
5297                         continue;
5298                     }
5299                 }
5300                 if (!printedSomething) {
5301                     pw.print(prefix); pw.println("install permissions:");
5302                     printedSomething = true;
5303                 }
5304                 pw.print(prefix); pw.print("  "); pw.print(permissionName);
5305                 pw.print(": granted="); pw.print(
5306                         permissionState != null && permissionState.isGranted());
5307                 pw.print(permissionFlagsToString(", flags=",
5308                         permissionState != null ? permissionState.getFlags() : 0));
5309                 if (userId == UserHandle.USER_SYSTEM) {
5310                     pw.println();
5311                 } else {
5312                     pw.print(", userId="); pw.println(userId);
5313                 }
5314             }
5315         }
5316     }
5317 
5318     void dumpComponents(PrintWriter pw, String prefix, PackageSetting ps) {
5319         dumpComponents(pw, prefix, "activities:", ps.getPkg().getActivities());
5320         dumpComponents(pw, prefix, "services:", ps.getPkg().getServices());
5321         dumpComponents(pw, prefix, "receivers:", ps.getPkg().getReceivers());
5322         dumpComponents(pw, prefix, "providers:", ps.getPkg().getProviders());
5323         dumpComponents(pw, prefix, "instrumentations:", ps.getPkg().getInstrumentations());
5324     }
5325 
5326     void dumpComponents(PrintWriter pw, String prefix, String label,
5327             List<? extends ParsedComponent> list) {
5328         final int size = CollectionUtils.size(list);
5329         if (size == 0) {
5330             return;
5331         }
5332         pw.print(prefix);pw.println(label);
5333         for (int i = 0; i < size; i++) {
5334             final ParsedComponent component = list.get(i);
5335             pw.print(prefix);pw.print("  ");
5336             pw.println(component.getComponentName().flattenToShortString());
5337         }
5338     }
5339 
5340     public void writePermissionStateForUserLPr(int userId, boolean sync) {
5341         if (sync) {
5342             mRuntimePermissionsPersistence.writeStateForUser(userId, mPermissionDataProvider,
5343                     mPackages, mSharedUsers, /*handler=*/null, mLock, /*sync=*/true);
5344         } else {
5345             mRuntimePermissionsPersistence.writeStateForUserAsync(userId);
5346         }
5347     }
5348 
5349     private static class KeySetToValueMap<K, V> implements Map<K, V> {
5350         @NonNull
5351         private final Set<K> mKeySet;
5352         private final V mValue;
5353 
5354         KeySetToValueMap(@NonNull Set<K> keySet, V value) {
5355             mKeySet = keySet;
5356             mValue = value;
5357         }
5358 
5359         @Override
5360         public int size() {
5361             return mKeySet.size();
5362         }
5363 
5364         @Override
5365         public boolean isEmpty() {
5366             return mKeySet.isEmpty();
5367         }
5368 
5369         @Override
5370         public boolean containsKey(Object key) {
5371             return mKeySet.contains(key);
5372         }
5373 
5374         @Override
5375         public boolean containsValue(Object value) {
5376             return mValue == value;
5377         }
5378 
5379         @Override
5380         public V get(Object key) {
5381             return mValue;
5382         }
5383 
5384         @Override
5385         public V put(K key, V value) {
5386             throw new UnsupportedOperationException();
5387         }
5388 
5389         @Override
5390         public V remove(Object key) {
5391             throw new UnsupportedOperationException();
5392         }
5393 
5394         @Override
5395         public void putAll(Map<? extends K, ? extends V> m) {
5396             throw new UnsupportedOperationException();
5397         }
5398 
5399         @Override
5400         public void clear() {
5401             throw new UnsupportedOperationException();
5402         }
5403 
5404         @Override
5405         public Set<K> keySet() {
5406             return mKeySet;
5407         }
5408 
5409         @Override
5410         public Collection<V> values() {
5411             throw new UnsupportedOperationException();
5412         }
5413 
5414         @Override
5415         public Set<Entry<K, V>> entrySet() {
5416             throw new UnsupportedOperationException();
5417         }
5418     }
5419 
5420     private static final class RuntimePermissionPersistence {
5421         // 200-400ms delay to avoid monopolizing PMS lock when written for multiple users.
5422         private static final long WRITE_PERMISSIONS_DELAY_MILLIS = 300;
5423         private static final double WRITE_PERMISSIONS_DELAY_JITTER = 0.3;
5424 
5425         private static final long MAX_WRITE_PERMISSIONS_DELAY_MILLIS = 2000;
5426 
5427         private static final int UPGRADE_VERSION = -1;
5428         private static final int INITIAL_VERSION = 0;
5429 
5430         private static final Random sRandom = new Random();
5431 
5432         private String mExtendedFingerprint;
5433 
5434         @GuardedBy("mPersistenceLock")
5435         private final RuntimePermissionsPersistence mPersistence;
5436         private final Object mPersistenceLock = new Object();
5437 
5438         // Low-priority handlers running on SystemBg thread.
5439         private final Handler mAsyncHandler = new MyHandler();
5440         private final Handler mPersistenceHandler = new Handler(
5441                 BackgroundThread.getHandler().getLooper());
5442 
5443         private final Object mLock = new Object();
5444 
5445         @GuardedBy("mLock")
5446         private final SparseBooleanArray mWriteScheduled = new SparseBooleanArray();
5447 
5448         @GuardedBy("mLock")
5449         // The mapping keys are user ids.
5450         private final SparseLongArray mLastNotWrittenMutationTimesMillis = new SparseLongArray();
5451 
5452         @GuardedBy("mLock")
5453         // Tracking the mutations that haven't yet been written to legacy state.
5454         // This avoids unnecessary work when writing settings for multiple users.
5455         private boolean mIsLegacyPermissionStateStale = false;
5456 
5457         @GuardedBy("mLock")
5458         // The mapping keys are user ids.
5459         private final SparseIntArray mVersions = new SparseIntArray();
5460 
5461         @GuardedBy("mLock")
5462         // The mapping keys are user ids.
5463         private final SparseArray<String> mFingerprints = new SparseArray<>();
5464 
5465         @GuardedBy("mLock")
5466         // The mapping keys are user ids.
5467         private final SparseBooleanArray mPermissionUpgradeNeeded = new SparseBooleanArray();
5468 
5469         @GuardedBy("mLock")
5470         // Staging area for states prepared to be written.
5471         private final SparseArray<RuntimePermissionsState> mPendingStatesToWrite =
5472                 new SparseArray<>();
5473 
5474         // This is a hack to allow this class to invoke a write using Settings's data structures,
5475         // to facilitate moving to a finer scoped lock without a significant refactor.
5476         private final Consumer<Integer> mInvokeWriteUserStateAsyncCallback;
5477 
5478         public RuntimePermissionPersistence(RuntimePermissionsPersistence persistence,
5479                 Consumer<Integer> invokeWriteUserStateAsyncCallback) {
5480             mPersistence = persistence;
5481             mInvokeWriteUserStateAsyncCallback = invokeWriteUserStateAsyncCallback;
5482         }
5483 
5484         int getVersion(int userId) {
5485             synchronized (mLock) {
5486                 return mVersions.get(userId, INITIAL_VERSION);
5487             }
5488         }
5489 
5490         void setVersion(int version, int userId) {
5491             synchronized (mLock) {
5492                 mVersions.put(userId, version);
5493                 writeStateForUserAsync(userId);
5494             }
5495         }
5496 
5497         public boolean isPermissionUpgradeNeeded(int userId) {
5498             synchronized (mLock) {
5499                 return mPermissionUpgradeNeeded.get(userId, true);
5500             }
5501         }
5502 
5503         public void updateRuntimePermissionsFingerprint(@UserIdInt int userId) {
5504             synchronized (mLock) {
5505                 if (mExtendedFingerprint == null) {
5506                     throw new RuntimeException(
5507                             "The version of the permission controller hasn't been "
5508                                     + "set before trying to update the fingerprint.");
5509                 }
5510                 mFingerprints.put(userId, mExtendedFingerprint);
5511                 writeStateForUserAsync(userId);
5512             }
5513         }
5514 
5515         public void setPermissionControllerVersion(long version) {
5516             synchronized (mLock) {
5517                 int numUser = mFingerprints.size();
5518                 mExtendedFingerprint = getExtendedFingerprint(version);
5519 
5520                 for (int i = 0; i < numUser; i++) {
5521                     int userId = mFingerprints.keyAt(i);
5522                     String fingerprint = mFingerprints.valueAt(i);
5523                     mPermissionUpgradeNeeded.put(userId,
5524                             !TextUtils.equals(mExtendedFingerprint, fingerprint));
5525                 }
5526             }
5527         }
5528 
5529         private String getExtendedFingerprint(long version) {
5530             return PackagePartitions.FINGERPRINT + "?pc_version=" + version;
5531         }
5532 
5533         private static long uniformRandom(double low, double high) {
5534             double mag = high - low;
5535             return (long) (sRandom.nextDouble() * mag + low);
5536         }
5537 
5538         private static long nextWritePermissionDelayMillis() {
5539             final long delay = WRITE_PERMISSIONS_DELAY_MILLIS;
5540             final double jitter = WRITE_PERMISSIONS_DELAY_JITTER;
5541             return delay + uniformRandom(-jitter * delay, jitter * delay);
5542         }
5543 
5544         public void writeStateForUserAsync(int userId) {
5545             synchronized (mLock) {
5546                 mIsLegacyPermissionStateStale = true;
5547                 final long currentTimeMillis = SystemClock.uptimeMillis();
5548                 final long writePermissionDelayMillis = nextWritePermissionDelayMillis();
5549 
5550                 if (mWriteScheduled.get(userId)) {
5551                     mAsyncHandler.removeMessages(userId);
5552 
5553                     // If enough time passed, write without holding off anymore.
5554                     final long lastNotWrittenMutationTimeMillis = mLastNotWrittenMutationTimesMillis
5555                             .get(userId);
5556                     final long timeSinceLastNotWrittenMutationMillis = currentTimeMillis
5557                             - lastNotWrittenMutationTimeMillis;
5558                     if (timeSinceLastNotWrittenMutationMillis
5559                             >= MAX_WRITE_PERMISSIONS_DELAY_MILLIS) {
5560                         mAsyncHandler.obtainMessage(userId).sendToTarget();
5561                         return;
5562                     }
5563 
5564                     // Hold off a bit more as settings are frequently changing.
5565                     final long maxDelayMillis = Math.max(lastNotWrittenMutationTimeMillis
5566                             + MAX_WRITE_PERMISSIONS_DELAY_MILLIS - currentTimeMillis, 0);
5567                     final long writeDelayMillis = Math.min(writePermissionDelayMillis,
5568                             maxDelayMillis);
5569 
5570                     Message message = mAsyncHandler.obtainMessage(userId);
5571                     mAsyncHandler.sendMessageDelayed(message, writeDelayMillis);
5572                 } else {
5573                     mLastNotWrittenMutationTimesMillis.put(userId, currentTimeMillis);
5574                     Message message = mAsyncHandler.obtainMessage(userId);
5575                     mAsyncHandler.sendMessageDelayed(message, writePermissionDelayMillis);
5576                     mWriteScheduled.put(userId, true);
5577                 }
5578             }
5579         }
5580 
5581         public void writeStateForUser(int userId, @NonNull LegacyPermissionDataProvider
5582                 legacyPermissionDataProvider,
5583                 @NonNull WatchedArrayMap<String, ? extends PackageStateInternal> packageStates,
5584                 @NonNull WatchedArrayMap<String, SharedUserSetting> sharedUsers,
5585                 @Nullable Handler pmHandler, @NonNull Object pmLock,
5586                 boolean sync) {
5587             final int version;
5588             final String fingerprint;
5589             final boolean isLegacyPermissionStateStale;
5590             synchronized (mLock) {
5591                 mAsyncHandler.removeMessages(userId);
5592                 mWriteScheduled.delete(userId);
5593 
5594                 version = mVersions.get(userId, INITIAL_VERSION);
5595                 fingerprint = mFingerprints.get(userId);
5596                 isLegacyPermissionStateStale = mIsLegacyPermissionStateStale;
5597                 mIsLegacyPermissionStateStale = false;
5598             }
5599 
5600             Runnable writer = () -> {
5601                 final RuntimePermissionsState runtimePermissions;
5602                 synchronized (pmLock) {
5603                     if (sync || isLegacyPermissionStateStale) {
5604                         legacyPermissionDataProvider.writeLegacyPermissionStateTEMP();
5605                     }
5606 
5607                     Map<String, List<RuntimePermissionsState.PermissionState>> packagePermissions =
5608                             new ArrayMap<>();
5609                     int packagesSize = packageStates.size();
5610                     for (int i = 0; i < packagesSize; i++) {
5611                         String packageName = packageStates.keyAt(i);
5612                         PackageStateInternal packageState = packageStates.valueAt(i);
5613                         if (!packageState.hasSharedUser()) {
5614                             List<RuntimePermissionsState.PermissionState> permissions =
5615                                     getPermissionsFromPermissionsState(
5616                                             packageState.getLegacyPermissionState(), userId);
5617                             if (permissions.isEmpty()
5618                                     && !packageState.isInstallPermissionsFixed()) {
5619                                 // Storing an empty state means the package is known to the
5620                                 // system and its install permissions have been granted and fixed.
5621                                 // If this is not the case, we should not store anything.
5622                                 continue;
5623                             }
5624                             packagePermissions.put(packageName, permissions);
5625                         }
5626                     }
5627 
5628                     Map<String, List<RuntimePermissionsState.PermissionState>>
5629                             sharedUserPermissions =
5630                             new ArrayMap<>();
5631                     final int sharedUsersSize = sharedUsers.size();
5632                     for (int i = 0; i < sharedUsersSize; i++) {
5633                         String sharedUserName = sharedUsers.keyAt(i);
5634                         SharedUserSetting sharedUserSetting = sharedUsers.valueAt(i);
5635                         List<RuntimePermissionsState.PermissionState> permissions =
5636                                 getPermissionsFromPermissionsState(
5637                                         sharedUserSetting.getLegacyPermissionState(), userId);
5638                         sharedUserPermissions.put(sharedUserName, permissions);
5639                     }
5640 
5641                     runtimePermissions = new RuntimePermissionsState(version,
5642                             fingerprint, packagePermissions, sharedUserPermissions);
5643                 }
5644                 synchronized (mLock) {
5645                     mPendingStatesToWrite.put(userId, runtimePermissions);
5646                 }
5647                 if (pmHandler != null) {
5648                     // Async version.
5649                     mPersistenceHandler.post(() -> writePendingStates());
5650                 } else {
5651                     // Sync version.
5652                     writePendingStates();
5653                 }
5654             };
5655 
5656             if (pmHandler != null) {
5657                 // Async version, use pmHandler.
5658                 pmHandler.post(writer);
5659             } else {
5660                 // Sync version, use caller's thread.
5661                 writer.run();
5662             }
5663         }
5664 
5665         private void writePendingStates() {
5666             while (true) {
5667                 final RuntimePermissionsState runtimePermissions;
5668                 final int userId;
5669                 synchronized (mLock) {
5670                     if (mPendingStatesToWrite.size() == 0) {
5671                         break;
5672                     }
5673                     userId = mPendingStatesToWrite.keyAt(0);
5674                     runtimePermissions = mPendingStatesToWrite.valueAt(0);
5675                     mPendingStatesToWrite.removeAt(0);
5676                 }
5677                 synchronized (mPersistenceLock) {
5678                     mPersistence.writeForUser(runtimePermissions, UserHandle.of(userId));
5679                 }
5680             }
5681         }
5682 
5683         @NonNull
5684         private List<RuntimePermissionsState.PermissionState> getPermissionsFromPermissionsState(
5685                 @NonNull LegacyPermissionState permissionsState, @UserIdInt int userId) {
5686             Collection<PermissionState> permissionStates =
5687                     permissionsState.getPermissionStates(userId);
5688             List<RuntimePermissionsState.PermissionState> permissions = new ArrayList<>();
5689             for (PermissionState permissionState : permissionStates) {
5690                 RuntimePermissionsState.PermissionState permission =
5691                         new RuntimePermissionsState.PermissionState(permissionState.getName(),
5692                                 permissionState.isGranted(), permissionState.getFlags());
5693                 permissions.add(permission);
5694             }
5695             return permissions;
5696         }
5697 
5698         private void onUserRemoved(int userId) {
5699             synchronized (mLock) {
5700                 // Make sure we do not
5701                 mAsyncHandler.removeMessages(userId);
5702 
5703                 mPermissionUpgradeNeeded.delete(userId);
5704                 mVersions.delete(userId);
5705                 mFingerprints.remove(userId);
5706             }
5707         }
5708 
5709         public void deleteUserRuntimePermissionsFile(int userId) {
5710             synchronized (mPersistenceLock) {
5711                 mPersistence.deleteForUser(UserHandle.of(userId));
5712             }
5713         }
5714 
5715         public void readStateForUserSync(int userId, @NonNull VersionInfo internalVersion,
5716                 @NonNull WatchedArrayMap<String, PackageSetting> packageSettings,
5717                 @NonNull WatchedArrayMap<String, SharedUserSetting> sharedUsers,
5718                 @NonNull File userRuntimePermissionsFile) {
5719             final RuntimePermissionsState runtimePermissions;
5720             synchronized (mPersistenceLock) {
5721                 runtimePermissions = mPersistence.readForUser(UserHandle.of(userId));
5722             }
5723             if (runtimePermissions == null) {
5724                 readLegacyStateForUserSync(userId, userRuntimePermissionsFile, packageSettings,
5725                         sharedUsers);
5726                 writeStateForUserAsync(userId);
5727                 return;
5728             }
5729             synchronized (mLock) {
5730                 // If the runtime permissions file exists but the version is not set this is
5731                 // an upgrade from P->Q. Hence mark it with the special UPGRADE_VERSION.
5732                 int version = runtimePermissions.getVersion();
5733                 if (version == RuntimePermissionsState.NO_VERSION) {
5734                     version = UPGRADE_VERSION;
5735                 }
5736                 mVersions.put(userId, version);
5737 
5738                 String fingerprint = runtimePermissions.getFingerprint();
5739                 mFingerprints.put(userId, fingerprint);
5740 
5741                 boolean isUpgradeToR = internalVersion.sdkVersion < Build.VERSION_CODES.R;
5742 
5743                 Map<String, List<RuntimePermissionsState.PermissionState>> packagePermissions =
5744                         runtimePermissions.getPackagePermissions();
5745                 int packagesSize = packageSettings.size();
5746                 for (int i = 0; i < packagesSize; i++) {
5747                     String packageName = packageSettings.keyAt(i);
5748                     PackageSetting packageSetting = packageSettings.valueAt(i);
5749 
5750                     List<RuntimePermissionsState.PermissionState> permissions =
5751                             packagePermissions.get(packageName);
5752                     if (permissions != null) {
5753                         readPermissionsState(permissions,
5754                                 packageSetting.getLegacyPermissionState(),
5755                                 userId);
5756                         packageSetting.setInstallPermissionsFixed(true);
5757                     } else if (!packageSetting.hasSharedUser() && !isUpgradeToR) {
5758                         Slogf.w(TAG, "Missing permission state for package %s on user %d",
5759                                 packageName, userId);
5760                         packageSetting.getLegacyPermissionState().setMissing(true, userId);
5761                     }
5762                 }
5763 
5764                 Map<String, List<RuntimePermissionsState.PermissionState>> sharedUserPermissions =
5765                         runtimePermissions.getSharedUserPermissions();
5766                 int sharedUsersSize = sharedUsers.size();
5767                 for (int i = 0; i < sharedUsersSize; i++) {
5768                     String sharedUserName = sharedUsers.keyAt(i);
5769                     SharedUserSetting sharedUserSetting = sharedUsers.valueAt(i);
5770 
5771                     List<RuntimePermissionsState.PermissionState> permissions =
5772                             sharedUserPermissions.get(sharedUserName);
5773                     if (permissions != null) {
5774                         readPermissionsState(permissions,
5775                                 sharedUserSetting.getLegacyPermissionState(), userId);
5776                     } else if (!isUpgradeToR) {
5777                         Slog.w(TAG, "Missing permission state for shared user: " + sharedUserName);
5778                         sharedUserSetting.getLegacyPermissionState().setMissing(true, userId);
5779                     }
5780                 }
5781             }
5782         }
5783 
5784         private void readPermissionsState(
5785                 @NonNull List<RuntimePermissionsState.PermissionState> permissions,
5786                 @NonNull LegacyPermissionState permissionsState, @UserIdInt int userId) {
5787             int permissionsSize = permissions.size();
5788             for (int i = 0; i < permissionsSize; i++) {
5789                 RuntimePermissionsState.PermissionState permission = permissions.get(i);
5790                 String name = permission.getName();
5791                 boolean granted = permission.isGranted();
5792                 int flags = permission.getFlags();
5793                 permissionsState.putPermissionState(new PermissionState(name, true, granted,
5794                         flags), userId);
5795             }
5796         }
5797 
5798         private void readLegacyStateForUserSync(int userId, @NonNull File permissionsFile,
5799                 @NonNull WatchedArrayMap<String, ? extends PackageStateInternal> packageStates,
5800                 @NonNull WatchedArrayMap<String, SharedUserSetting> sharedUsers) {
5801             synchronized (mLock) {
5802                 if (!permissionsFile.exists()) {
5803                     return;
5804                 }
5805 
5806                 FileInputStream in;
5807                 try {
5808                     in = new AtomicFile(permissionsFile).openRead();
5809                 } catch (FileNotFoundException fnfe) {
5810                     Slog.i(PackageManagerService.TAG, "No permissions state");
5811                     return;
5812                 }
5813 
5814                 try {
5815                     final TypedXmlPullParser parser = Xml.resolvePullParser(in);
5816                     parseLegacyRuntimePermissions(parser, userId, packageStates, sharedUsers);
5817 
5818                 } catch (XmlPullParserException | IOException e) {
5819                     throw new IllegalStateException("Failed parsing permissions file: "
5820                             + permissionsFile, e);
5821                 } finally {
5822                     IoUtils.closeQuietly(in);
5823                 }
5824             }
5825         }
5826 
5827         private void parseLegacyRuntimePermissions(TypedXmlPullParser parser, int userId,
5828                 @NonNull WatchedArrayMap<String, ? extends PackageStateInternal> packageStates,
5829                 @NonNull WatchedArrayMap<String, SharedUserSetting> sharedUsers)
5830                 throws IOException, XmlPullParserException {
5831             synchronized (mLock) {
5832                 final int outerDepth = parser.getDepth();
5833                 int type;
5834                 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
5835                         && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
5836                     if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
5837                         continue;
5838                     }
5839 
5840                     switch (parser.getName()) {
5841                         case TAG_RUNTIME_PERMISSIONS: {
5842                             // If the permisions settings file exists but the version is not set this is
5843                             // an upgrade from P->Q. Hence mark it with the special UPGRADE_VERSION
5844                             int version = parser.getAttributeInt(null, ATTR_VERSION,
5845                                     UPGRADE_VERSION);
5846                             mVersions.put(userId, version);
5847                             String fingerprint = parser.getAttributeValue(null, ATTR_FINGERPRINT);
5848                             mFingerprints.put(userId, fingerprint);
5849                         }
5850                         break;
5851 
5852                         case TAG_PACKAGE: {
5853                             String name = parser.getAttributeValue(null, ATTR_NAME);
5854                             PackageStateInternal ps = packageStates.get(name);
5855                             if (ps == null) {
5856                                 Slog.w(PackageManagerService.TAG, "Unknown package:" + name);
5857                                 XmlUtils.skipCurrentTag(parser);
5858                                 continue;
5859                             }
5860                             parseLegacyPermissionsLPr(parser, ps.getLegacyPermissionState(),
5861                                     userId);
5862                         }
5863                         break;
5864 
5865                         case TAG_SHARED_USER: {
5866                             String name = parser.getAttributeValue(null, ATTR_NAME);
5867                             SharedUserSetting sus = sharedUsers.get(name);
5868                             if (sus == null) {
5869                                 Slog.w(PackageManagerService.TAG, "Unknown shared user:" + name);
5870                                 XmlUtils.skipCurrentTag(parser);
5871                                 continue;
5872                             }
5873                             parseLegacyPermissionsLPr(parser, sus.getLegacyPermissionState(),
5874                                     userId);
5875                         }
5876                         break;
5877                     }
5878                 }
5879             }
5880         }
5881 
5882         private void parseLegacyPermissionsLPr(TypedXmlPullParser parser,
5883                 LegacyPermissionState permissionsState, int userId)
5884                 throws IOException, XmlPullParserException {
5885             synchronized (mLock) {
5886                 final int outerDepth = parser.getDepth();
5887                 int type;
5888                 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
5889                         && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
5890                     if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
5891                         continue;
5892                     }
5893 
5894                     switch (parser.getName()) {
5895                         case TAG_ITEM: {
5896                             String name = parser.getAttributeValue(null, ATTR_NAME);
5897                             final boolean granted =
5898                                     parser.getAttributeBoolean(null, ATTR_GRANTED, true);
5899                             final int flags =
5900                                     parser.getAttributeIntHex(null, ATTR_FLAGS, 0);
5901                             permissionsState.putPermissionState(new PermissionState(name, true,
5902                                     granted, flags), userId);
5903                         }
5904                         break;
5905                     }
5906                 }
5907             }
5908         }
5909 
5910         private final class MyHandler extends Handler {
5911             public MyHandler() {
5912                 super(BackgroundThread.getHandler().getLooper());
5913             }
5914 
5915             @Override
5916             public void handleMessage(Message message) {
5917                 final int userId = message.what;
5918                 Runnable callback = (Runnable) message.obj;
5919                 mInvokeWriteUserStateAsyncCallback.accept(userId);
5920                 if (callback != null) {
5921                     callback.run();
5922                 }
5923             }
5924         }
5925     }
5926 
5927     /**
5928      * Accessor for preferred activities
5929      */
5930     PersistentPreferredIntentResolver getPersistentPreferredActivities(int userId) {
5931         return mPersistentPreferredActivities.get(userId);
5932     }
5933 
5934     PreferredIntentResolver getPreferredActivities(int userId) {
5935         return mPreferredActivities.get(userId);
5936     }
5937 
5938     @Nullable
5939     CrossProfileIntentResolver getCrossProfileIntentResolver(int userId) {
5940         return mCrossProfileIntentResolvers.get(userId);
5941     }
5942 
5943     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
5944     void clearPackagePreferredActivities(String packageName,
5945             @NonNull SparseBooleanArray outUserChanged, int userId) {
5946         boolean changed = false;
5947         ArrayList<PreferredActivity> removed = null;
5948         for (int i = 0; i < mPreferredActivities.size(); i++) {
5949             final int thisUserId = mPreferredActivities.keyAt(i);
5950             PreferredIntentResolver pir = mPreferredActivities.valueAt(i);
5951             if (userId != UserHandle.USER_ALL && userId != thisUserId) {
5952                 continue;
5953             }
5954             Iterator<PreferredActivity> it = pir.filterIterator();
5955             while (it.hasNext()) {
5956                 PreferredActivity pa = it.next();
5957                 // Mark entry for removal only if it matches the package name
5958                 // and the entry is of type "always".
5959                 if (packageName == null
5960                         || (pa.mPref.mComponent.getPackageName().equals(packageName)
5961                                 && pa.mPref.mAlways)) {
5962                     if (removed == null) {
5963                         removed = new ArrayList<>();
5964                     }
5965                     removed.add(pa);
5966                 }
5967             }
5968             if (removed != null) {
5969                 for (int j = 0; j < removed.size(); j++) {
5970                     PreferredActivity pa = removed.get(j);
5971                     pir.removeFilter(pa);
5972                 }
5973                 outUserChanged.put(thisUserId, true);
5974                 changed = true;
5975             }
5976         }
5977         if (changed) {
5978             onChanged();
5979         }
5980     }
5981 
5982     boolean clearPackagePersistentPreferredActivities(String packageName, int userId) {
5983         ArrayList<PersistentPreferredActivity> removed = null;
5984         boolean changed = false;
5985         for (int i = 0; i < mPersistentPreferredActivities.size(); i++) {
5986             final int thisUserId = mPersistentPreferredActivities.keyAt(i);
5987             PersistentPreferredIntentResolver ppir = mPersistentPreferredActivities.valueAt(i);
5988             if (userId != thisUserId) {
5989                 continue;
5990             }
5991             Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
5992             while (it.hasNext()) {
5993                 PersistentPreferredActivity ppa = it.next();
5994                 // Mark entry for removal only if it matches the package name.
5995                 if (ppa.mComponent.getPackageName().equals(packageName)) {
5996                     if (removed == null) {
5997                         removed = new ArrayList<>();
5998                     }
5999                     removed.add(ppa);
6000                 }
6001             }
6002             if (removed != null) {
6003                 for (int j = 0; j < removed.size(); j++) {
6004                     PersistentPreferredActivity ppa = removed.get(j);
6005                     ppir.removeFilter(ppa);
6006                 }
6007                 changed = true;
6008             }
6009         }
6010         if (changed) {
6011             onChanged();
6012         }
6013         return changed;
6014     }
6015 
6016     ArrayList<Integer> systemReady(ComponentResolver resolver) {
6017         // Verify that all of the preferred activity components actually
6018         // exist.  It is possible for applications to be updated and at
6019         // that point remove a previously declared activity component that
6020         // had been set as a preferred activity.  We try to clean this up
6021         // the next time we encounter that preferred activity, but it is
6022         // possible for the user flow to never be able to return to that
6023         // situation so here we do a validity check to make sure we haven't
6024         // left any junk around.
6025         ArrayList<Integer> changed = new ArrayList<>();
6026         ArrayList<PreferredActivity> removed = new ArrayList<>();
6027         for (int i = 0; i < mPreferredActivities.size(); i++) {
6028             PreferredIntentResolver pir = mPreferredActivities.valueAt(i);
6029             removed.clear();
6030             for (PreferredActivity pa : pir.filterSet()) {
6031                 if (!resolver.isActivityDefined(pa.mPref.mComponent)) {
6032                     removed.add(pa);
6033                 }
6034             }
6035             if (removed.size() > 0) {
6036                 for (int r = 0; r < removed.size(); r++) {
6037                     PreferredActivity pa = removed.get(r);
6038                     Slog.w(TAG, "Removing dangling preferred activity: "
6039                             + pa.mPref.mComponent);
6040                     pir.removeFilter(pa);
6041                 }
6042                 changed.add(mPreferredActivities.keyAt(i));
6043             }
6044         }
6045         onChanged();
6046         return changed;
6047     }
6048 
6049     void dumpPreferred(PrintWriter pw, DumpState dumpState, String packageName) {
6050         for (int i = 0; i < mPreferredActivities.size(); i++) {
6051             PreferredIntentResolver pir = mPreferredActivities.valueAt(i);
6052             int user = mPreferredActivities.keyAt(i);
6053             if (pir.dump(pw,
6054                          dumpState.getTitlePrinted()
6055                          ? "\nPreferred Activities User " + user + ":"
6056                          : "Preferred Activities User " + user + ":", "  ",
6057                          packageName, true, false)) {
6058                 dumpState.setTitlePrinted(true);
6059             }
6060         }
6061     }
6062 
6063     boolean isInstallerPackage(@NonNull String packageName) {
6064         return mInstallerPackages.contains(packageName);
6065     }
6066 }
6067