blob: aced1a2adf66031a04907fb1b884c5c1824002ec [file] [log] [blame]
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001/*
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
17package com.android.server.pm;
18
19import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
20import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
Todd Kennedy13715d52016-08-01 13:38:57 -070022import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
Todd Kennedy3cd658e2016-08-16 15:00:31 -070023import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
Fabrice Di Meglio07885952015-04-06 19:41:28 -070024import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -080025import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070026import static android.content.pm.PackageManager.MATCH_DEFAULT_ONLY;
Jeff Sharkey184a0102013-07-10 16:19:52 -070027import static android.os.Process.PACKAGE_INFO_GID;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070028import static android.os.Process.SYSTEM_UID;
Jeff Sharkey2271ba32016-02-01 17:57:08 -070029
Christopher Tate72c10a22015-06-12 18:31:24 -070030import static com.android.server.pm.PackageManagerService.DEBUG_DOMAIN_VERIFICATION;
Suprabh Shukla021b57a2018-03-08 18:21:50 -080031import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070032
Xiaohui Chen594f2082015-08-18 11:04:20 -070033import android.annotation.NonNull;
Todd Kennedy13715d52016-08-01 13:38:57 -070034import android.annotation.Nullable;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070035import android.content.ComponentName;
36import android.content.Intent;
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080037import android.content.IntentFilter;
38import android.content.pm.ActivityInfo;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070039import android.content.pm.ApplicationInfo;
40import android.content.pm.ComponentInfo;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -080041import android.content.pm.IntentFilterVerificationInfo;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070042import android.content.pm.PackageManager;
Todd Kennedycf827032018-07-03 13:17:22 -070043import android.content.pm.PackageManagerInternal;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070044import android.content.pm.PackageParser;
45import android.content.pm.PackageUserState;
46import android.content.pm.PermissionInfo;
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080047import android.content.pm.ResolveInfo;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070048import android.content.pm.Signature;
Suprabh Shukla389cb6f2018-10-01 18:20:39 -070049import android.content.pm.SuspendDialogInfo;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070050import android.content.pm.UserInfo;
51import android.content.pm.VerifierDeviceIdentity;
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080052import android.net.Uri;
Narayan Kamathff110bd2014-07-04 18:30:45 +010053import android.os.Binder;
Jeff Sharkey4ed745d2014-07-15 20:39:15 -070054import android.os.Build;
Narayan Kamathff110bd2014-07-04 18:30:45 +010055import android.os.Environment;
56import android.os.FileUtils;
Svetoslavc6d1c342015-02-26 14:44:43 -080057import android.os.Handler;
58import android.os.Message;
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080059import android.os.PatternMatcher;
Suprabh Shukla021b57a2018-03-08 18:21:50 -080060import android.os.PersistableBundle;
Narayan Kamathff110bd2014-07-04 18:30:45 +010061import android.os.Process;
Svetoslavc6d1c342015-02-26 14:44:43 -080062import android.os.SystemClock;
Narayan Kamathff110bd2014-07-04 18:30:45 +010063import android.os.UserHandle;
Amith Yamasani26f9ea32014-09-11 10:56:51 -070064import android.os.UserManager;
Paul Crowleybcf48ed2015-04-22 13:36:59 +010065import android.os.storage.StorageManager;
Netta P426cbef2017-02-10 14:38:39 -080066import android.service.pm.PackageServiceDumpProto;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -080067import android.text.TextUtils;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070068import android.util.ArrayMap;
69import android.util.ArraySet;
70import android.util.AtomicFile;
71import android.util.Log;
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080072import android.util.LogPrinter;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070073import android.util.Slog;
74import android.util.SparseArray;
Svetoslavc6d1c342015-02-26 14:44:43 -080075import android.util.SparseBooleanArray;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070076import android.util.SparseIntArray;
Svetoslavc6d1c342015-02-26 14:44:43 -080077import android.util.SparseLongArray;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070078import android.util.Xml;
Netta P426cbef2017-02-10 14:38:39 -080079import android.util.proto.ProtoOutputStream;
Christopher Tatee012a232015-04-01 17:18:50 -070080
Svetoslavc6d1c342015-02-26 14:44:43 -080081import com.android.internal.annotations.GuardedBy;
82import com.android.internal.os.BackgroundThread;
83import com.android.internal.util.ArrayUtils;
Makoto Onuki0a068582018-06-13 10:57:34 -070084import com.android.internal.util.CollectionUtils;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070085import com.android.internal.util.FastXmlSerializer;
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -070086import com.android.internal.util.IndentingPrintWriter;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070087import com.android.internal.util.JournaledFile;
88import com.android.internal.util.XmlUtils;
Todd Kennedycf827032018-07-03 13:17:22 -070089import com.android.server.LocalServices;
Jeff Sharkey740f5232016-12-09 14:31:26 -070090import com.android.server.pm.Installer.InstallerException;
Todd Kennedy91a39d12017-09-27 12:37:04 -070091import com.android.server.pm.permission.BasePermission;
Todd Kennedy0eb97382017-10-03 16:57:22 -070092import com.android.server.pm.permission.PermissionSettings;
Todd Kennedy82b08422017-09-28 13:32:05 -070093import com.android.server.pm.permission.PermissionsState;
94import com.android.server.pm.permission.PermissionsState.PermissionState;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070095
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070096import libcore.io.IoUtils;
Alexandra Gherghina6e2ae252014-06-12 16:03:58 +010097
Kenny Rootcf0b38c2011-03-22 14:17:59 -070098import org.xmlpull.v1.XmlPullParser;
99import org.xmlpull.v1.XmlPullParserException;
100import org.xmlpull.v1.XmlSerializer;
101
Jeff Sharkey2a90f6732016-01-06 12:26:11 -0700102import java.io.BufferedInputStream;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700103import java.io.BufferedOutputStream;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -0700104import java.io.BufferedWriter;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700105import java.io.File;
106import java.io.FileInputStream;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -0700107import java.io.FileNotFoundException;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700108import java.io.FileOutputStream;
109import java.io.IOException;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -0700110import java.io.InputStream;
111import java.io.OutputStreamWriter;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700112import java.io.PrintWriter;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -0700113import java.nio.charset.Charset;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100114import java.nio.charset.StandardCharsets;
Kenny Root447106f2011-03-23 11:00:15 -0700115import java.text.SimpleDateFormat;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700116import java.util.ArrayList;
117import java.util.Arrays;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -0700118import java.util.Collection;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -0800119import java.util.Collections;
Kenny Root447106f2011-03-23 11:00:15 -0700120import java.util.Date;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700121import java.util.Iterator;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700122import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800123import java.util.Map;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -0700124import java.util.Map.Entry;
Jeff Sharkey84f12942014-07-10 17:48:11 -0700125import java.util.Objects;
Dianne Hackborn63092712012-10-07 14:45:35 -0700126import java.util.Set;
Kenny Root62539e92011-11-10 09:35:38 -0800127
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700128/**
129 * Holds information about dynamic settings.
130 */
Todd Kennedy91a39d12017-09-27 12:37:04 -0700131public final class Settings {
Kenny Root447106f2011-03-23 11:00:15 -0700132 private static final String TAG = "PackageSettings";
133
Kenny Rootc1c0d3c2014-04-24 13:36:40 -0700134 /**
135 * Current version of the package database. Set it to the latest version in
136 * the {@link DatabaseVersion} class below to ensure the database upgrade
137 * doesn't happen repeatedly.
138 * <p>
139 * Note that care should be taken to make sure all database upgrades are
140 * idempotent.
141 */
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700142 public static final int CURRENT_DATABASE_VERSION = DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
Kenny Rootc1c0d3c2014-04-24 13:36:40 -0700143
144 /**
145 * This class contains constants that can be referred to from upgrade code.
146 * Insert constant values here that describe the upgrade reason. The version
147 * code must be monotonically increasing.
148 */
149 public static class DatabaseVersion {
150 /**
151 * The initial version of the database.
152 */
153 public static final int FIRST_VERSION = 1;
Kenny Roota8e65fd2014-04-24 11:44:47 -0700154
155 /**
156 * Migrating the Signature array from the entire certificate chain to
157 * just the signing certificate.
158 */
159 public static final int SIGNATURE_END_ENTITY = 2;
Jeff Sharkeyd68b87c2014-11-12 12:18:11 -0800160
161 /**
162 * There was a window of time in
163 * {@link android.os.Build.VERSION_CODES#LOLLIPOP} where we persisted
164 * certificates after potentially mutating them. To switch back to the
165 * original untouched certificates, we need to force a collection pass.
166 */
167 public static final int SIGNATURE_MALFORMED_RECOVER = 3;
Kenny Rootc1c0d3c2014-04-24 13:36:40 -0700168 }
169
Kenny Root447106f2011-03-23 11:00:15 -0700170 private static final boolean DEBUG_STOPPED = false;
Amith Yamasani258848d2012-08-10 17:06:33 -0700171 private static final boolean DEBUG_MU = false;
Jeff Sharkey2271ba32016-02-01 17:57:08 -0700172 private static final boolean DEBUG_KERNEL = false;
Todd Kennedy788c8422016-08-10 10:52:34 -0700173 private static final boolean DEBUG_PARSER = false;
Kenny Root447106f2011-03-23 11:00:15 -0700174
Svetoslavc6d1c342015-02-26 14:44:43 -0800175 private static final String RUNTIME_PERMISSIONS_FILE_NAME = "runtime-permissions.xml";
176
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -0700177 private static final String TAG_READ_EXTERNAL_STORAGE = "read-external-storage";
178 private static final String ATTR_ENFORCEMENT = "enforcement";
179
Todd Kennedy91a39d12017-09-27 12:37:04 -0700180 public static final String TAG_ITEM = "item";
Amith Yamasani483f3b02012-03-13 16:08:00 -0700181 private static final String TAG_DISABLED_COMPONENTS = "disabled-components";
182 private static final String TAG_ENABLED_COMPONENTS = "enabled-components";
183 private static final String TAG_PACKAGE_RESTRICTIONS = "package-restrictions";
184 private static final String TAG_PACKAGE = "pkg";
Svetoslavc6d1c342015-02-26 14:44:43 -0800185 private static final String TAG_SHARED_USER = "shared-user";
186 private static final String TAG_RUNTIME_PERMISSIONS = "runtime-permissions";
187 private static final String TAG_PERMISSIONS = "perms";
Svet Ganov354cd3c2015-12-17 11:35:04 -0800188 private static final String TAG_CHILD_PACKAGE = "child-package";
Svet Ganov67882122016-12-11 16:36:34 -0800189 private static final String TAG_USES_STATIC_LIB = "uses-static-lib";
Vladislav Kuzkokov253984e2016-10-24 09:27:16 +0200190 private static final String TAG_BLOCK_UNINSTALL_PACKAGES = "block-uninstall-packages";
191 private static final String TAG_BLOCK_UNINSTALL = "block-uninstall";
Svet Ganov354cd3c2015-12-17 11:35:04 -0800192
Sander Alewijnseaf597622014-03-20 18:44:57 +0000193 private static final String TAG_PERSISTENT_PREFERRED_ACTIVITIES =
194 "persistent-preferred-activities";
Nicolas Prevot81948992014-05-16 18:25:26 +0100195 static final String TAG_CROSS_PROFILE_INTENT_FILTERS =
196 "crossProfile-intent-filters";
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700197 private static final String TAG_DOMAIN_VERIFICATION = "domain-verification";
198 private static final String TAG_DEFAULT_APPS = "default-apps";
199 private static final String TAG_ALL_INTENT_FILTER_VERIFICATION =
Christopher Tate6038d152015-06-17 13:07:46 -0700200 "all-intent-filter-verifications";
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700201 private static final String TAG_DEFAULT_BROWSER = "default-browser";
Robin Lee0dc591b2016-05-04 13:01:46 +0100202 private static final String TAG_DEFAULT_DIALER = "default-dialer";
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700203 private static final String TAG_VERSION = "version";
Suprabh Shukla389cb6f2018-10-01 18:20:39 -0700204 private static final String TAG_SUSPENDED_DIALOG_INFO = "suspended-dialog-info";
Suprabh Shukla021b57a2018-03-08 18:21:50 -0800205 private static final String TAG_SUSPENDED_APP_EXTRAS = "suspended-app-extras";
206 private static final String TAG_SUSPENDED_LAUNCHER_EXTRAS = "suspended-launcher-extras";
Amith Yamasani483f3b02012-03-13 16:08:00 -0700207
Todd Kennedy91a39d12017-09-27 12:37:04 -0700208 public static final String ATTR_NAME = "name";
209 public static final String ATTR_PACKAGE = "package";
Svet Ganov8c7f7002015-05-07 10:48:44 -0700210 private static final String ATTR_GRANTED = "granted";
211 private static final String ATTR_FLAGS = "flags";
Svet Ganov67882122016-12-11 16:36:34 -0800212 private static final String ATTR_VERSION = "version";
Jeff Sharkey42884192016-04-09 16:12:01 -0600213
214 private static final String ATTR_CE_DATA_INODE = "ceDataInode";
215 private static final String ATTR_INSTALLED = "inst";
Amith Yamasani483f3b02012-03-13 16:08:00 -0700216 private static final String ATTR_STOPPED = "stopped";
Jeff Sharkey42884192016-04-09 16:12:01 -0600217 private static final String ATTR_NOT_LAUNCHED = "nl";
Amith Yamasanie5bcff62014-07-19 15:44:09 -0700218 // Legacy, here for reading older versions of the package-restrictions.
Amith Yamasani655d0e22013-06-12 14:19:10 -0700219 private static final String ATTR_BLOCKED = "blocked";
Amith Yamasanie5bcff62014-07-19 15:44:09 -0700220 // New name for the above attribute.
221 private static final String ATTR_HIDDEN = "hidden";
Suprabh Shukla79000492018-12-24 17:03:02 -0800222 private static final String ATTR_DISTRACTION_FLAGS = "distraction_flags";
Andrei Stingaceanu1e283912015-11-26 15:26:28 +0000223 private static final String ATTR_SUSPENDED = "suspended";
Suprabh Shukla021b57a2018-03-08 18:21:50 -0800224 private static final String ATTR_SUSPENDING_PACKAGE = "suspending-package";
Suprabh Shukla389cb6f2018-10-01 18:20:39 -0700225 /**
226 * @deprecated Legacy attribute, kept only for upgrading from P builds.
227 */
228 @Deprecated
Suprabh Shukla3c3af142018-03-30 00:28:37 -0700229 private static final String ATTR_SUSPEND_DIALOG_MESSAGE = "suspend_dialog_message";
Vladislav Kuzkokov253984e2016-10-24 09:27:16 +0200230 // Legacy, uninstall blocks are stored separately.
231 @Deprecated
Kenny Guyc13053b2014-05-29 14:17:17 +0100232 private static final String ATTR_BLOCK_UNINSTALL = "blockUninstall";
Jeff Sharkey42884192016-04-09 16:12:01 -0600233 private static final String ATTR_ENABLED = "enabled";
234 private static final String ATTR_ENABLED_CALLER = "enabledCaller";
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -0800235 private static final String ATTR_DOMAIN_VERIFICATON_STATE = "domainVerificationStatus";
Jeff Sharkey42884192016-04-09 16:12:01 -0600236 private static final String ATTR_APP_LINK_GENERATION = "app-link-generation";
Bartosz Fabianowskia34f53f2017-01-11 18:08:47 +0100237 private static final String ATTR_INSTALL_REASON = "install-reason";
Todd Kennedybe0b8892017-02-15 14:13:52 -0800238 private static final String ATTR_INSTANT_APP = "instant-app";
Todd Kennedy5eb5a7d2017-08-01 07:42:47 -0700239 private static final String ATTR_VIRTUAL_PRELOAD = "virtual-preload";
Ben Gruver1ab3d6e2017-12-07 13:45:08 -0800240 private static final String ATTR_HARMFUL_APP_WARNING = "harmful-app-warning";
Jeff Sharkey42884192016-04-09 16:12:01 -0600241
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700242 private static final String ATTR_PACKAGE_NAME = "packageName";
Svet Ganovba3ba812015-06-26 10:54:06 -0700243 private static final String ATTR_FINGERPRINT = "fingerprint";
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700244 private static final String ATTR_VOLUME_UUID = "volumeUuid";
245 private static final String ATTR_SDK_VERSION = "sdkVersion";
246 private static final String ATTR_DATABASE_VERSION = "databaseVersion";
Amith Yamasani483f3b02012-03-13 16:08:00 -0700247
Svetoslavc6d1c342015-02-26 14:44:43 -0800248 private final Object mLock;
Svetoslavc6d1c342015-02-26 14:44:43 -0800249
250 private final RuntimePermissionPersistence mRuntimePermissionsPersistence;
251
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700252 private final File mSettingsFilename;
253 private final File mBackupSettingsFilename;
254 private final File mPackageListFilename;
255 private final File mStoppedPackagesFilename;
256 private final File mBackupStoppedPackagesFilename;
Amith Yamasani23ab7f52017-01-22 17:43:24 -0800257 /** The top level directory in configfs for sdcardfs to push the package->uid,userId mappings */
Jeff Sharkey2271ba32016-02-01 17:57:08 -0700258 private final File mKernelMappingFilename;
Jeff Sharkey184a0102013-07-10 16:19:52 -0700259
Jeff Sharkey2271ba32016-02-01 17:57:08 -0700260 /** Map from package name to settings */
261 final ArrayMap<String, PackageSetting> mPackages = new ArrayMap<>();
262
Sudheer Shanka29283372016-04-04 20:56:27 -0700263 /** List of packages that installed other packages */
264 final ArraySet<String> mInstallerPackages = new ArraySet<>();
265
Amith Yamasani23ab7f52017-01-22 17:43:24 -0800266 /** Map from package name to appId and excluded userids */
267 private final ArrayMap<String, KernelPackageState> mKernelMapping = new ArrayMap<>();
Christopher Tate6038d152015-06-17 13:07:46 -0700268
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700269 // List of replaced system applications
Jeff Sharkey9f837a92014-10-24 12:07:24 -0700270 private final ArrayMap<String, PackageSetting> mDisabledSysPackages =
271 new ArrayMap<String, PackageSetting>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700272
Vladislav Kuzkokov253984e2016-10-24 09:27:16 +0200273 /** List of packages that are blocked for uninstall for specific users */
274 private final SparseArray<ArraySet<String>> mBlockUninstallPackages = new SparseArray<>();
275
Christopher Tate6038d152015-06-17 13:07:46 -0700276 // Set of restored intent-filter verification states
277 private final ArrayMap<String, IntentFilterVerificationInfo> mRestoredIntentFilterVerifications =
278 new ArrayMap<String, IntentFilterVerificationInfo>();
279
Amith Yamasani23ab7f52017-01-22 17:43:24 -0800280 private static final class KernelPackageState {
281 int appId;
282 int[] excludedUserIds;
283 }
284
Geremy Condra12c18382013-03-06 16:49:06 -0800285 private static int mFirstAvailableUid = 0;
286
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700287 /** Map from volume UUID to {@link VersionInfo} */
288 private ArrayMap<String, VersionInfo> mVersion = new ArrayMap<>();
Kenny Root0aaa0d92011-09-12 16:42:55 -0700289
Kenny Rootc1c0d3c2014-04-24 13:36:40 -0700290 /**
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700291 * Version details for a storage volume that may hold apps.
Kenny Rootc1c0d3c2014-04-24 13:36:40 -0700292 */
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700293 public static class VersionInfo {
294 /**
295 * These are the last platform API version we were using for the apps
296 * installed on internal and external storage. It is used to grant newer
297 * permissions one time during a system upgrade.
298 */
299 int sdkVersion;
Kenny Rootc1c0d3c2014-04-24 13:36:40 -0700300
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700301 /**
302 * The current database version for apps on internal storage. This is
303 * used to upgrade the format of the packages.xml database not
304 * necessarily tied to an SDK version.
305 */
306 int databaseVersion;
307
308 /**
309 * Last known value of {@link Build#FINGERPRINT}. Used to determine when
310 * an system update has occurred, meaning we need to clear code caches.
311 */
312 String fingerprint;
313
314 /**
315 * Force all version information to match current system values,
316 * typically after resolving any required upgrade steps.
317 */
318 public void forceCurrent() {
319 sdkVersion = Build.VERSION.SDK_INT;
320 databaseVersion = CURRENT_DATABASE_VERSION;
321 fingerprint = Build.FINGERPRINT;
322 }
323 }
Jeff Sharkey4ed745d2014-07-15 20:39:15 -0700324
Jeff Sharkeyf5385772012-05-11 14:04:41 -0700325 Boolean mReadExternalStorageEnforced;
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -0700326
Kenny Root0aaa0d92011-09-12 16:42:55 -0700327 /** Device identity for the purpose of package verification. */
328 private VerifierDeviceIdentity mVerifierDeviceIdentity;
329
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700330 // The user's preferred activities associated with particular intent
331 // filters.
Dianne Hackborn63092712012-10-07 14:45:35 -0700332 final SparseArray<PreferredIntentResolver> mPreferredActivities =
333 new SparseArray<PreferredIntentResolver>();
334
Sander Alewijnsef475ca32014-02-17 15:13:58 +0000335 // The persistent preferred activities of the user's profile/device owner
336 // associated with particular intent filters.
337 final SparseArray<PersistentPreferredIntentResolver> mPersistentPreferredActivities =
338 new SparseArray<PersistentPreferredIntentResolver>();
339
Nicolas Prevot10fa67c2014-03-24 13:44:38 +0000340 // For every user, it is used to find to which other users the intent can be forwarded.
Nicolas Prevot81948992014-05-16 18:25:26 +0100341 final SparseArray<CrossProfileIntentResolver> mCrossProfileIntentResolvers =
342 new SparseArray<CrossProfileIntentResolver>();
Nicolas Prevot10fa67c2014-03-24 13:44:38 +0000343
Patrick Baumann649a8572018-11-20 11:16:58 -0800344 final ArrayMap<String, SharedUserSetting> mSharedUsers = new ArrayMap<>();
345 private final ArrayList<SettingBase> mAppIds = new ArrayList<>();
346 private final SparseArray<SettingBase> mOtherAppIds = new SparseArray<>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700347
348 // For reading/writing settings file.
349 private final ArrayList<Signature> mPastSignatures =
350 new ArrayList<Signature>();
dcashman8c04fac2015-03-23 11:39:42 -0700351 private final ArrayMap<Long, Integer> mKeySetRefs =
352 new ArrayMap<Long, Integer>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700353
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700354 // Packages that have been renamed since they were first installed.
355 // Keys are the new names of the packages, values are the original
Todd Kennedy13715d52016-08-01 13:38:57 -0700356 // names. The packages appear everywhere else under their original
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700357 // names.
Todd Kennedy13715d52016-08-01 13:38:57 -0700358 private final ArrayMap<String, String> mRenamedPackages = new ArrayMap<String, String>();
Fabrice Di Meglio62271722015-04-10 17:24:02 -0700359
360 // For every user, it is used to find the package name of the default Browser App.
361 final SparseArray<String> mDefaultBrowserApp = new SparseArray<String>();
362
Robin Lee0dc591b2016-05-04 13:01:46 +0100363 // For every user, a record of the package name of the default Dialer App.
364 final SparseArray<String> mDefaultDialerApp = new SparseArray<String>();
365
Christopher Tatef0d6cb32015-07-10 17:44:53 -0700366 // App-link priority tracking, per-user
367 final SparseIntArray mNextAppLinkGeneration = new SparseIntArray();
368
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700369 final StringBuilder mReadMessages = new StringBuilder();
370
Kenny Root447106f2011-03-23 11:00:15 -0700371 /**
372 * Used to track packages that have a shared user ID that hasn't been read
373 * in yet.
374 * <p>
375 * TODO: make this just a local variable that is passed in during package
376 * scanning to make it less confusing.
377 */
Todd Kennedy788c8422016-08-10 10:52:34 -0700378 private final ArrayList<PackageSetting> mPendingPackages = new ArrayList<>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700379
Amith Yamasani483f3b02012-03-13 16:08:00 -0700380 private final File mSystemDir;
Geremy Condraf1bcca82013-01-07 22:35:24 -0800381
dcashman55b10782014-04-09 14:20:38 -0700382 public final KeySetManagerService mKeySetManagerService = new KeySetManagerService(mPackages);
Todd Kennedy0eb97382017-10-03 16:57:22 -0700383 /** Settings and other information about permissions */
Todd Kennedyc8423932017-10-05 08:58:36 -0700384 final PermissionSettings mPermissions;
Geremy Condraf1bcca82013-01-07 22:35:24 -0800385
Todd Kennedycf827032018-07-03 13:17:22 -0700386 Settings(File dataDir, PermissionSettings permission,
387 Object lock) {
Svetoslavc6d1c342015-02-26 14:44:43 -0800388 mLock = lock;
Todd Kennedy0eb97382017-10-03 16:57:22 -0700389 mPermissions = permission;
Svetoslavc6d1c342015-02-26 14:44:43 -0800390 mRuntimePermissionsPersistence = new RuntimePermissionPersistence(mLock);
391
Amith Yamasani483f3b02012-03-13 16:08:00 -0700392 mSystemDir = new File(dataDir, "system");
393 mSystemDir.mkdirs();
394 FileUtils.setPermissions(mSystemDir.toString(),
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700395 FileUtils.S_IRWXU|FileUtils.S_IRWXG
396 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
397 -1, -1);
Amith Yamasani483f3b02012-03-13 16:08:00 -0700398 mSettingsFilename = new File(mSystemDir, "packages.xml");
399 mBackupSettingsFilename = new File(mSystemDir, "packages-backup.xml");
400 mPackageListFilename = new File(mSystemDir, "packages.list");
Jeff Sharkeyaebb65c2014-11-24 15:00:13 -0800401 FileUtils.setPermissions(mPackageListFilename, 0640, SYSTEM_UID, PACKAGE_INFO_GID);
Jeff Sharkey184a0102013-07-10 16:19:52 -0700402
Jeff Sharkey2271ba32016-02-01 17:57:08 -0700403 final File kernelDir = new File("/config/sdcardfs");
404 mKernelMappingFilename = kernelDir.exists() ? kernelDir : null;
405
Amith Yamasani483f3b02012-03-13 16:08:00 -0700406 // Deprecated: Needed for migration
407 mStoppedPackagesFilename = new File(mSystemDir, "packages-stopped.xml");
408 mBackupStoppedPackagesFilename = new File(mSystemDir, "packages-stopped-backup.xml");
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700409 }
410
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700411 PackageSetting getPackageLPr(String pkgName) {
Todd Kennedy13715d52016-08-01 13:38:57 -0700412 return mPackages.get(pkgName);
413 }
414
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700415 String getRenamedPackageLPr(String pkgName) {
Todd Kennedy13715d52016-08-01 13:38:57 -0700416 return mRenamedPackages.get(pkgName);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700417 }
418
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700419 String addRenamedPackageLPw(String pkgName, String origPkgName) {
420 return mRenamedPackages.put(pkgName, origPkgName);
421 }
422
Todd Kennedy0eb97382017-10-03 16:57:22 -0700423 public boolean canPropagatePermissionToInstantApp(String permName) {
424 return mPermissions.canPropagatePermissionToInstantApp(permName);
425 }
426
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -0700427 void setInstallerPackageName(String pkgName, String installerPkgName) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700428 PackageSetting p = mPackages.get(pkgName);
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -0700429 if (p != null) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700430 p.setInstallerPackageName(installerPkgName);
Sudheer Shanka29283372016-04-04 20:56:27 -0700431 if (installerPkgName != null) {
432 mInstallerPackages.add(installerPkgName);
433 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700434 }
435 }
436
Todd Kennedy13715d52016-08-01 13:38:57 -0700437 /** Gets and optionally creates a new shared user id. */
Todd Kennedyff35e662016-09-20 12:53:52 -0700438 SharedUserSetting getSharedUserLPw(String name, int pkgFlags, int pkgPrivateFlags,
439 boolean create) throws PackageManagerException {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700440 SharedUserSetting s = mSharedUsers.get(name);
Todd Kennedyff35e662016-09-20 12:53:52 -0700441 if (s == null && create) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800442 s = new SharedUserSetting(name, pkgFlags, pkgPrivateFlags);
Patrick Baumann649a8572018-11-20 11:16:58 -0800443 s.userId = acquireAndRegisterNewAppIdLPw(s);
Todd Kennedyff35e662016-09-20 12:53:52 -0700444 if (s.userId < 0) {
445 // < 0 means we couldn't assign a userid; throw exception
446 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
447 "Creating shared user " + name + " failed");
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700448 }
Todd Kennedyff35e662016-09-20 12:53:52 -0700449 Log.i(PackageManagerService.TAG, "New shared user " + name + ": id=" + s.userId);
450 mSharedUsers.put(name, s);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700451 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700452 return s;
453 }
454
Narayan Kamathdf6d6dc2014-04-28 14:18:34 +0100455 Collection<SharedUserSetting> getAllSharedUsersLPw() {
456 return mSharedUsers.values();
457 }
458
Svet Ganov354cd3c2015-12-17 11:35:04 -0800459 boolean disableSystemPackageLPw(String name, boolean replaced) {
Kenny Root447106f2011-03-23 11:00:15 -0700460 final PackageSetting p = mPackages.get(name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700461 if(p == null) {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700462 Log.w(PackageManagerService.TAG, "Package " + name + " is not an installed package");
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700463 return false;
464 }
Kenny Root447106f2011-03-23 11:00:15 -0700465 final PackageSetting dp = mDisabledSysPackages.get(name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700466 // always make sure the system package code and resource paths dont change
Todd Kennedyc29b11a2017-10-23 15:55:59 -0700467 if (dp == null && p.pkg != null && p.pkg.isSystem() && !p.pkg.isUpdatedSystemApp()) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700468 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
469 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
470 }
Patrick4ccae942018-07-17 09:15:55 -0700471 final PackageSetting disabled;
Svet Ganov354cd3c2015-12-17 11:35:04 -0800472 if (replaced) {
473 // a little trick... when we install the new package, we don't
474 // want to modify the existing PackageSetting for the built-in
Patrick4ccae942018-07-17 09:15:55 -0700475 // version. so at this point we make a copy to place into the
476 // disabled set.
477 disabled = new PackageSetting(p);
478 } else {
479 disabled = p;
Svet Ganov354cd3c2015-12-17 11:35:04 -0800480 }
Patrick4ccae942018-07-17 09:15:55 -0700481 mDisabledSysPackages.put(name, disabled);
482
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700483 return true;
484 }
485 return false;
486 }
487
Kenny Root447106f2011-03-23 11:00:15 -0700488 PackageSetting enableSystemPackageLPw(String name) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700489 PackageSetting p = mDisabledSysPackages.get(name);
490 if(p == null) {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700491 Log.w(PackageManagerService.TAG, "Package " + name + " is not disabled");
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700492 return null;
493 }
494 // Reset flag in ApplicationInfo object
495 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
496 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
497 }
Kenny Root447106f2011-03-23 11:00:15 -0700498 PackageSetting ret = addPackageLPw(name, p.realName, p.codePath, p.resourcePath,
Narayan Kamathff110bd2014-07-04 18:30:45 +0100499 p.legacyNativeLibraryPathString, p.primaryCpuAbiString,
Selim Gurun5c8acb42016-04-07 16:34:02 -0700500 p.secondaryCpuAbiString, p.cpuAbiOverrideString,
Svet Ganov354cd3c2015-12-17 11:35:04 -0800501 p.appId, p.versionCode, p.pkgFlags, p.pkgPrivateFlags,
Svet Ganov67882122016-12-11 16:36:34 -0800502 p.parentPackageName, p.childPackageNames, p.usesStaticLibraries,
503 p.usesStaticLibrariesVersions);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700504 mDisabledSysPackages.remove(name);
505 return ret;
506 }
507
Kenny Rootc52d6fd2012-05-07 23:04:52 -0700508 boolean isDisabledSystemPackageLPr(String name) {
509 return mDisabledSysPackages.containsKey(name);
510 }
511
512 void removeDisabledSystemPackageLPw(String name) {
513 mDisabledSysPackages.remove(name);
514 }
515
Kenny Root447106f2011-03-23 11:00:15 -0700516 PackageSetting addPackageLPw(String name, String realName, File codePath, File resourcePath,
Svet Ganovf4ff39c2016-02-04 14:27:05 -0800517 String legacyNativeLibraryPathString, String primaryCpuAbiString,
Dianne Hackborn3accca02013-09-20 09:32:11 -0700518 String secondaryCpuAbiString, String cpuAbiOverrideString, int uid, long vc, int
Svet Ganovf4ff39c2016-02-04 14:27:05 -0800519 pkgFlags, int pkgPrivateFlags, String parentPackageName,
Svet Ganov67882122016-12-11 16:36:34 -0800520 List<String> childPackageNames, String[] usesStaticLibraries,
Dianne Hackborn3accca02013-09-20 09:32:11 -0700521 long[] usesStaticLibraryNames) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700522 PackageSetting p = mPackages.get(name);
523 if (p != null) {
Amith Yamasani13593602012-03-22 16:16:17 -0700524 if (p.appId == uid) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700525 return p;
526 }
527 PackageManagerService.reportSettingsProblem(Log.ERROR,
528 "Adding duplicate package, keeping first: " + name);
529 return null;
530 }
Narayan Kamathff110bd2014-07-04 18:30:45 +0100531 p = new PackageSetting(name, realName, codePath, resourcePath,
Narayan Kamath4903f642014-08-11 13:33:45 +0100532 legacyNativeLibraryPathString, primaryCpuAbiString, secondaryCpuAbiString,
Svet Ganov354cd3c2015-12-17 11:35:04 -0800533 cpuAbiOverrideString, vc, pkgFlags, pkgPrivateFlags, parentPackageName,
Svet Ganov67882122016-12-11 16:36:34 -0800534 childPackageNames, 0 /*userId*/, usesStaticLibraries, usesStaticLibraryNames);
Amith Yamasani13593602012-03-22 16:16:17 -0700535 p.appId = uid;
Patrick Baumann649a8572018-11-20 11:16:58 -0800536 if (registerExistingAppIdLPw(uid, p, name)) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700537 mPackages.put(name, p);
538 return p;
539 }
540 return null;
541 }
542
Todd Kennedyc8423932017-10-05 08:58:36 -0700543 void addAppOpPackage(String permName, String packageName) {
544 mPermissions.addAppOpPackage(permName, packageName);
545 }
546
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800547 SharedUserSetting addSharedUserLPw(String name, int uid, int pkgFlags, int pkgPrivateFlags) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700548 SharedUserSetting s = mSharedUsers.get(name);
549 if (s != null) {
550 if (s.userId == uid) {
551 return s;
552 }
553 PackageManagerService.reportSettingsProblem(Log.ERROR,
554 "Adding duplicate shared user, keeping first: " + name);
555 return null;
556 }
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800557 s = new SharedUserSetting(name, pkgFlags, pkgPrivateFlags);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700558 s.userId = uid;
Patrick Baumann649a8572018-11-20 11:16:58 -0800559 if (registerExistingAppIdLPw(uid, s, name)) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700560 mSharedUsers.put(name, s);
561 return s;
562 }
563 return null;
564 }
565
Christopher Tate86b391c2013-09-13 16:58:36 -0700566 void pruneSharedUsersLPw() {
567 ArrayList<String> removeStage = new ArrayList<String>();
568 for (Map.Entry<String,SharedUserSetting> entry : mSharedUsers.entrySet()) {
569 final SharedUserSetting sus = entry.getValue();
Todd Kennedy68f67152015-10-21 13:09:10 -0700570 if (sus == null) {
571 removeStage.add(entry.getKey());
572 continue;
573 }
574 // remove packages that are no longer installed
575 for (Iterator<PackageSetting> iter = sus.packages.iterator(); iter.hasNext();) {
576 PackageSetting ps = iter.next();
577 if (mPackages.get(ps.name) == null) {
578 iter.remove();
579 }
580 }
581 if (sus.packages.size() == 0) {
Christopher Tate86b391c2013-09-13 16:58:36 -0700582 removeStage.add(entry.getKey());
583 }
584 }
585 for (int i = 0; i < removeStage.size(); i++) {
586 mSharedUsers.remove(removeStage.get(i));
587 }
588 }
589
Todd Kennedy0eb97382017-10-03 16:57:22 -0700590 /**
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700591 * Creates a new {@code PackageSetting} object.
592 * Use this method instead of the constructor to ensure a settings object is created
593 * with the correct base.
Todd Kennedy13715d52016-08-01 13:38:57 -0700594 */
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700595 static @NonNull PackageSetting createNewSetting(String pkgName, PackageSetting originalPkg,
596 PackageSetting disabledPkg, String realPkgName, SharedUserSetting sharedUser,
597 File codePath, File resourcePath, String legacyNativeLibraryPath, String primaryCpuAbi,
Dianne Hackborn3accca02013-09-20 09:32:11 -0700598 String secondaryCpuAbi, long versionCode, int pkgFlags, int pkgPrivateFlags,
Todd Kennedy5eb5a7d2017-08-01 07:42:47 -0700599 UserHandle installUser, boolean allowInstall, boolean instantApp,
600 boolean virtualPreload, String parentPkgName, List<String> childPkgNames,
601 UserManagerService userManager,
Dianne Hackborn3accca02013-09-20 09:32:11 -0700602 String[] usesStaticLibraries, long[] usesStaticLibrariesVersions) {
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700603 final PackageSetting pkgSetting;
604 if (originalPkg != null) {
605 if (PackageManagerService.DEBUG_UPGRADE) Log.v(PackageManagerService.TAG, "Package "
606 + pkgName + " is adopting original package " + originalPkg.name);
607 pkgSetting = new PackageSetting(originalPkg, pkgName /*realPkgName*/);
608 pkgSetting.childPackageNames =
609 (childPkgNames != null) ? new ArrayList<>(childPkgNames) : null;
610 pkgSetting.codePath = codePath;
611 pkgSetting.legacyNativeLibraryPathString = legacyNativeLibraryPath;
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700612 pkgSetting.parentPackageName = parentPkgName;
613 pkgSetting.pkgFlags = pkgFlags;
614 pkgSetting.pkgPrivateFlags = pkgPrivateFlags;
Todd Kennedy13715d52016-08-01 13:38:57 -0700615 pkgSetting.primaryCpuAbiString = primaryCpuAbi;
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700616 pkgSetting.resourcePath = resourcePath;
Todd Kennedy13715d52016-08-01 13:38:57 -0700617 pkgSetting.secondaryCpuAbiString = secondaryCpuAbi;
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700618 // NOTE: Create a deeper copy of the package signatures so we don't
619 // overwrite the signatures in the original package setting.
620 pkgSetting.signatures = new PackageSignatures();
621 pkgSetting.versionCode = versionCode;
Svet Ganov67882122016-12-11 16:36:34 -0800622 pkgSetting.usesStaticLibraries = usesStaticLibraries;
623 pkgSetting.usesStaticLibrariesVersions = usesStaticLibrariesVersions;
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700624 // Update new package state.
625 pkgSetting.setTimeStamp(codePath.lastModified());
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700626 } else {
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700627 pkgSetting = new PackageSetting(pkgName, realPkgName, codePath, resourcePath,
628 legacyNativeLibraryPath, primaryCpuAbi, secondaryCpuAbi,
629 null /*cpuAbiOverrideString*/, versionCode, pkgFlags, pkgPrivateFlags,
Svet Ganov67882122016-12-11 16:36:34 -0800630 parentPkgName, childPkgNames, 0 /*sharedUserId*/, usesStaticLibraries,
631 usesStaticLibrariesVersions);
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700632 pkgSetting.setTimeStamp(codePath.lastModified());
633 pkgSetting.sharedUser = sharedUser;
634 // If this is not a system app, it starts out stopped.
635 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
636 if (DEBUG_STOPPED) {
637 RuntimeException e = new RuntimeException("here");
638 e.fillInStackTrace();
639 Slog.i(PackageManagerService.TAG, "Stopping package " + pkgName, e);
640 }
Todd Kennedy13715d52016-08-01 13:38:57 -0700641 List<UserInfo> users = getAllUsers(userManager);
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700642 final int installUserId = installUser != null ? installUser.getIdentifier() : 0;
643 if (users != null && allowInstall) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700644 for (UserInfo user : users) {
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700645 // By default we consider this app to be installed
646 // for the user if no user has been specified (which
647 // means to leave it at its original value, and the
648 // original default value is true), or we are being
649 // asked to install for all users, or this is the
650 // user we are installing for.
651 final boolean installed = installUser == null
652 || (installUserId == UserHandle.USER_ALL
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700653 && !isAdbInstallDisallowed(userManager, user.id))
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700654 || installUserId == user.id;
655 pkgSetting.setUserState(user.id, 0, COMPONENT_ENABLED_STATE_DEFAULT,
656 installed,
Todd Kennedybe0b8892017-02-15 14:13:52 -0800657 true /*stopped*/,
658 true /*notLaunched*/,
659 false /*hidden*/,
Suprabh Shukla79000492018-12-24 17:03:02 -0800660 0 /*distractionFlags*/,
Todd Kennedybe0b8892017-02-15 14:13:52 -0800661 false /*suspended*/,
Suprabh Shukla151b21b2018-04-27 19:30:30 -0700662 null /*suspendingPackage*/,
Suprabh Shukla389cb6f2018-10-01 18:20:39 -0700663 null /*dialogInfo*/,
Suprabh Shukla151b21b2018-04-27 19:30:30 -0700664 null /*suspendedAppExtras*/,
665 null /*suspendedLauncherExtras*/,
Todd Kennedybe0b8892017-02-15 14:13:52 -0800666 instantApp,
Todd Kennedy5eb5a7d2017-08-01 07:42:47 -0700667 virtualPreload,
Todd Kennedybe0b8892017-02-15 14:13:52 -0800668 null /*lastDisableAppCaller*/,
669 null /*enabledComponents*/,
670 null /*disabledComponents*/,
Todd Kennedybe0b8892017-02-15 14:13:52 -0800671 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED,
Ben Gruver1ab3d6e2017-12-07 13:45:08 -0800672 0, PackageManager.INSTALL_REASON_UNKNOWN,
673 null /*harmfulAppWarning*/);
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700674 }
675 }
676 }
677 if (sharedUser != null) {
678 pkgSetting.appId = sharedUser.userId;
679 } else {
680 // Clone the setting here for disabled system packages
681 if (disabledPkg != null) {
682 // For disabled packages a new setting is created
683 // from the existing user id. This still has to be
684 // added to list of user id's
685 // Copy signatures from previous setting
686 pkgSetting.signatures = new PackageSignatures(disabledPkg.signatures);
687 pkgSetting.appId = disabledPkg.appId;
688 // Clone permissions
689 pkgSetting.getPermissionsState().copyFrom(disabledPkg.getPermissionsState());
690 // Clone component info
691 List<UserInfo> users = getAllUsers(userManager);
692 if (users != null) {
693 for (UserInfo user : users) {
694 final int userId = user.id;
695 pkgSetting.setDisabledComponentsCopy(
696 disabledPkg.getDisabledComponents(userId), userId);
697 pkgSetting.setEnabledComponentsCopy(
698 disabledPkg.getEnabledComponents(userId), userId);
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700699 }
700 }
701 }
702 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700703 }
Todd Kennedy13715d52016-08-01 13:38:57 -0700704 return pkgSetting;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700705 }
706
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700707 /**
708 * Updates the given package setting using the provided information.
709 * <p>
710 * WARNING: The provided PackageSetting object may be mutated.
711 */
712 static void updatePackageSetting(@NonNull PackageSetting pkgSetting,
713 @Nullable PackageSetting disabledPkg, @Nullable SharedUserSetting sharedUser,
Todd Kennedy30a23a52018-01-04 13:27:49 -0800714 @NonNull File codePath, File resourcePath,
715 @Nullable String legacyNativeLibraryPath, @Nullable String primaryCpuAbi,
716 @Nullable String secondaryCpuAbi, int pkgFlags, int pkgPrivateFlags,
717 @Nullable List<String> childPkgNames, @NonNull UserManagerService userManager,
718 @Nullable String[] usesStaticLibraries, @Nullable long[] usesStaticLibrariesVersions)
719 throws PackageManagerException {
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700720 final String pkgName = pkgSetting.name;
721 if (pkgSetting.sharedUser != sharedUser) {
722 PackageManagerService.reportSettingsProblem(Log.WARN,
723 "Package " + pkgName + " shared user changed from "
724 + (pkgSetting.sharedUser != null ? pkgSetting.sharedUser.name : "<nothing>")
725 + " to " + (sharedUser != null ? sharedUser.name : "<nothing>"));
726 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
727 "Updating application package " + pkgName + " failed");
728 }
729
730 if (!pkgSetting.codePath.equals(codePath)) {
Todd Kennedy30a23a52018-01-04 13:27:49 -0800731 final boolean isSystem = pkgSetting.isSystem();
732 Slog.i(PackageManagerService.TAG,
733 "Update" + (isSystem ? " system" : "")
734 + " package " + pkgName
735 + " code path from " + pkgSetting.codePathString
736 + " to " + codePath.toString()
737 + "; Retain data and using new");
738 if (!isSystem) {
739 // The package isn't considered as installed if the application was
740 // first installed by another user. Update the installed flag when the
741 // application ever becomes part of the system.
742 if ((pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0 && disabledPkg == null) {
743 final List<UserInfo> allUserInfos = getAllUsers(userManager);
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700744 if (allUserInfos != null) {
745 for (UserInfo userInfo : allUserInfos) {
746 pkgSetting.setInstalled(true, userInfo.id);
747 }
748 }
749 }
750
Todd Kennedy30a23a52018-01-04 13:27:49 -0800751 // Since we've changed paths, prefer the new native library path over
752 // the one stored in the package settings since we might have moved from
753 // internal to external storage or vice versa.
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700754 pkgSetting.legacyNativeLibraryPathString = legacyNativeLibraryPath;
755 }
Todd Kennedy30a23a52018-01-04 13:27:49 -0800756 pkgSetting.codePath = codePath;
757 pkgSetting.codePathString = codePath.toString();
758 }
759 if (!pkgSetting.resourcePath.equals(resourcePath)) {
760 final boolean isSystem = pkgSetting.isSystem();
761 Slog.i(PackageManagerService.TAG,
762 "Update" + (isSystem ? " system" : "")
763 + " package " + pkgName
764 + " resource path from " + pkgSetting.resourcePathString
765 + " to " + resourcePath.toString()
766 + "; Retain data and using new");
767 pkgSetting.resourcePath = resourcePath;
768 pkgSetting.resourcePathString = resourcePath.toString();
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700769 }
770 // If what we are scanning is a system (and possibly privileged) package,
771 // then make it so, regardless of whether it was previously installed only
Patrick Baumanna639d142018-05-02 15:00:59 -0700772 // in the data partition. Reset first.
773 pkgSetting.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
774 pkgSetting.pkgPrivateFlags &= ~(ApplicationInfo.PRIVATE_FLAG_PRIVILEGED
775 | ApplicationInfo.PRIVATE_FLAG_OEM
776 | ApplicationInfo.PRIVATE_FLAG_VENDOR
Dario Freni2bef1762018-06-01 14:02:08 +0100777 | ApplicationInfo.PRIVATE_FLAG_PRODUCT
778 | ApplicationInfo.PRIVATE_FLAG_PRODUCT_SERVICES);
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700779 pkgSetting.pkgFlags |= pkgFlags & ApplicationInfo.FLAG_SYSTEM;
780 pkgSetting.pkgPrivateFlags |=
781 pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
Svet Ganov087dce22017-09-07 15:42:16 -0700782 pkgSetting.pkgPrivateFlags |=
783 pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM;
Jiyong Park002fdbd2017-02-13 20:50:31 +0900784 pkgSetting.pkgPrivateFlags |=
785 pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR;
Jaekyun Seok1713d9e2018-01-12 21:47:26 +0900786 pkgSetting.pkgPrivateFlags |=
787 pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT;
Dario Freni2bef1762018-06-01 14:02:08 +0100788 pkgSetting.pkgPrivateFlags |=
789 pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT_SERVICES;
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700790 pkgSetting.primaryCpuAbiString = primaryCpuAbi;
791 pkgSetting.secondaryCpuAbiString = secondaryCpuAbi;
792 if (childPkgNames != null) {
793 pkgSetting.childPackageNames = new ArrayList<>(childPkgNames);
794 }
Todd Kennedy30a23a52018-01-04 13:27:49 -0800795 // Update static shared library dependencies if needed
796 if (usesStaticLibraries != null && usesStaticLibrariesVersions != null
797 && usesStaticLibraries.length == usesStaticLibrariesVersions.length) {
798 pkgSetting.usesStaticLibraries = usesStaticLibraries;
799 pkgSetting.usesStaticLibrariesVersions = usesStaticLibrariesVersions;
800 } else {
801 pkgSetting.usesStaticLibraries = null;
802 pkgSetting.usesStaticLibrariesVersions = null;
Svet Ganov67882122016-12-11 16:36:34 -0800803 }
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700804 }
805
806 /**
807 * Registers a user ID with the system. Potentially allocates a new user ID.
808 * @throws PackageManagerException If a user ID could not be allocated.
809 */
Patrick Baumann649a8572018-11-20 11:16:58 -0800810 void registerAppIdLPw(PackageSetting p) throws PackageManagerException {
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700811 if (p.appId == 0) {
812 // Assign new user ID
Patrick Baumann649a8572018-11-20 11:16:58 -0800813 p.appId = acquireAndRegisterNewAppIdLPw(p);
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700814 } else {
815 // Add new setting to list of user IDs
Patrick Baumann649a8572018-11-20 11:16:58 -0800816 registerExistingAppIdLPw(p.appId, p, p.name);
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700817 }
818 if (p.appId < 0) {
819 PackageManagerService.reportSettingsProblem(Log.WARN,
Jeff Sharkeyf60d8ab2017-02-24 11:06:49 -0700820 "Package " + p.name + " could not be assigned a valid UID");
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700821 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
Jeff Sharkeyf60d8ab2017-02-24 11:06:49 -0700822 "Package " + p.name + " could not be assigned a valid UID");
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700823 }
824 }
825
826 /**
827 * Writes per-user package restrictions if the user state has changed. If the user
828 * state has not changed, this does nothing.
829 */
Todd Kennedyff35e662016-09-20 12:53:52 -0700830 void writeUserRestrictionsLPw(PackageSetting newPackage, PackageSetting oldPackage) {
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700831 // package doesn't exist; do nothing
Todd Kennedy8cad6232016-10-06 11:27:07 -0700832 if (getPackageLPr(newPackage.name) == null) {
Todd Kennedy3cd658e2016-08-16 15:00:31 -0700833 return;
834 }
835 // no users defined; do nothing
836 final List<UserInfo> allUsers = getAllUsers(UserManagerService.getInstance());
837 if (allUsers == null) {
838 return;
839 }
840 for (UserInfo user : allUsers) {
841 final PackageUserState oldUserState = oldPackage == null
842 ? PackageSettingBase.DEFAULT_USER_STATE
843 : oldPackage.readUserState(user.id);
844 if (!oldUserState.equals(newPackage.readUserState(user.id))) {
845 writePackageRestrictionsLPr(user.id);
846 }
847 }
848 }
849
Todd Kennedy13715d52016-08-01 13:38:57 -0700850 static boolean isAdbInstallDisallowed(UserManagerService userManager, int userId) {
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700851 return userManager.hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES,
852 userId);
853 }
854
Todd Kennedy30a23a52018-01-04 13:27:49 -0800855 // TODO: Move to scanPackageOnlyLI() after verifying signatures are setup correctly
856 // by that time.
Kenny Root447106f2011-03-23 11:00:15 -0700857 void insertPackageSettingLPw(PackageSetting p, PackageParser.Package pkg) {
Amith Yamasani483f3b02012-03-13 16:08:00 -0700858 // Update signatures if needed.
Daniel Cashman77029c52018-01-18 16:19:29 -0800859 if (p.signatures.mSigningDetails.signatures == null) {
860 p.signatures.mSigningDetails = pkg.mSigningDetails;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700861 }
862 // If this app defines a shared user id initialize
863 // the shared user signatures as well.
Daniel Cashman77029c52018-01-18 16:19:29 -0800864 if (p.sharedUser != null && p.sharedUser.signatures.mSigningDetails.signatures == null) {
865 p.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700866 }
Todd Kennedy788c8422016-08-10 10:52:34 -0700867 addPackageSettingLPw(p, p.sharedUser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700868 }
869
870 // Utility method that adds a PackageSetting to mPackages and
Christopher Tate6038d152015-06-17 13:07:46 -0700871 // completes updating the shared user attributes and any restored
872 // app link verification state
Todd Kennedy788c8422016-08-10 10:52:34 -0700873 private void addPackageSettingLPw(PackageSetting p, SharedUserSetting sharedUser) {
874 mPackages.put(p.name, p);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700875 if (sharedUser != null) {
876 if (p.sharedUser != null && p.sharedUser != sharedUser) {
877 PackageManagerService.reportSettingsProblem(Log.ERROR,
878 "Package " + p.name + " was user "
879 + p.sharedUser + " but is now " + sharedUser
880 + "; I am not changing its files so it will probably fail!");
Ben Gruverdd72c9e2013-08-06 12:34:17 -0700881 p.sharedUser.removePackage(p);
Amith Yamasani13593602012-03-22 16:16:17 -0700882 } else if (p.appId != sharedUser.userId) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700883 PackageManagerService.reportSettingsProblem(Log.ERROR,
Amith Yamasani13593602012-03-22 16:16:17 -0700884 "Package " + p.name + " was user id " + p.appId
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700885 + " but is now user " + sharedUser
886 + " with id " + sharedUser.userId
887 + "; I am not changing its files so it will probably fail!");
888 }
889
Ben Gruverdd72c9e2013-08-06 12:34:17 -0700890 sharedUser.addPackage(p);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700891 p.sharedUser = sharedUser;
Amith Yamasani13593602012-03-22 16:16:17 -0700892 p.appId = sharedUser.userId;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700893 }
Svet Ganove7af1942015-08-04 11:13:44 -0700894
895 // If the we know about this user id, we have to update it as it
896 // has to point to the same PackageSetting instance as the package.
Patrick Baumann649a8572018-11-20 11:16:58 -0800897 Object userIdPs = getSettingLPr(p.appId);
Svet Ganove7af1942015-08-04 11:13:44 -0700898 if (sharedUser == null) {
899 if (userIdPs != null && userIdPs != p) {
Patrick Baumann649a8572018-11-20 11:16:58 -0800900 replaceAppIdLPw(p.appId, p);
Svet Ganove7af1942015-08-04 11:13:44 -0700901 }
902 } else {
903 if (userIdPs != null && userIdPs != sharedUser) {
Patrick Baumann649a8572018-11-20 11:16:58 -0800904 replaceAppIdLPw(p.appId, sharedUser);
Svet Ganove7af1942015-08-04 11:13:44 -0700905 }
906 }
907
Todd Kennedy788c8422016-08-10 10:52:34 -0700908 IntentFilterVerificationInfo ivi = mRestoredIntentFilterVerifications.get(p.name);
Christopher Tate6038d152015-06-17 13:07:46 -0700909 if (ivi != null) {
910 if (DEBUG_DOMAIN_VERIFICATION) {
Todd Kennedy788c8422016-08-10 10:52:34 -0700911 Slog.i(TAG, "Applying restored IVI for " + p.name + " : " + ivi.getStatusString());
Christopher Tate6038d152015-06-17 13:07:46 -0700912 }
Todd Kennedy788c8422016-08-10 10:52:34 -0700913 mRestoredIntentFilterVerifications.remove(p.name);
Christopher Tate6038d152015-06-17 13:07:46 -0700914 p.setIntentFilterVerificationInfo(ivi);
915 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700916 }
917
918 /*
919 * Update the shared user setting when a package using
920 * specifying the shared user id is removed. The gids
921 * associated with each permission of the deleted package
922 * are removed from the shared user's gid list only if its
923 * not in use by other permissions of packages in the
924 * shared user setting.
925 */
Svetoslavc6d1c342015-02-26 14:44:43 -0800926 int updateSharedUserPermsLPw(PackageSetting deletedPs, int userId) {
Kenny Root447106f2011-03-23 11:00:15 -0700927 if ((deletedPs == null) || (deletedPs.pkg == null)) {
928 Slog.i(PackageManagerService.TAG,
929 "Trying to update info for null package. Just ignoring");
Svetoslavc6d1c342015-02-26 14:44:43 -0800930 return UserHandle.USER_NULL;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700931 }
Svetoslavc6d1c342015-02-26 14:44:43 -0800932
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700933 // No sharedUserId
934 if (deletedPs.sharedUser == null) {
Svetoslavc6d1c342015-02-26 14:44:43 -0800935 return UserHandle.USER_NULL;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700936 }
Svetoslavc6d1c342015-02-26 14:44:43 -0800937
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700938 SharedUserSetting sus = deletedPs.sharedUser;
Svetoslavc6d1c342015-02-26 14:44:43 -0800939
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700940 // Update permissions
Kenny Root447106f2011-03-23 11:00:15 -0700941 for (String eachPerm : deletedPs.pkg.requestedPermissions) {
Todd Kennedy0eb97382017-10-03 16:57:22 -0700942 BasePermission bp = mPermissions.getPermission(eachPerm);
Svetoslavc6d1c342015-02-26 14:44:43 -0800943 if (bp == null) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700944 continue;
945 }
Svetoslavc6d1c342015-02-26 14:44:43 -0800946
Svetoslavc6d1c342015-02-26 14:44:43 -0800947 // Check if another package in the shared user needs the permission.
Svetoslav4a5f4a22015-07-07 18:18:15 -0700948 boolean used = false;
Svetoslavc6d1c342015-02-26 14:44:43 -0800949 for (PackageSetting pkg : sus.packages) {
950 if (pkg.pkg != null
951 && !pkg.pkg.packageName.equals(deletedPs.pkg.packageName)
952 && pkg.pkg.requestedPermissions.contains(eachPerm)) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700953 used = true;
954 break;
955 }
956 }
Svetoslav4a5f4a22015-07-07 18:18:15 -0700957 if (used) {
958 continue;
959 }
Svetoslavc6d1c342015-02-26 14:44:43 -0800960
Svetoslav4a5f4a22015-07-07 18:18:15 -0700961 PermissionsState permissionsState = sus.getPermissionsState();
962 PackageSetting disabledPs = getDisabledSystemPkgLPr(deletedPs.pkg.packageName);
Svet Ganov8c7f7002015-05-07 10:48:44 -0700963
Svetoslav4a5f4a22015-07-07 18:18:15 -0700964 // If the package is shadowing is a disabled system package,
965 // do not drop permissions that the shadowed package requests.
966 if (disabledPs != null) {
967 boolean reqByDisabledSysPkg = false;
968 for (String permission : disabledPs.pkg.requestedPermissions) {
969 if (permission.equals(eachPerm)) {
970 reqByDisabledSysPkg = true;
971 break;
972 }
Svetoslavc6d1c342015-02-26 14:44:43 -0800973 }
Svetoslav4a5f4a22015-07-07 18:18:15 -0700974 if (reqByDisabledSysPkg) {
975 continue;
Svetoslavc6d1c342015-02-26 14:44:43 -0800976 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700977 }
Svetoslav4a5f4a22015-07-07 18:18:15 -0700978
979 // Try to revoke as an install permission which is for all users.
980 // The package is gone - no need to keep flags for applying policy.
981 permissionsState.updatePermissionFlags(bp, userId,
Philip P. Moltmann76597692019-03-02 13:18:41 -0800982 PackageManager.MASK_PERMISSION_FLAGS_ALL, 0);
Svetoslav4a5f4a22015-07-07 18:18:15 -0700983
984 if (permissionsState.revokeInstallPermission(bp) ==
985 PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED) {
986 return UserHandle.USER_ALL;
987 }
988
989 // Try to revoke as an install permission which is per user.
990 if (permissionsState.revokeRuntimePermission(bp, userId) ==
991 PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED) {
992 return userId;
993 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700994 }
Svetoslavc6d1c342015-02-26 14:44:43 -0800995
996 return UserHandle.USER_NULL;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700997 }
998
Kenny Root447106f2011-03-23 11:00:15 -0700999 int removePackageLPw(String name) {
1000 final PackageSetting p = mPackages.get(name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001001 if (p != null) {
1002 mPackages.remove(name);
Sudheer Shanka29283372016-04-04 20:56:27 -07001003 removeInstallerPackageStatus(name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001004 if (p.sharedUser != null) {
Ben Gruverdd72c9e2013-08-06 12:34:17 -07001005 p.sharedUser.removePackage(p);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001006 if (p.sharedUser.packages.size() == 0) {
1007 mSharedUsers.remove(p.sharedUser.name);
Patrick Baumann649a8572018-11-20 11:16:58 -08001008 removeAppIdLPw(p.sharedUser.userId);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001009 return p.sharedUser.userId;
1010 }
1011 } else {
Patrick Baumann649a8572018-11-20 11:16:58 -08001012 removeAppIdLPw(p.appId);
Amith Yamasani13593602012-03-22 16:16:17 -07001013 return p.appId;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001014 }
1015 }
1016 return -1;
1017 }
1018
Sudheer Shanka29283372016-04-04 20:56:27 -07001019 /**
1020 * Checks if {@param packageName} is an installer package and if so, clear the installer
1021 * package name of the packages that are installed by this.
1022 */
1023 private void removeInstallerPackageStatus(String packageName) {
1024 // Check if the package to be removed is an installer package.
1025 if (!mInstallerPackages.contains(packageName)) {
1026 return;
1027 }
1028 for (int i = 0; i < mPackages.size(); i++) {
1029 final PackageSetting ps = mPackages.valueAt(i);
1030 final String installerPackageName = ps.getInstallerPackageName();
1031 if (installerPackageName != null
1032 && installerPackageName.equals(packageName)) {
1033 ps.setInstallerPackageName(null);
Sudheer Shanka8c57aea2016-04-20 16:47:50 -07001034 ps.isOrphaned = true;
Sudheer Shanka29283372016-04-04 20:56:27 -07001035 }
1036 }
1037 mInstallerPackages.remove(packageName);
1038 }
1039
Patrick Baumann649a8572018-11-20 11:16:58 -08001040 /** Returns true if the requested AppID was valid and not already registered. */
1041 private boolean registerExistingAppIdLPw(int appId, SettingBase obj, Object name) {
1042 if (appId > Process.LAST_APPLICATION_UID) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001043 return false;
1044 }
1045
Patrick Baumann649a8572018-11-20 11:16:58 -08001046 if (appId >= Process.FIRST_APPLICATION_UID) {
1047 int size = mAppIds.size();
1048 final int index = appId - Process.FIRST_APPLICATION_UID;
1049 // fill the array until our index becomes valid
1050 while (index >= size) {
1051 mAppIds.add(null);
1052 size++;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001053 }
Patrick Baumann649a8572018-11-20 11:16:58 -08001054 if (mAppIds.get(index) != null) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001055 PackageManagerService.reportSettingsProblem(Log.ERROR,
Patrick Baumann649a8572018-11-20 11:16:58 -08001056 "Adding duplicate app id: " + appId
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001057 + " name=" + name);
1058 return false;
1059 }
Patrick Baumann649a8572018-11-20 11:16:58 -08001060 mAppIds.set(index, obj);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001061 } else {
Patrick Baumann649a8572018-11-20 11:16:58 -08001062 if (mOtherAppIds.get(appId) != null) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001063 PackageManagerService.reportSettingsProblem(Log.ERROR,
Patrick Baumann649a8572018-11-20 11:16:58 -08001064 "Adding duplicate shared id: " + appId
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001065 + " name=" + name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001066 return false;
1067 }
Patrick Baumann649a8572018-11-20 11:16:58 -08001068 mOtherAppIds.put(appId, obj);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001069 }
1070 return true;
1071 }
1072
Patrick Baumann649a8572018-11-20 11:16:58 -08001073 /** Gets the setting associated with the provided App ID */
1074 public SettingBase getSettingLPr(int appId) {
1075 if (appId >= Process.FIRST_APPLICATION_UID) {
1076 final int size = mAppIds.size();
1077 final int index = appId - Process.FIRST_APPLICATION_UID;
1078 return index < size ? mAppIds.get(index) : null;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001079 } else {
Patrick Baumann649a8572018-11-20 11:16:58 -08001080 return mOtherAppIds.get(appId);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001081 }
1082 }
1083
Patrick Baumann649a8572018-11-20 11:16:58 -08001084 /** Unregisters the provided app ID. */
1085 void removeAppIdLPw(int appId) {
1086 if (appId >= Process.FIRST_APPLICATION_UID) {
1087 final int size = mAppIds.size();
1088 final int index = appId - Process.FIRST_APPLICATION_UID;
1089 if (index < size) mAppIds.set(index, null);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001090 } else {
Patrick Baumann649a8572018-11-20 11:16:58 -08001091 mOtherAppIds.remove(appId);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001092 }
Patrick Baumann649a8572018-11-20 11:16:58 -08001093 setFirstAvailableUid(appId + 1);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001094 }
1095
Patrick Baumann649a8572018-11-20 11:16:58 -08001096 private void replaceAppIdLPw(int appId, SettingBase obj) {
1097 if (appId >= Process.FIRST_APPLICATION_UID) {
1098 final int size = mAppIds.size();
1099 final int index = appId - Process.FIRST_APPLICATION_UID;
1100 if (index < size) mAppIds.set(index, obj);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001101 } else {
Patrick Baumann649a8572018-11-20 11:16:58 -08001102 mOtherAppIds.put(appId, obj);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001103 }
1104 }
1105
Dianne Hackborn63092712012-10-07 14:45:35 -07001106 PreferredIntentResolver editPreferredActivitiesLPw(int userId) {
1107 PreferredIntentResolver pir = mPreferredActivities.get(userId);
1108 if (pir == null) {
1109 pir = new PreferredIntentResolver();
1110 mPreferredActivities.put(userId, pir);
1111 }
1112 return pir;
1113 }
1114
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001115 PersistentPreferredIntentResolver editPersistentPreferredActivitiesLPw(int userId) {
1116 PersistentPreferredIntentResolver ppir = mPersistentPreferredActivities.get(userId);
1117 if (ppir == null) {
1118 ppir = new PersistentPreferredIntentResolver();
1119 mPersistentPreferredActivities.put(userId, ppir);
1120 }
1121 return ppir;
1122 }
1123
Nicolas Prevot81948992014-05-16 18:25:26 +01001124 CrossProfileIntentResolver editCrossProfileIntentResolverLPw(int userId) {
1125 CrossProfileIntentResolver cpir = mCrossProfileIntentResolvers.get(userId);
1126 if (cpir == null) {
1127 cpir = new CrossProfileIntentResolver();
1128 mCrossProfileIntentResolvers.put(userId, cpir);
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001129 }
Nicolas Prevot81948992014-05-16 18:25:26 +01001130 return cpir;
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001131 }
1132
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001133 /**
1134 * The following functions suppose that you have a lock for managing access to the
1135 * mIntentFiltersVerifications map.
1136 */
1137
1138 /* package protected */
1139 IntentFilterVerificationInfo getIntentFilterVerificationLPr(String packageName) {
1140 PackageSetting ps = mPackages.get(packageName);
1141 if (ps == null) {
Christopher Tate72c10a22015-06-12 18:31:24 -07001142 if (DEBUG_DOMAIN_VERIFICATION) {
1143 Slog.w(PackageManagerService.TAG, "No package known: " + packageName);
1144 }
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001145 return null;
1146 }
1147 return ps.getIntentFilterVerificationInfo();
1148 }
1149
1150 /* package protected */
Fabrice Di Meglio7d014ce2015-04-08 16:17:46 -07001151 IntentFilterVerificationInfo createIntentFilterVerificationIfNeededLPw(String packageName,
Todd Kennedy788c8422016-08-10 10:52:34 -07001152 ArraySet<String> domains) {
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001153 PackageSetting ps = mPackages.get(packageName);
1154 if (ps == null) {
Christopher Tate72c10a22015-06-12 18:31:24 -07001155 if (DEBUG_DOMAIN_VERIFICATION) {
1156 Slog.w(PackageManagerService.TAG, "No package known: " + packageName);
1157 }
Fabrice Di Meglio7d014ce2015-04-08 16:17:46 -07001158 return null;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001159 }
Fabrice Di Meglio7d014ce2015-04-08 16:17:46 -07001160 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
1161 if (ivi == null) {
1162 ivi = new IntentFilterVerificationInfo(packageName, domains);
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001163 ps.setIntentFilterVerificationInfo(ivi);
Christopher Tate72c10a22015-06-12 18:31:24 -07001164 if (DEBUG_DOMAIN_VERIFICATION) {
1165 Slog.d(PackageManagerService.TAG,
1166 "Creating new IntentFilterVerificationInfo for pkg: " + packageName);
1167 }
Fabrice Di Meglio1de3f0d2015-04-29 19:42:41 -07001168 } else {
1169 ivi.setDomains(domains);
Christopher Tate72c10a22015-06-12 18:31:24 -07001170 if (DEBUG_DOMAIN_VERIFICATION) {
1171 Slog.d(PackageManagerService.TAG,
1172 "Setting domains to existing IntentFilterVerificationInfo for pkg: " +
1173 packageName + " and with domains: " + ivi.getDomainsString());
1174 }
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001175 }
Fabrice Di Meglio7d014ce2015-04-08 16:17:46 -07001176 return ivi;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001177 }
1178
1179 int getIntentFilterVerificationStatusLPr(String packageName, int userId) {
1180 PackageSetting ps = mPackages.get(packageName);
1181 if (ps == null) {
Christopher Tate72c10a22015-06-12 18:31:24 -07001182 if (DEBUG_DOMAIN_VERIFICATION) {
1183 Slog.w(PackageManagerService.TAG, "No package known: " + packageName);
1184 }
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001185 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1186 }
Christopher Tated85a6642015-07-17 15:39:08 -07001187 return (int)(ps.getDomainVerificationStatusForUser(userId) >> 32);
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001188 }
1189
Christopher Tatef0d6cb32015-07-10 17:44:53 -07001190 boolean updateIntentFilterVerificationStatusLPw(String packageName, final int status, int userId) {
Fabrice Di Meglio07885952015-04-06 19:41:28 -07001191 // Update the status for the current package
1192 PackageSetting current = mPackages.get(packageName);
1193 if (current == null) {
Christopher Tate72c10a22015-06-12 18:31:24 -07001194 if (DEBUG_DOMAIN_VERIFICATION) {
1195 Slog.w(PackageManagerService.TAG, "No package known: " + packageName);
1196 }
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001197 return false;
1198 }
Christopher Tate050aee22015-07-01 16:50:43 -07001199
Christopher Tatef0d6cb32015-07-10 17:44:53 -07001200 final int alwaysGeneration;
1201 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
1202 alwaysGeneration = mNextAppLinkGeneration.get(userId) + 1;
1203 mNextAppLinkGeneration.put(userId, alwaysGeneration);
1204 } else {
1205 alwaysGeneration = 0;
1206 }
1207
1208 current.setDomainVerificationStatusForUser(status, alwaysGeneration, userId);
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001209 return true;
1210 }
1211
1212 /**
Fabrice Di Meglio07885952015-04-06 19:41:28 -07001213 * Used for Settings App and PackageManagerService dump. Should be read only.
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001214 */
1215 List<IntentFilterVerificationInfo> getIntentFilterVerificationsLPr(
1216 String packageName) {
1217 if (packageName == null) {
1218 return Collections.<IntentFilterVerificationInfo>emptyList();
1219 }
1220 ArrayList<IntentFilterVerificationInfo> result = new ArrayList<>();
1221 for (PackageSetting ps : mPackages.values()) {
1222 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
1223 if (ivi == null || TextUtils.isEmpty(ivi.getPackageName()) ||
1224 !ivi.getPackageName().equalsIgnoreCase(packageName)) {
1225 continue;
1226 }
1227 result.add(ivi);
1228 }
1229 return result;
1230 }
1231
Fabrice Di Meglio1f09b8c2015-05-06 18:51:21 -07001232 boolean removeIntentFilterVerificationLPw(String packageName, int userId) {
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001233 PackageSetting ps = mPackages.get(packageName);
1234 if (ps == null) {
Christopher Tate72c10a22015-06-12 18:31:24 -07001235 if (DEBUG_DOMAIN_VERIFICATION) {
1236 Slog.w(PackageManagerService.TAG, "No package known: " + packageName);
1237 }
Fabrice Di Meglio1f09b8c2015-05-06 18:51:21 -07001238 return false;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001239 }
1240 ps.clearDomainVerificationStatusForUser(userId);
Fabrice Di Meglio1f09b8c2015-05-06 18:51:21 -07001241 return true;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001242 }
1243
Fabrice Di Meglio1f09b8c2015-05-06 18:51:21 -07001244 boolean removeIntentFilterVerificationLPw(String packageName, int[] userIds) {
1245 boolean result = false;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001246 for (int userId : userIds) {
Fabrice Di Meglio1f09b8c2015-05-06 18:51:21 -07001247 result |= removeIntentFilterVerificationLPw(packageName, userId);
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001248 }
Fabrice Di Meglio1f09b8c2015-05-06 18:51:21 -07001249 return result;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001250 }
1251
Hai Zhanga22cd832019-01-30 13:38:43 -08001252 String removeDefaultBrowserPackageNameLPw(int userId) {
1253 return (userId == UserHandle.USER_ALL) ? null : mDefaultBrowserApp.removeReturnOld(userId);
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001254 }
1255
Robin Lee0dc591b2016-05-04 13:01:46 +01001256 boolean setDefaultDialerPackageNameLPw(String packageName, int userId) {
1257 if (userId == UserHandle.USER_ALL) {
1258 return false;
1259 }
1260 mDefaultDialerApp.put(userId, packageName);
1261 writePackageRestrictionsLPr(userId);
1262 return true;
1263 }
1264
1265 String getDefaultDialerPackageNameLPw(int userId) {
1266 return (userId == UserHandle.USER_ALL) ? null : mDefaultDialerApp.get(userId);
1267 }
1268
Amith Yamasani483f3b02012-03-13 16:08:00 -07001269 private File getUserPackagesStateFile(int userId) {
Svetoslavc6d1c342015-02-26 14:44:43 -08001270 // TODO: Implement a cleaner solution when adding tests.
1271 // This instead of Environment.getUserSystemDirectory(userId) to support testing.
1272 File userDir = new File(new File(mSystemDir, "users"), Integer.toString(userId));
1273 return new File(userDir, "package-restrictions.xml");
1274 }
1275
1276 private File getUserRuntimePermissionsFile(int userId) {
1277 // TODO: Implement a cleaner solution when adding tests.
1278 // This instead of Environment.getUserSystemDirectory(userId) to support testing.
1279 File userDir = new File(new File(mSystemDir, "users"), Integer.toString(userId));
1280 return new File(userDir, RUNTIME_PERMISSIONS_FILE_NAME);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001281 }
1282
1283 private File getUserPackagesStateBackupFile(int userId) {
Amith Yamasani61f57372012-08-31 12:12:28 -07001284 return new File(Environment.getUserSystemDirectory(userId),
1285 "package-restrictions-backup.xml");
Amith Yamasani483f3b02012-03-13 16:08:00 -07001286 }
1287
1288 void writeAllUsersPackageRestrictionsLPr() {
Todd Kennedy13715d52016-08-01 13:38:57 -07001289 List<UserInfo> users = getAllUsers(UserManagerService.getInstance());
Amith Yamasani483f3b02012-03-13 16:08:00 -07001290 if (users == null) return;
1291
1292 for (UserInfo user : users) {
1293 writePackageRestrictionsLPr(user.id);
1294 }
1295 }
1296
Svetoslavc6d1c342015-02-26 14:44:43 -08001297 void writeAllRuntimePermissionsLPr() {
1298 for (int userId : UserManagerService.getInstance().getUserIds()) {
1299 mRuntimePermissionsPersistence.writePermissionsForUserAsyncLPr(userId);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001300 }
1301 }
1302
Svet Ganovba3ba812015-06-26 10:54:06 -07001303 boolean areDefaultRuntimePermissionsGrantedLPr(int userId) {
1304 return mRuntimePermissionsPersistence
1305 .areDefaultRuntimPermissionsGrantedLPr(userId);
1306 }
1307
1308 void onDefaultRuntimePermissionsGrantedLPr(int userId) {
1309 mRuntimePermissionsPersistence
1310 .onDefaultRuntimePermissionsGrantedLPr(userId);
1311 }
1312
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07001313 public VersionInfo findOrCreateVersion(String volumeUuid) {
1314 VersionInfo ver = mVersion.get(volumeUuid);
1315 if (ver == null) {
1316 ver = new VersionInfo();
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07001317 mVersion.put(volumeUuid, ver);
1318 }
1319 return ver;
Kenny Rootc1c0d3c2014-04-24 13:36:40 -07001320 }
1321
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07001322 public VersionInfo getInternalVersion() {
1323 return mVersion.get(StorageManager.UUID_PRIVATE_INTERNAL);
Kenny Rootc1c0d3c2014-04-24 13:36:40 -07001324 }
1325
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07001326 public VersionInfo getExternalVersion() {
1327 return mVersion.get(StorageManager.UUID_PRIMARY_PHYSICAL);
Kenny Rootc1c0d3c2014-04-24 13:36:40 -07001328 }
1329
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07001330 public void onVolumeForgotten(String fsUuid) {
1331 mVersion.remove(fsUuid);
Kenny Rootc1c0d3c2014-04-24 13:36:40 -07001332 }
1333
Christopher Tatee012a232015-04-01 17:18:50 -07001334 /**
1335 * Applies the preferred activity state described by the given XML. This code
1336 * also supports the restore-from-backup code path.
1337 *
1338 * @see PreferredActivityBackupHelper
1339 */
1340 void readPreferredActivitiesLPw(XmlPullParser parser, int userId)
Dianne Hackborn63092712012-10-07 14:45:35 -07001341 throws XmlPullParserException, IOException {
1342 int outerDepth = parser.getDepth();
1343 int type;
1344 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1345 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1346 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1347 continue;
1348 }
1349
1350 String tagName = parser.getName();
1351 if (tagName.equals(TAG_ITEM)) {
1352 PreferredActivity pa = new PreferredActivity(parser);
1353 if (pa.mPref.getParseError() == null) {
1354 editPreferredActivitiesLPw(userId).addFilter(pa);
1355 } else {
1356 PackageManagerService.reportSettingsProblem(Log.WARN,
1357 "Error in package manager settings: <preferred-activity> "
1358 + pa.mPref.getParseError() + " at "
1359 + parser.getPositionDescription());
1360 }
1361 } else {
1362 PackageManagerService.reportSettingsProblem(Log.WARN,
1363 "Unknown element under <preferred-activities>: " + parser.getName());
1364 XmlUtils.skipCurrentTag(parser);
1365 }
1366 }
1367 }
1368
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001369 private void readPersistentPreferredActivitiesLPw(XmlPullParser parser, int userId)
1370 throws XmlPullParserException, IOException {
1371 int outerDepth = parser.getDepth();
1372 int type;
1373 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1374 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1375 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1376 continue;
1377 }
1378 String tagName = parser.getName();
1379 if (tagName.equals(TAG_ITEM)) {
1380 PersistentPreferredActivity ppa = new PersistentPreferredActivity(parser);
1381 editPersistentPreferredActivitiesLPw(userId).addFilter(ppa);
1382 } else {
1383 PackageManagerService.reportSettingsProblem(Log.WARN,
Sander Alewijnseaf597622014-03-20 18:44:57 +00001384 "Unknown element under <" + TAG_PERSISTENT_PREFERRED_ACTIVITIES + ">: "
1385 + parser.getName());
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001386 XmlUtils.skipCurrentTag(parser);
1387 }
1388 }
1389 }
1390
Nicolas Prevot81948992014-05-16 18:25:26 +01001391 private void readCrossProfileIntentFiltersLPw(XmlPullParser parser, int userId)
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001392 throws XmlPullParserException, IOException {
1393 int outerDepth = parser.getDepth();
1394 int type;
1395 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1396 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1397 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1398 continue;
1399 }
Christopher Tate6038d152015-06-17 13:07:46 -07001400 final String tagName = parser.getName();
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001401 if (tagName.equals(TAG_ITEM)) {
Nicolas Prevot81948992014-05-16 18:25:26 +01001402 CrossProfileIntentFilter cpif = new CrossProfileIntentFilter(parser);
1403 editCrossProfileIntentResolverLPw(userId).addFilter(cpif);
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001404 } else {
Nicolas Prevot81948992014-05-16 18:25:26 +01001405 String msg = "Unknown element under " + TAG_CROSS_PROFILE_INTENT_FILTERS + ": " +
Christopher Tate6038d152015-06-17 13:07:46 -07001406 tagName;
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001407 PackageManagerService.reportSettingsProblem(Log.WARN, msg);
1408 XmlUtils.skipCurrentTag(parser);
1409 }
1410 }
1411 }
1412
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001413 private void readDomainVerificationLPw(XmlPullParser parser, PackageSettingBase packageSetting)
1414 throws XmlPullParserException, IOException {
1415 IntentFilterVerificationInfo ivi = new IntentFilterVerificationInfo(parser);
1416 packageSetting.setIntentFilterVerificationInfo(ivi);
Todd Kennedy788c8422016-08-10 10:52:34 -07001417 if (DEBUG_PARSER) {
1418 Log.d(TAG, "Read domain verification for package: " + ivi.getPackageName());
1419 }
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001420 }
1421
Christopher Tate6038d152015-06-17 13:07:46 -07001422 private void readRestoredIntentFilterVerifications(XmlPullParser parser)
1423 throws XmlPullParserException, IOException {
1424 int outerDepth = parser.getDepth();
1425 int type;
1426 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1427 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1428 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1429 continue;
1430 }
1431 final String tagName = parser.getName();
1432 if (tagName.equals(TAG_DOMAIN_VERIFICATION)) {
1433 IntentFilterVerificationInfo ivi = new IntentFilterVerificationInfo(parser);
1434 if (DEBUG_DOMAIN_VERIFICATION) {
1435 Slog.i(TAG, "Restored IVI for " + ivi.getPackageName()
1436 + " status=" + ivi.getStatusString());
1437 }
1438 mRestoredIntentFilterVerifications.put(ivi.getPackageName(), ivi);
1439 } else {
1440 Slog.w(TAG, "Unknown element: " + tagName);
1441 XmlUtils.skipCurrentTag(parser);
1442 }
1443 }
1444 }
1445
1446 void readDefaultAppsLPw(XmlPullParser parser, int userId)
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001447 throws XmlPullParserException, IOException {
1448 int outerDepth = parser.getDepth();
1449 int type;
1450 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1451 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1452 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1453 continue;
1454 }
1455 String tagName = parser.getName();
1456 if (tagName.equals(TAG_DEFAULT_BROWSER)) {
1457 String packageName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
1458 mDefaultBrowserApp.put(userId, packageName);
Robin Lee0dc591b2016-05-04 13:01:46 +01001459 } else if (tagName.equals(TAG_DEFAULT_DIALER)) {
1460 String packageName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
1461 mDefaultDialerApp.put(userId, packageName);
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001462 } else {
1463 String msg = "Unknown element under " + TAG_DEFAULT_APPS + ": " +
1464 parser.getName();
1465 PackageManagerService.reportSettingsProblem(Log.WARN, msg);
1466 XmlUtils.skipCurrentTag(parser);
1467 }
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001468 }
1469 }
1470
Vladislav Kuzkokov253984e2016-10-24 09:27:16 +02001471 void readBlockUninstallPackagesLPw(XmlPullParser parser, int userId)
1472 throws XmlPullParserException, IOException {
1473 int outerDepth = parser.getDepth();
1474 int type;
1475 ArraySet<String> packages = new ArraySet<>();
1476 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1477 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1478 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1479 continue;
1480 }
1481 String tagName = parser.getName();
1482 if (tagName.equals(TAG_BLOCK_UNINSTALL)) {
1483 String packageName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
1484 packages.add(packageName);
1485 } else {
1486 String msg = "Unknown element under " + TAG_BLOCK_UNINSTALL_PACKAGES + ": " +
1487 parser.getName();
1488 PackageManagerService.reportSettingsProblem(Log.WARN, msg);
1489 XmlUtils.skipCurrentTag(parser);
1490 }
1491 }
1492 if (packages.isEmpty()) {
1493 mBlockUninstallPackages.remove(userId);
1494 } else {
1495 mBlockUninstallPackages.put(userId, packages);
1496 }
1497 }
1498
Amith Yamasani483f3b02012-03-13 16:08:00 -07001499 void readPackageRestrictionsLPr(int userId) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001500 if (DEBUG_MU) {
1501 Log.i(TAG, "Reading package restrictions for user=" + userId);
1502 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07001503 FileInputStream str = null;
1504 File userPackagesStateFile = getUserPackagesStateFile(userId);
1505 File backupFile = getUserPackagesStateBackupFile(userId);
1506 if (backupFile.exists()) {
1507 try {
1508 str = new FileInputStream(backupFile);
1509 mReadMessages.append("Reading from backup stopped packages file\n");
1510 PackageManagerService.reportSettingsProblem(Log.INFO,
1511 "Need to read from backup stopped packages file");
1512 if (userPackagesStateFile.exists()) {
1513 // If both the backup and normal file exist, we
1514 // ignore the normal one since it might have been
1515 // corrupted.
1516 Slog.w(PackageManagerService.TAG, "Cleaning up stopped packages file "
1517 + userPackagesStateFile);
1518 userPackagesStateFile.delete();
1519 }
1520 } catch (java.io.IOException e) {
1521 // We'll try for the normal settings file.
1522 }
1523 }
1524
1525 try {
1526 if (str == null) {
1527 if (!userPackagesStateFile.exists()) {
1528 mReadMessages.append("No stopped packages file found\n");
1529 PackageManagerService.reportSettingsProblem(Log.INFO,
1530 "No stopped packages file; "
1531 + "assuming all started");
1532 // At first boot, make sure no packages are stopped.
1533 // We usually want to have third party apps initialize
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001534 // in the stopped state, but not at first boot. Also
1535 // consider all applications to be installed.
Amith Yamasani483f3b02012-03-13 16:08:00 -07001536 for (PackageSetting pkg : mPackages.values()) {
Jeff Sharkey42884192016-04-09 16:12:01 -06001537 pkg.setUserState(userId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
Todd Kennedybe0b8892017-02-15 14:13:52 -08001538 true /*installed*/,
1539 false /*stopped*/,
1540 false /*notLaunched*/,
1541 false /*hidden*/,
Suprabh Shukla79000492018-12-24 17:03:02 -08001542 0 /*distractionFlags*/,
Todd Kennedybe0b8892017-02-15 14:13:52 -08001543 false /*suspended*/,
Suprabh Shukla151b21b2018-04-27 19:30:30 -07001544 null /*suspendingPackage*/,
Suprabh Shukla389cb6f2018-10-01 18:20:39 -07001545 null /*dialogInfo*/,
Suprabh Shukla151b21b2018-04-27 19:30:30 -07001546 null /*suspendedAppExtras*/,
1547 null /*suspendedLauncherExtras*/,
Todd Kennedybe0b8892017-02-15 14:13:52 -08001548 false /*instantApp*/,
Todd Kennedy5eb5a7d2017-08-01 07:42:47 -07001549 false /*virtualPreload*/,
Todd Kennedybe0b8892017-02-15 14:13:52 -08001550 null /*lastDisableAppCaller*/,
1551 null /*enabledComponents*/,
1552 null /*disabledComponents*/,
Todd Kennedybe0b8892017-02-15 14:13:52 -08001553 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED,
Ben Gruver1ab3d6e2017-12-07 13:45:08 -08001554 0, PackageManager.INSTALL_REASON_UNKNOWN,
1555 null /*harmfulAppWarning*/);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001556 }
1557 return;
1558 }
1559 str = new FileInputStream(userPackagesStateFile);
1560 }
1561 final XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001562 parser.setInput(str, StandardCharsets.UTF_8.name());
Amith Yamasani483f3b02012-03-13 16:08:00 -07001563
1564 int type;
1565 while ((type=parser.next()) != XmlPullParser.START_TAG
1566 && type != XmlPullParser.END_DOCUMENT) {
1567 ;
1568 }
1569
1570 if (type != XmlPullParser.START_TAG) {
1571 mReadMessages.append("No start tag found in package restrictions file\n");
1572 PackageManagerService.reportSettingsProblem(Log.WARN,
1573 "No start tag found in package manager stopped packages");
1574 return;
1575 }
1576
Christopher Tatef0d6cb32015-07-10 17:44:53 -07001577 int maxAppLinkGeneration = 0;
1578
Amith Yamasani483f3b02012-03-13 16:08:00 -07001579 int outerDepth = parser.getDepth();
1580 PackageSetting ps = null;
1581 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1582 && (type != XmlPullParser.END_TAG
1583 || parser.getDepth() > outerDepth)) {
1584 if (type == XmlPullParser.END_TAG
1585 || type == XmlPullParser.TEXT) {
1586 continue;
1587 }
1588
1589 String tagName = parser.getName();
1590 if (tagName.equals(TAG_PACKAGE)) {
1591 String name = parser.getAttributeValue(null, ATTR_NAME);
1592 ps = mPackages.get(name);
1593 if (ps == null) {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001594 Slog.w(PackageManagerService.TAG, "No package known for stopped package "
Amith Yamasani483f3b02012-03-13 16:08:00 -07001595 + name);
1596 XmlUtils.skipCurrentTag(parser);
1597 continue;
1598 }
Jeff Sharkey42884192016-04-09 16:12:01 -06001599
1600 final long ceDataInode = XmlUtils.readLongAttribute(parser, ATTR_CE_DATA_INODE,
1601 0);
1602 final boolean installed = XmlUtils.readBooleanAttribute(parser, ATTR_INSTALLED,
1603 true);
1604 final boolean stopped = XmlUtils.readBooleanAttribute(parser, ATTR_STOPPED,
1605 false);
1606 final boolean notLaunched = XmlUtils.readBooleanAttribute(parser,
1607 ATTR_NOT_LAUNCHED, false);
1608
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001609 // For backwards compatibility with the previous name of "blocked", which
1610 // now means hidden, read the old attribute as well.
Amith Yamasani655d0e22013-06-12 14:19:10 -07001611 final String blockedStr = parser.getAttributeValue(null, ATTR_BLOCKED);
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001612 boolean hidden = blockedStr == null
Amith Yamasani655d0e22013-06-12 14:19:10 -07001613 ? false : Boolean.parseBoolean(blockedStr);
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001614 final String hiddenStr = parser.getAttributeValue(null, ATTR_HIDDEN);
1615 hidden = hiddenStr == null
1616 ? hidden : Boolean.parseBoolean(hiddenStr);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001617
Suprabh Shukla79000492018-12-24 17:03:02 -08001618 final int distractionFlags = XmlUtils.readIntAttribute(parser,
1619 ATTR_DISTRACTION_FLAGS, 0);
Jeff Sharkey42884192016-04-09 16:12:01 -06001620 final boolean suspended = XmlUtils.readBooleanAttribute(parser, ATTR_SUSPENDED,
1621 false);
Suprabh Shukla021b57a2018-03-08 18:21:50 -08001622 String suspendingPackage = parser.getAttributeValue(null,
1623 ATTR_SUSPENDING_PACKAGE);
Suprabh Shukla3c3af142018-03-30 00:28:37 -07001624 final String dialogMessage = parser.getAttributeValue(null,
1625 ATTR_SUSPEND_DIALOG_MESSAGE);
Suprabh Shukla021b57a2018-03-08 18:21:50 -08001626 if (suspended && suspendingPackage == null) {
1627 suspendingPackage = PLATFORM_PACKAGE_NAME;
1628 }
1629
Jeff Sharkey42884192016-04-09 16:12:01 -06001630 final boolean blockUninstall = XmlUtils.readBooleanAttribute(parser,
1631 ATTR_BLOCK_UNINSTALL, false);
Todd Kennedybe0b8892017-02-15 14:13:52 -08001632 final boolean instantApp = XmlUtils.readBooleanAttribute(parser,
1633 ATTR_INSTANT_APP, false);
Todd Kennedy5eb5a7d2017-08-01 07:42:47 -07001634 final boolean virtualPreload = XmlUtils.readBooleanAttribute(parser,
1635 ATTR_VIRTUAL_PRELOAD, false);
Jeff Sharkey42884192016-04-09 16:12:01 -06001636 final int enabled = XmlUtils.readIntAttribute(parser, ATTR_ENABLED,
1637 COMPONENT_ENABLED_STATE_DEFAULT);
1638 final String enabledCaller = parser.getAttributeValue(null,
1639 ATTR_ENABLED_CALLER);
Ben Gruver1ab3d6e2017-12-07 13:45:08 -08001640 final String harmfulAppWarning =
1641 parser.getAttributeValue(null, ATTR_HARMFUL_APP_WARNING);
Jeff Sharkey42884192016-04-09 16:12:01 -06001642 final int verifState = XmlUtils.readIntAttribute(parser,
1643 ATTR_DOMAIN_VERIFICATON_STATE,
1644 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
1645 final int linkGeneration = XmlUtils.readIntAttribute(parser,
1646 ATTR_APP_LINK_GENERATION, 0);
Christopher Tatef0d6cb32015-07-10 17:44:53 -07001647 if (linkGeneration > maxAppLinkGeneration) {
1648 maxAppLinkGeneration = linkGeneration;
1649 }
Bartosz Fabianowskia34f53f2017-01-11 18:08:47 +01001650 final int installReason = XmlUtils.readIntAttribute(parser,
1651 ATTR_INSTALL_REASON, PackageManager.INSTALL_REASON_UNKNOWN);
Christopher Tatef0d6cb32015-07-10 17:44:53 -07001652
Jeff Sharkey9f837a92014-10-24 12:07:24 -07001653 ArraySet<String> enabledComponents = null;
1654 ArraySet<String> disabledComponents = null;
Suprabh Shukla021b57a2018-03-08 18:21:50 -08001655 PersistableBundle suspendedAppExtras = null;
1656 PersistableBundle suspendedLauncherExtras = null;
Suprabh Shukla389cb6f2018-10-01 18:20:39 -07001657 SuspendDialogInfo suspendDialogInfo = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001658
1659 int packageDepth = parser.getDepth();
1660 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1661 && (type != XmlPullParser.END_TAG
1662 || parser.getDepth() > packageDepth)) {
1663 if (type == XmlPullParser.END_TAG
1664 || type == XmlPullParser.TEXT) {
1665 continue;
1666 }
Suprabh Shukla021b57a2018-03-08 18:21:50 -08001667 switch (parser.getName()) {
1668 case TAG_ENABLED_COMPONENTS:
1669 enabledComponents = readComponentsLPr(parser);
1670 break;
1671 case TAG_DISABLED_COMPONENTS:
1672 disabledComponents = readComponentsLPr(parser);
1673 break;
1674 case TAG_SUSPENDED_APP_EXTRAS:
1675 suspendedAppExtras = PersistableBundle.restoreFromXml(parser);
1676 break;
1677 case TAG_SUSPENDED_LAUNCHER_EXTRAS:
1678 suspendedLauncherExtras = PersistableBundle.restoreFromXml(parser);
1679 break;
Suprabh Shukla389cb6f2018-10-01 18:20:39 -07001680 case TAG_SUSPENDED_DIALOG_INFO:
1681 suspendDialogInfo = SuspendDialogInfo.restoreFromXml(parser);
1682 break;
Suprabh Shukla021b57a2018-03-08 18:21:50 -08001683 default:
1684 Slog.wtf(TAG, "Unknown tag " + parser.getName() + " under tag "
1685 + TAG_PACKAGE);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001686 }
1687 }
Suprabh Shukla389cb6f2018-10-01 18:20:39 -07001688 if (suspendDialogInfo == null && !TextUtils.isEmpty(dialogMessage)) {
1689 suspendDialogInfo = new SuspendDialogInfo.Builder()
1690 .setMessage(dialogMessage)
1691 .build();
1692 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001693
Vladislav Kuzkokov253984e2016-10-24 09:27:16 +02001694 if (blockUninstall) {
1695 setBlockUninstallLPw(userId, name, true);
1696 }
Jeff Sharkey42884192016-04-09 16:12:01 -06001697 ps.setUserState(userId, ceDataInode, enabled, installed, stopped, notLaunched,
Suprabh Shukla79000492018-12-24 17:03:02 -08001698 hidden, distractionFlags, suspended, suspendingPackage,
1699 suspendDialogInfo,
Suprabh Shukla389cb6f2018-10-01 18:20:39 -07001700 suspendedAppExtras, suspendedLauncherExtras, instantApp, virtualPreload,
1701 enabledCaller, enabledComponents, disabledComponents, verifState,
1702 linkGeneration, installReason, harmfulAppWarning);
Dianne Hackborn63092712012-10-07 14:45:35 -07001703 } else if (tagName.equals("preferred-activities")) {
1704 readPreferredActivitiesLPw(parser, userId);
Sander Alewijnseaf597622014-03-20 18:44:57 +00001705 } else if (tagName.equals(TAG_PERSISTENT_PREFERRED_ACTIVITIES)) {
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001706 readPersistentPreferredActivitiesLPw(parser, userId);
Nicolas Prevot29762c32014-07-29 18:51:32 +01001707 } else if (tagName.equals(TAG_CROSS_PROFILE_INTENT_FILTERS)) {
Nicolas Prevot81948992014-05-16 18:25:26 +01001708 readCrossProfileIntentFiltersLPw(parser, userId);
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001709 } else if (tagName.equals(TAG_DEFAULT_APPS)) {
1710 readDefaultAppsLPw(parser, userId);
Vladislav Kuzkokov253984e2016-10-24 09:27:16 +02001711 } else if (tagName.equals(TAG_BLOCK_UNINSTALL_PACKAGES)) {
1712 readBlockUninstallPackagesLPw(parser, userId);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001713 } else {
1714 Slog.w(PackageManagerService.TAG, "Unknown element under <stopped-packages>: "
1715 + parser.getName());
1716 XmlUtils.skipCurrentTag(parser);
1717 }
1718 }
1719
1720 str.close();
1721
Christopher Tatef0d6cb32015-07-10 17:44:53 -07001722 mNextAppLinkGeneration.put(userId, maxAppLinkGeneration + 1);
1723
Amith Yamasani483f3b02012-03-13 16:08:00 -07001724 } catch (XmlPullParserException e) {
1725 mReadMessages.append("Error reading: " + e.toString());
1726 PackageManagerService.reportSettingsProblem(Log.ERROR,
1727 "Error reading stopped packages: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07001728 Slog.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages",
1729 e);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001730
1731 } catch (java.io.IOException e) {
1732 mReadMessages.append("Error reading: " + e.toString());
1733 PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07001734 Slog.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages",
1735 e);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001736 }
1737 }
1738
Vladislav Kuzkokov253984e2016-10-24 09:27:16 +02001739 void setBlockUninstallLPw(int userId, String packageName, boolean blockUninstall) {
1740 ArraySet<String> packages = mBlockUninstallPackages.get(userId);
1741 if (blockUninstall) {
1742 if (packages == null) {
1743 packages = new ArraySet<String>();
1744 mBlockUninstallPackages.put(userId, packages);
1745 }
1746 packages.add(packageName);
1747 } else if (packages != null) {
1748 packages.remove(packageName);
1749 if (packages.isEmpty()) {
1750 mBlockUninstallPackages.remove(userId);
1751 }
1752 }
1753 }
1754
1755 boolean getBlockUninstallLPr(int userId, String packageName) {
1756 ArraySet<String> packages = mBlockUninstallPackages.get(userId);
1757 if (packages == null) {
1758 return false;
1759 }
1760 return packages.contains(packageName);
1761 }
1762
Jeff Sharkey9f837a92014-10-24 12:07:24 -07001763 private ArraySet<String> readComponentsLPr(XmlPullParser parser)
Amith Yamasani483f3b02012-03-13 16:08:00 -07001764 throws IOException, XmlPullParserException {
Jeff Sharkey9f837a92014-10-24 12:07:24 -07001765 ArraySet<String> components = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001766 int type;
1767 int outerDepth = parser.getDepth();
1768 String tagName;
1769 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1770 && (type != XmlPullParser.END_TAG
1771 || parser.getDepth() > outerDepth)) {
1772 if (type == XmlPullParser.END_TAG
1773 || type == XmlPullParser.TEXT) {
1774 continue;
1775 }
1776 tagName = parser.getName();
1777 if (tagName.equals(TAG_ITEM)) {
1778 String componentName = parser.getAttributeValue(null, ATTR_NAME);
1779 if (componentName != null) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001780 if (components == null) {
Jeff Sharkey9f837a92014-10-24 12:07:24 -07001781 components = new ArraySet<String>();
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001782 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07001783 components.add(componentName);
1784 }
1785 }
1786 }
1787 return components;
1788 }
1789
Christopher Tatee012a232015-04-01 17:18:50 -07001790 /**
1791 * Record the state of preferred activity configuration into XML. This is used both
1792 * for recording packages.xml internally and for supporting backup/restore of the
1793 * preferred activity configuration.
1794 */
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08001795 void writePreferredActivitiesLPr(XmlSerializer serializer, int userId, boolean full)
Dianne Hackborn63092712012-10-07 14:45:35 -07001796 throws IllegalArgumentException, IllegalStateException, IOException {
1797 serializer.startTag(null, "preferred-activities");
1798 PreferredIntentResolver pir = mPreferredActivities.get(userId);
1799 if (pir != null) {
1800 for (final PreferredActivity pa : pir.filterSet()) {
1801 serializer.startTag(null, TAG_ITEM);
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08001802 pa.writeToXml(serializer, full);
Dianne Hackborn63092712012-10-07 14:45:35 -07001803 serializer.endTag(null, TAG_ITEM);
1804 }
1805 }
1806 serializer.endTag(null, "preferred-activities");
1807 }
1808
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001809 void writePersistentPreferredActivitiesLPr(XmlSerializer serializer, int userId)
1810 throws IllegalArgumentException, IllegalStateException, IOException {
Sander Alewijnseaf597622014-03-20 18:44:57 +00001811 serializer.startTag(null, TAG_PERSISTENT_PREFERRED_ACTIVITIES);
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001812 PersistentPreferredIntentResolver ppir = mPersistentPreferredActivities.get(userId);
1813 if (ppir != null) {
1814 for (final PersistentPreferredActivity ppa : ppir.filterSet()) {
1815 serializer.startTag(null, TAG_ITEM);
1816 ppa.writeToXml(serializer);
1817 serializer.endTag(null, TAG_ITEM);
1818 }
1819 }
Sander Alewijnseaf597622014-03-20 18:44:57 +00001820 serializer.endTag(null, TAG_PERSISTENT_PREFERRED_ACTIVITIES);
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001821 }
1822
Nicolas Prevot81948992014-05-16 18:25:26 +01001823 void writeCrossProfileIntentFiltersLPr(XmlSerializer serializer, int userId)
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001824 throws IllegalArgumentException, IllegalStateException, IOException {
Nicolas Prevot81948992014-05-16 18:25:26 +01001825 serializer.startTag(null, TAG_CROSS_PROFILE_INTENT_FILTERS);
1826 CrossProfileIntentResolver cpir = mCrossProfileIntentResolvers.get(userId);
1827 if (cpir != null) {
1828 for (final CrossProfileIntentFilter cpif : cpir.filterSet()) {
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001829 serializer.startTag(null, TAG_ITEM);
Nicolas Prevot81948992014-05-16 18:25:26 +01001830 cpif.writeToXml(serializer);
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001831 serializer.endTag(null, TAG_ITEM);
1832 }
1833 }
Nicolas Prevot81948992014-05-16 18:25:26 +01001834 serializer.endTag(null, TAG_CROSS_PROFILE_INTENT_FILTERS);
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001835 }
1836
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001837 void writeDomainVerificationsLPr(XmlSerializer serializer,
1838 IntentFilterVerificationInfo verificationInfo)
1839 throws IllegalArgumentException, IllegalStateException, IOException {
1840 if (verificationInfo != null && verificationInfo.getPackageName() != null) {
1841 serializer.startTag(null, TAG_DOMAIN_VERIFICATION);
1842 verificationInfo.writeToXml(serializer);
Christopher Tate72c10a22015-06-12 18:31:24 -07001843 if (DEBUG_DOMAIN_VERIFICATION) {
1844 Slog.d(TAG, "Wrote domain verification for package: "
1845 + verificationInfo.getPackageName());
1846 }
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001847 serializer.endTag(null, TAG_DOMAIN_VERIFICATION);
1848 }
1849 }
1850
Christopher Tate6038d152015-06-17 13:07:46 -07001851 // Specifically for backup/restore
1852 void writeAllDomainVerificationsLPr(XmlSerializer serializer, int userId)
1853 throws IllegalArgumentException, IllegalStateException, IOException {
1854 serializer.startTag(null, TAG_ALL_INTENT_FILTER_VERIFICATION);
1855 final int N = mPackages.size();
1856 for (int i = 0; i < N; i++) {
1857 PackageSetting ps = mPackages.valueAt(i);
1858 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
1859 if (ivi != null) {
1860 writeDomainVerificationsLPr(serializer, ivi);
1861 }
1862 }
1863 serializer.endTag(null, TAG_ALL_INTENT_FILTER_VERIFICATION);
1864 }
1865
1866 // Specifically for backup/restore
1867 void readAllDomainVerificationsLPr(XmlPullParser parser, int userId)
1868 throws XmlPullParserException, IOException {
1869 mRestoredIntentFilterVerifications.clear();
1870
1871 int outerDepth = parser.getDepth();
1872 int type;
1873 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1874 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1875 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1876 continue;
1877 }
1878
1879 String tagName = parser.getName();
1880 if (tagName.equals(TAG_DOMAIN_VERIFICATION)) {
1881 IntentFilterVerificationInfo ivi = new IntentFilterVerificationInfo(parser);
1882 final String pkgName = ivi.getPackageName();
1883 final PackageSetting ps = mPackages.get(pkgName);
1884 if (ps != null) {
1885 // known/existing package; update in place
1886 ps.setIntentFilterVerificationInfo(ivi);
1887 if (DEBUG_DOMAIN_VERIFICATION) {
1888 Slog.d(TAG, "Restored IVI for existing app " + pkgName
1889 + " status=" + ivi.getStatusString());
1890 }
1891 } else {
1892 mRestoredIntentFilterVerifications.put(pkgName, ivi);
1893 if (DEBUG_DOMAIN_VERIFICATION) {
1894 Slog.d(TAG, "Restored IVI for pending app " + pkgName
1895 + " status=" + ivi.getStatusString());
1896 }
1897 }
1898 } else {
1899 PackageManagerService.reportSettingsProblem(Log.WARN,
1900 "Unknown element under <all-intent-filter-verification>: "
1901 + parser.getName());
1902 XmlUtils.skipCurrentTag(parser);
1903 }
1904 }
1905 }
1906
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001907 void writeDefaultAppsLPr(XmlSerializer serializer, int userId)
1908 throws IllegalArgumentException, IllegalStateException, IOException {
1909 serializer.startTag(null, TAG_DEFAULT_APPS);
Robin Lee0dc591b2016-05-04 13:01:46 +01001910 String defaultBrowser = mDefaultBrowserApp.get(userId);
1911 if (!TextUtils.isEmpty(defaultBrowser)) {
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001912 serializer.startTag(null, TAG_DEFAULT_BROWSER);
Robin Lee0dc591b2016-05-04 13:01:46 +01001913 serializer.attribute(null, ATTR_PACKAGE_NAME, defaultBrowser);
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001914 serializer.endTag(null, TAG_DEFAULT_BROWSER);
1915 }
Robin Lee0dc591b2016-05-04 13:01:46 +01001916 String defaultDialer = mDefaultDialerApp.get(userId);
1917 if (!TextUtils.isEmpty(defaultDialer)) {
1918 serializer.startTag(null, TAG_DEFAULT_DIALER);
1919 serializer.attribute(null, ATTR_PACKAGE_NAME, defaultDialer);
1920 serializer.endTag(null, TAG_DEFAULT_DIALER);
1921 }
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001922 serializer.endTag(null, TAG_DEFAULT_APPS);
1923 }
1924
Vladislav Kuzkokov253984e2016-10-24 09:27:16 +02001925 void writeBlockUninstallPackagesLPr(XmlSerializer serializer, int userId)
1926 throws IOException {
1927 ArraySet<String> packages = mBlockUninstallPackages.get(userId);
1928 if (packages != null) {
1929 serializer.startTag(null, TAG_BLOCK_UNINSTALL_PACKAGES);
1930 for (int i = 0; i < packages.size(); i++) {
1931 serializer.startTag(null, TAG_BLOCK_UNINSTALL);
1932 serializer.attribute(null, ATTR_PACKAGE_NAME, packages.valueAt(i));
1933 serializer.endTag(null, TAG_BLOCK_UNINSTALL);
1934 }
1935 serializer.endTag(null, TAG_BLOCK_UNINSTALL_PACKAGES);
1936 }
1937 }
1938
Amith Yamasani483f3b02012-03-13 16:08:00 -07001939 void writePackageRestrictionsLPr(int userId) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001940 if (DEBUG_MU) {
1941 Log.i(TAG, "Writing package restrictions for user=" + userId);
1942 }
Dianne Hackborne17b4452018-01-10 13:15:40 -08001943 final long startTime = SystemClock.uptimeMillis();
1944
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001945 // Keep the old stopped packages around until we know the new ones have
1946 // been successfully written.
Amith Yamasani483f3b02012-03-13 16:08:00 -07001947 File userPackagesStateFile = getUserPackagesStateFile(userId);
1948 File backupFile = getUserPackagesStateBackupFile(userId);
1949 new File(userPackagesStateFile.getParent()).mkdirs();
1950 if (userPackagesStateFile.exists()) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001951 // Presence of backup settings file indicates that we failed
1952 // to persist packages earlier. So preserve the older
1953 // backup for future reference since the current packages
1954 // might have been corrupted.
Amith Yamasani483f3b02012-03-13 16:08:00 -07001955 if (!backupFile.exists()) {
1956 if (!userPackagesStateFile.renameTo(backupFile)) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07001957 Slog.wtf(PackageManagerService.TAG,
1958 "Unable to backup user packages state file, "
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001959 + "current changes will be lost at reboot");
1960 return;
1961 }
1962 } else {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001963 userPackagesStateFile.delete();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001964 Slog.w(PackageManagerService.TAG, "Preserving older stopped packages backup");
1965 }
1966 }
1967
1968 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001969 final FileOutputStream fstr = new FileOutputStream(userPackagesStateFile);
Kenny Root447106f2011-03-23 11:00:15 -07001970 final BufferedOutputStream str = new BufferedOutputStream(fstr);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001971
Kenny Root447106f2011-03-23 11:00:15 -07001972 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001973 serializer.setOutput(str, StandardCharsets.UTF_8.name());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001974 serializer.startDocument(null, true);
1975 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1976
Amith Yamasani483f3b02012-03-13 16:08:00 -07001977 serializer.startTag(null, TAG_PACKAGE_RESTRICTIONS);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001978
Kenny Root447106f2011-03-23 11:00:15 -07001979 for (final PackageSetting pkg : mPackages.values()) {
Jeff Sharkey42884192016-04-09 16:12:01 -06001980 final PackageUserState ustate = pkg.readUserState(userId);
1981 if (DEBUG_MU) Log.i(TAG, " pkg=" + pkg.name + ", state=" + ustate.enabled);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001982
Jeff Sharkey42884192016-04-09 16:12:01 -06001983 serializer.startTag(null, TAG_PACKAGE);
1984 serializer.attribute(null, ATTR_NAME, pkg.name);
1985 if (ustate.ceDataInode != 0) {
1986 XmlUtils.writeLongAttribute(serializer, ATTR_CE_DATA_INODE, ustate.ceDataInode);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001987 }
Jeff Sharkey42884192016-04-09 16:12:01 -06001988 if (!ustate.installed) {
1989 serializer.attribute(null, ATTR_INSTALLED, "false");
1990 }
1991 if (ustate.stopped) {
1992 serializer.attribute(null, ATTR_STOPPED, "true");
1993 }
1994 if (ustate.notLaunched) {
1995 serializer.attribute(null, ATTR_NOT_LAUNCHED, "true");
1996 }
1997 if (ustate.hidden) {
1998 serializer.attribute(null, ATTR_HIDDEN, "true");
1999 }
Suprabh Shukla79000492018-12-24 17:03:02 -08002000 if (ustate.distractionFlags != 0) {
2001 serializer.attribute(null, ATTR_DISTRACTION_FLAGS,
2002 Integer.toString(ustate.distractionFlags));
2003 }
Jeff Sharkey42884192016-04-09 16:12:01 -06002004 if (ustate.suspended) {
2005 serializer.attribute(null, ATTR_SUSPENDED, "true");
Suprabh Shukla3c3af142018-03-30 00:28:37 -07002006 if (ustate.suspendingPackage != null) {
2007 serializer.attribute(null, ATTR_SUSPENDING_PACKAGE,
2008 ustate.suspendingPackage);
2009 }
Suprabh Shukla389cb6f2018-10-01 18:20:39 -07002010 if (ustate.dialogInfo != null) {
2011 serializer.startTag(null, TAG_SUSPENDED_DIALOG_INFO);
2012 ustate.dialogInfo.saveToXml(serializer);
2013 serializer.endTag(null, TAG_SUSPENDED_DIALOG_INFO);
Suprabh Shukla3c3af142018-03-30 00:28:37 -07002014 }
Suprabh Shukla021b57a2018-03-08 18:21:50 -08002015 if (ustate.suspendedAppExtras != null) {
2016 serializer.startTag(null, TAG_SUSPENDED_APP_EXTRAS);
2017 try {
2018 ustate.suspendedAppExtras.saveToXml(serializer);
2019 } catch (XmlPullParserException xmle) {
2020 Slog.wtf(TAG, "Exception while trying to write suspendedAppExtras for "
2021 + pkg + ". Will be lost on reboot", xmle);
2022 }
2023 serializer.endTag(null, TAG_SUSPENDED_APP_EXTRAS);
2024 }
2025 if (ustate.suspendedLauncherExtras != null) {
2026 serializer.startTag(null, TAG_SUSPENDED_LAUNCHER_EXTRAS);
2027 try {
2028 ustate.suspendedLauncherExtras.saveToXml(serializer);
2029 } catch (XmlPullParserException xmle) {
2030 Slog.wtf(TAG, "Exception while trying to write suspendedLauncherExtras"
2031 + " for " + pkg + ". Will be lost on reboot", xmle);
2032 }
2033 serializer.endTag(null, TAG_SUSPENDED_LAUNCHER_EXTRAS);
2034 }
Jeff Sharkey42884192016-04-09 16:12:01 -06002035 }
Todd Kennedybe0b8892017-02-15 14:13:52 -08002036 if (ustate.instantApp) {
2037 serializer.attribute(null, ATTR_INSTANT_APP, "true");
2038 }
Todd Kennedy5eb5a7d2017-08-01 07:42:47 -07002039 if (ustate.virtualPreload) {
2040 serializer.attribute(null, ATTR_VIRTUAL_PRELOAD, "true");
2041 }
Jeff Sharkey42884192016-04-09 16:12:01 -06002042 if (ustate.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
2043 serializer.attribute(null, ATTR_ENABLED,
2044 Integer.toString(ustate.enabled));
2045 if (ustate.lastDisableAppCaller != null) {
2046 serializer.attribute(null, ATTR_ENABLED_CALLER,
2047 ustate.lastDisableAppCaller);
2048 }
2049 }
2050 if (ustate.domainVerificationStatus !=
2051 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
2052 XmlUtils.writeIntAttribute(serializer, ATTR_DOMAIN_VERIFICATON_STATE,
2053 ustate.domainVerificationStatus);
2054 }
2055 if (ustate.appLinkGeneration != 0) {
2056 XmlUtils.writeIntAttribute(serializer, ATTR_APP_LINK_GENERATION,
2057 ustate.appLinkGeneration);
2058 }
Bartosz Fabianowskia34f53f2017-01-11 18:08:47 +01002059 if (ustate.installReason != PackageManager.INSTALL_REASON_UNKNOWN) {
2060 serializer.attribute(null, ATTR_INSTALL_REASON,
2061 Integer.toString(ustate.installReason));
2062 }
Ben Gruver1ab3d6e2017-12-07 13:45:08 -08002063 if (ustate.harmfulAppWarning != null) {
2064 serializer.attribute(null, ATTR_HARMFUL_APP_WARNING,
2065 ustate.harmfulAppWarning);
2066 }
Jeff Sharkey42884192016-04-09 16:12:01 -06002067 if (!ArrayUtils.isEmpty(ustate.enabledComponents)) {
2068 serializer.startTag(null, TAG_ENABLED_COMPONENTS);
2069 for (final String name : ustate.enabledComponents) {
2070 serializer.startTag(null, TAG_ITEM);
2071 serializer.attribute(null, ATTR_NAME, name);
2072 serializer.endTag(null, TAG_ITEM);
2073 }
2074 serializer.endTag(null, TAG_ENABLED_COMPONENTS);
2075 }
2076 if (!ArrayUtils.isEmpty(ustate.disabledComponents)) {
2077 serializer.startTag(null, TAG_DISABLED_COMPONENTS);
2078 for (final String name : ustate.disabledComponents) {
2079 serializer.startTag(null, TAG_ITEM);
2080 serializer.attribute(null, ATTR_NAME, name);
2081 serializer.endTag(null, TAG_ITEM);
2082 }
2083 serializer.endTag(null, TAG_DISABLED_COMPONENTS);
2084 }
2085
2086 serializer.endTag(null, TAG_PACKAGE);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002087 }
2088
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08002089 writePreferredActivitiesLPr(serializer, userId, true);
Sander Alewijnsef475ca32014-02-17 15:13:58 +00002090 writePersistentPreferredActivitiesLPr(serializer, userId);
Nicolas Prevot81948992014-05-16 18:25:26 +01002091 writeCrossProfileIntentFiltersLPr(serializer, userId);
Fabrice Di Meglio62271722015-04-10 17:24:02 -07002092 writeDefaultAppsLPr(serializer, userId);
Vladislav Kuzkokov253984e2016-10-24 09:27:16 +02002093 writeBlockUninstallPackagesLPr(serializer, userId);
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00002094
Amith Yamasani483f3b02012-03-13 16:08:00 -07002095 serializer.endTag(null, TAG_PACKAGE_RESTRICTIONS);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002096
2097 serializer.endDocument();
2098
2099 str.flush();
2100 FileUtils.sync(fstr);
2101 str.close();
2102
2103 // New settings successfully written, old ones are no longer
2104 // needed.
Amith Yamasani483f3b02012-03-13 16:08:00 -07002105 backupFile.delete();
2106 FileUtils.setPermissions(userPackagesStateFile.toString(),
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002107 FileUtils.S_IRUSR|FileUtils.S_IWUSR
Nick Kralevich70522ad2012-01-06 13:58:01 -08002108 |FileUtils.S_IRGRP|FileUtils.S_IWGRP,
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002109 -1, -1);
2110
Dianne Hackborne17b4452018-01-10 13:15:40 -08002111 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
2112 "package-user-" + userId, SystemClock.uptimeMillis() - startTime);
2113
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002114 // Done, all is good!
2115 return;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002116 } catch(java.io.IOException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002117 Slog.wtf(PackageManagerService.TAG,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002118 "Unable to write package manager user packages state, "
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002119 + " current changes will be lost at reboot", e);
2120 }
2121
2122 // Clean up partially written files
Amith Yamasani483f3b02012-03-13 16:08:00 -07002123 if (userPackagesStateFile.exists()) {
2124 if (!userPackagesStateFile.delete()) {
2125 Log.i(PackageManagerService.TAG, "Failed to clean up mangled file: "
2126 + mStoppedPackagesFilename);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002127 }
2128 }
2129 }
2130
Svetoslavc6d1c342015-02-26 14:44:43 -08002131 void readInstallPermissionsLPr(XmlPullParser parser,
2132 PermissionsState permissionsState) throws IOException, XmlPullParserException {
2133 int outerDepth = parser.getDepth();
2134 int type;
2135 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2136 && (type != XmlPullParser.END_TAG
2137 || parser.getDepth() > outerDepth)) {
2138 if (type == XmlPullParser.END_TAG
2139 || type == XmlPullParser.TEXT) {
2140 continue;
2141 }
2142 String tagName = parser.getName();
2143 if (tagName.equals(TAG_ITEM)) {
2144 String name = parser.getAttributeValue(null, ATTR_NAME);
2145
Todd Kennedy0eb97382017-10-03 16:57:22 -07002146 BasePermission bp = mPermissions.getPermission(name);
Svetoslavc6d1c342015-02-26 14:44:43 -08002147 if (bp == null) {
2148 Slog.w(PackageManagerService.TAG, "Unknown permission: " + name);
2149 XmlUtils.skipCurrentTag(parser);
2150 continue;
2151 }
2152
Svet Ganov8c7f7002015-05-07 10:48:44 -07002153 String grantedStr = parser.getAttributeValue(null, ATTR_GRANTED);
2154 final boolean granted = grantedStr == null
2155 || Boolean.parseBoolean(grantedStr);
2156
2157 String flagsStr = parser.getAttributeValue(null, ATTR_FLAGS);
2158 final int flags = (flagsStr != null)
2159 ? Integer.parseInt(flagsStr, 16) : 0;
2160
2161 if (granted) {
2162 if (permissionsState.grantInstallPermission(bp) ==
2163 PermissionsState.PERMISSION_OPERATION_FAILURE) {
2164 Slog.w(PackageManagerService.TAG, "Permission already added: " + name);
2165 XmlUtils.skipCurrentTag(parser);
2166 } else {
2167 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
Philip P. Moltmann76597692019-03-02 13:18:41 -08002168 PackageManager.MASK_PERMISSION_FLAGS_ALL, flags);
Svet Ganov8c7f7002015-05-07 10:48:44 -07002169 }
2170 } else {
2171 if (permissionsState.revokeInstallPermission(bp) ==
2172 PermissionsState.PERMISSION_OPERATION_FAILURE) {
2173 Slog.w(PackageManagerService.TAG, "Permission already added: " + name);
2174 XmlUtils.skipCurrentTag(parser);
2175 } else {
2176 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
Philip P. Moltmann76597692019-03-02 13:18:41 -08002177 PackageManager.MASK_PERMISSION_FLAGS_ALL, flags);
Svet Ganov8c7f7002015-05-07 10:48:44 -07002178 }
Svetoslavc6d1c342015-02-26 14:44:43 -08002179 }
2180 } else {
2181 Slog.w(PackageManagerService.TAG, "Unknown element under <permissions>: "
2182 + parser.getName());
2183 XmlUtils.skipCurrentTag(parser);
2184 }
2185 }
2186 }
2187
Svet Ganov8c7f7002015-05-07 10:48:44 -07002188 void writePermissionsLPr(XmlSerializer serializer, List<PermissionState> permissionStates)
Svetoslavc6d1c342015-02-26 14:44:43 -08002189 throws IOException {
Svet Ganov8c7f7002015-05-07 10:48:44 -07002190 if (permissionStates.isEmpty()) {
Svetoslavc6d1c342015-02-26 14:44:43 -08002191 return;
2192 }
2193
2194 serializer.startTag(null, TAG_PERMISSIONS);
2195
Svet Ganov8c7f7002015-05-07 10:48:44 -07002196 for (PermissionState permissionState : permissionStates) {
Svetoslavc6d1c342015-02-26 14:44:43 -08002197 serializer.startTag(null, TAG_ITEM);
Svet Ganov8c7f7002015-05-07 10:48:44 -07002198 serializer.attribute(null, ATTR_NAME, permissionState.getName());
2199 serializer.attribute(null, ATTR_GRANTED, String.valueOf(permissionState.isGranted()));
2200 serializer.attribute(null, ATTR_FLAGS, Integer.toHexString(permissionState.getFlags()));
Svetoslavc6d1c342015-02-26 14:44:43 -08002201 serializer.endTag(null, TAG_ITEM);
2202 }
2203
2204 serializer.endTag(null, TAG_PERMISSIONS);
2205 }
2206
Svet Ganov354cd3c2015-12-17 11:35:04 -08002207 void writeChildPackagesLPw(XmlSerializer serializer, List<String> childPackageNames)
2208 throws IOException {
2209 if (childPackageNames == null) {
2210 return;
2211 }
2212 final int childCount = childPackageNames.size();
2213 for (int i = 0; i < childCount; i++) {
2214 String childPackageName = childPackageNames.get(i);
2215 serializer.startTag(null, TAG_CHILD_PACKAGE);
2216 serializer.attribute(null, ATTR_NAME, childPackageName);
2217 serializer.endTag(null, TAG_CHILD_PACKAGE);
2218 }
2219 }
2220
Svet Ganov67882122016-12-11 16:36:34 -08002221 void readUsesStaticLibLPw(XmlPullParser parser, PackageSetting outPs)
2222 throws IOException, XmlPullParserException {
2223 int outerDepth = parser.getDepth();
2224 int type;
2225 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2226 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2227 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2228 continue;
2229 }
2230 String libName = parser.getAttributeValue(null, ATTR_NAME);
2231 String libVersionStr = parser.getAttributeValue(null, ATTR_VERSION);
2232
Dianne Hackborn3accca02013-09-20 09:32:11 -07002233 long libVersion = -1;
Svet Ganov67882122016-12-11 16:36:34 -08002234 try {
Dianne Hackborn3accca02013-09-20 09:32:11 -07002235 libVersion = Long.parseLong(libVersionStr);
Svet Ganov67882122016-12-11 16:36:34 -08002236 } catch (NumberFormatException e) {
2237 // ignore
2238 }
2239
2240 if (libName != null && libVersion >= 0) {
2241 outPs.usesStaticLibraries = ArrayUtils.appendElement(String.class,
2242 outPs.usesStaticLibraries, libName);
Dianne Hackborn3accca02013-09-20 09:32:11 -07002243 outPs.usesStaticLibrariesVersions = ArrayUtils.appendLong(
Svet Ganov67882122016-12-11 16:36:34 -08002244 outPs.usesStaticLibrariesVersions, libVersion);
2245 }
2246
2247 XmlUtils.skipCurrentTag(parser);
2248 }
2249 }
2250
2251 void writeUsesStaticLibLPw(XmlSerializer serializer, String[] usesStaticLibraries,
Dianne Hackborn3accca02013-09-20 09:32:11 -07002252 long[] usesStaticLibraryVersions) throws IOException {
Svet Ganov67882122016-12-11 16:36:34 -08002253 if (ArrayUtils.isEmpty(usesStaticLibraries) || ArrayUtils.isEmpty(usesStaticLibraryVersions)
2254 || usesStaticLibraries.length != usesStaticLibraryVersions.length) {
2255 return;
2256 }
2257 final int libCount = usesStaticLibraries.length;
2258 for (int i = 0; i < libCount; i++) {
2259 final String libName = usesStaticLibraries[i];
Dianne Hackborn3accca02013-09-20 09:32:11 -07002260 final long libVersion = usesStaticLibraryVersions[i];
Svet Ganov67882122016-12-11 16:36:34 -08002261 serializer.startTag(null, TAG_USES_STATIC_LIB);
2262 serializer.attribute(null, ATTR_NAME, libName);
Dianne Hackborn3accca02013-09-20 09:32:11 -07002263 serializer.attribute(null, ATTR_VERSION, Long.toString(libVersion));
Svet Ganov67882122016-12-11 16:36:34 -08002264 serializer.endTag(null, TAG_USES_STATIC_LIB);
2265 }
2266 }
2267
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002268 // Note: assumed "stopped" field is already cleared in all packages.
Amith Yamasani483f3b02012-03-13 16:08:00 -07002269 // Legacy reader, used to read in the old file format after an upgrade. Not used after that.
Kenny Root447106f2011-03-23 11:00:15 -07002270 void readStoppedLPw() {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002271 FileInputStream str = null;
2272 if (mBackupStoppedPackagesFilename.exists()) {
2273 try {
2274 str = new FileInputStream(mBackupStoppedPackagesFilename);
2275 mReadMessages.append("Reading from backup stopped packages file\n");
Amith Yamasani483f3b02012-03-13 16:08:00 -07002276 PackageManagerService.reportSettingsProblem(Log.INFO,
2277 "Need to read from backup stopped packages file");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002278 if (mSettingsFilename.exists()) {
2279 // If both the backup and normal file exist, we
2280 // ignore the normal one since it might have been
2281 // corrupted.
2282 Slog.w(PackageManagerService.TAG, "Cleaning up stopped packages file "
2283 + mStoppedPackagesFilename);
2284 mStoppedPackagesFilename.delete();
2285 }
2286 } catch (java.io.IOException e) {
2287 // We'll try for the normal settings file.
2288 }
2289 }
2290
2291 try {
2292 if (str == null) {
2293 if (!mStoppedPackagesFilename.exists()) {
2294 mReadMessages.append("No stopped packages file found\n");
Amith Yamasani483f3b02012-03-13 16:08:00 -07002295 PackageManagerService.reportSettingsProblem(Log.INFO,
2296 "No stopped packages file file; assuming all started");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002297 // At first boot, make sure no packages are stopped.
2298 // We usually want to have third party apps initialize
2299 // in the stopped state, but not at first boot.
2300 for (PackageSetting pkg : mPackages.values()) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002301 pkg.setStopped(false, 0);
2302 pkg.setNotLaunched(false, 0);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002303 }
2304 return;
2305 }
2306 str = new FileInputStream(mStoppedPackagesFilename);
2307 }
Kenny Root447106f2011-03-23 11:00:15 -07002308 final XmlPullParser parser = Xml.newPullParser();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002309 parser.setInput(str, null);
2310
2311 int type;
2312 while ((type=parser.next()) != XmlPullParser.START_TAG
2313 && type != XmlPullParser.END_DOCUMENT) {
2314 ;
2315 }
2316
2317 if (type != XmlPullParser.START_TAG) {
2318 mReadMessages.append("No start tag found in stopped packages file\n");
2319 PackageManagerService.reportSettingsProblem(Log.WARN,
2320 "No start tag found in package manager stopped packages");
2321 return;
2322 }
2323
2324 int outerDepth = parser.getDepth();
2325 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2326 && (type != XmlPullParser.END_TAG
2327 || parser.getDepth() > outerDepth)) {
2328 if (type == XmlPullParser.END_TAG
2329 || type == XmlPullParser.TEXT) {
2330 continue;
2331 }
2332
2333 String tagName = parser.getName();
Amith Yamasani483f3b02012-03-13 16:08:00 -07002334 if (tagName.equals(TAG_PACKAGE)) {
2335 String name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002336 PackageSetting ps = mPackages.get(name);
2337 if (ps != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002338 ps.setStopped(true, 0);
2339 if ("1".equals(parser.getAttributeValue(null, ATTR_NOT_LAUNCHED))) {
2340 ps.setNotLaunched(true, 0);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002341 }
2342 } else {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002343 Slog.w(PackageManagerService.TAG,
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07002344 "No package known for stopped package " + name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002345 }
2346 XmlUtils.skipCurrentTag(parser);
2347 } else {
2348 Slog.w(PackageManagerService.TAG, "Unknown element under <stopped-packages>: "
2349 + parser.getName());
2350 XmlUtils.skipCurrentTag(parser);
2351 }
2352 }
2353
2354 str.close();
2355
Amith Yamasani483f3b02012-03-13 16:08:00 -07002356 } catch (XmlPullParserException e) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002357 mReadMessages.append("Error reading: " + e.toString());
Amith Yamasani483f3b02012-03-13 16:08:00 -07002358 PackageManagerService.reportSettingsProblem(Log.ERROR,
2359 "Error reading stopped packages: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07002360 Slog.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages",
2361 e);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002362
Amith Yamasani483f3b02012-03-13 16:08:00 -07002363 } catch (java.io.IOException e) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002364 mReadMessages.append("Error reading: " + e.toString());
2365 PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07002366 Slog.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages",
2367 e);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002368
2369 }
2370 }
2371
Kenny Root447106f2011-03-23 11:00:15 -07002372 void writeLPr() {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002373 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
2374
Dianne Hackborne17b4452018-01-10 13:15:40 -08002375 final long startTime = SystemClock.uptimeMillis();
2376
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002377 // Keep the old settings around until we know the new ones have
2378 // been successfully written.
2379 if (mSettingsFilename.exists()) {
2380 // Presence of backup settings file indicates that we failed
2381 // to persist settings earlier. So preserve the older
2382 // backup for future reference since the current settings
2383 // might have been corrupted.
2384 if (!mBackupSettingsFilename.exists()) {
2385 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002386 Slog.wtf(PackageManagerService.TAG,
2387 "Unable to backup package manager settings, "
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002388 + " current changes will be lost at reboot");
2389 return;
2390 }
2391 } else {
2392 mSettingsFilename.delete();
2393 Slog.w(PackageManagerService.TAG, "Preserving older settings backup");
2394 }
2395 }
2396
2397 mPastSignatures.clear();
2398
2399 try {
2400 FileOutputStream fstr = new FileOutputStream(mSettingsFilename);
2401 BufferedOutputStream str = new BufferedOutputStream(fstr);
2402
2403 //XmlSerializer serializer = XmlUtils.serializerInstance();
2404 XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002405 serializer.setOutput(str, StandardCharsets.UTF_8.name());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002406 serializer.startDocument(null, true);
2407 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2408
2409 serializer.startTag(null, "packages");
2410
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07002411 for (int i = 0; i < mVersion.size(); i++) {
2412 final String volumeUuid = mVersion.keyAt(i);
2413 final VersionInfo ver = mVersion.valueAt(i);
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07002414
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07002415 serializer.startTag(null, TAG_VERSION);
2416 XmlUtils.writeStringAttribute(serializer, ATTR_VOLUME_UUID, volumeUuid);
2417 XmlUtils.writeIntAttribute(serializer, ATTR_SDK_VERSION, ver.sdkVersion);
2418 XmlUtils.writeIntAttribute(serializer, ATTR_DATABASE_VERSION, ver.databaseVersion);
2419 XmlUtils.writeStringAttribute(serializer, ATTR_FINGERPRINT, ver.fingerprint);
2420 serializer.endTag(null, TAG_VERSION);
2421 }
Kenny Rootc1c0d3c2014-04-24 13:36:40 -07002422
Kenny Root0aaa0d92011-09-12 16:42:55 -07002423 if (mVerifierDeviceIdentity != null) {
2424 serializer.startTag(null, "verifier");
2425 serializer.attribute(null, "device", mVerifierDeviceIdentity.toString());
2426 serializer.endTag(null, "verifier");
2427 }
2428
Jeff Sharkeyf5385772012-05-11 14:04:41 -07002429 if (mReadExternalStorageEnforced != null) {
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07002430 serializer.startTag(null, TAG_READ_EXTERNAL_STORAGE);
2431 serializer.attribute(
Jeff Sharkey5d32e772012-04-12 15:59:23 -07002432 null, ATTR_ENFORCEMENT, mReadExternalStorageEnforced ? "1" : "0");
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07002433 serializer.endTag(null, TAG_READ_EXTERNAL_STORAGE);
2434 }
2435
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002436 serializer.startTag(null, "permission-trees");
Todd Kennedyc8423932017-10-05 08:58:36 -07002437 mPermissions.writePermissionTrees(serializer);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002438 serializer.endTag(null, "permission-trees");
2439
2440 serializer.startTag(null, "permissions");
Todd Kennedy0eb97382017-10-03 16:57:22 -07002441 mPermissions.writePermissions(serializer);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002442 serializer.endTag(null, "permissions");
2443
Kenny Root447106f2011-03-23 11:00:15 -07002444 for (final PackageSetting pkg : mPackages.values()) {
2445 writePackageLPr(serializer, pkg);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002446 }
2447
Kenny Root447106f2011-03-23 11:00:15 -07002448 for (final PackageSetting pkg : mDisabledSysPackages.values()) {
2449 writeDisabledSysPackageLPr(serializer, pkg);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002450 }
2451
Kenny Root447106f2011-03-23 11:00:15 -07002452 for (final SharedUserSetting usr : mSharedUsers.values()) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002453 serializer.startTag(null, "shared-user");
Amith Yamasani483f3b02012-03-13 16:08:00 -07002454 serializer.attribute(null, ATTR_NAME, usr.name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002455 serializer.attribute(null, "userId",
2456 Integer.toString(usr.userId));
2457 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
Svet Ganov8c7f7002015-05-07 10:48:44 -07002458 writePermissionsLPr(serializer, usr.getPermissionsState()
2459 .getInstallPermissionStates());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002460 serializer.endTag(null, "shared-user");
2461 }
2462
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002463 if (mRenamedPackages.size() > 0) {
Andy McFadden2f362292012-01-20 14:43:38 -08002464 for (Map.Entry<String, String> e : mRenamedPackages.entrySet()) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002465 serializer.startTag(null, "renamed-package");
2466 serializer.attribute(null, "new", e.getKey());
2467 serializer.attribute(null, "old", e.getValue());
2468 serializer.endTag(null, "renamed-package");
2469 }
2470 }
Svetoslavc6d1c342015-02-26 14:44:43 -08002471
Christopher Tate6038d152015-06-17 13:07:46 -07002472 final int numIVIs = mRestoredIntentFilterVerifications.size();
2473 if (numIVIs > 0) {
2474 if (DEBUG_DOMAIN_VERIFICATION) {
2475 Slog.i(TAG, "Writing restored-ivi entries to packages.xml");
2476 }
2477 serializer.startTag(null, "restored-ivi");
2478 for (int i = 0; i < numIVIs; i++) {
2479 IntentFilterVerificationInfo ivi = mRestoredIntentFilterVerifications.valueAt(i);
2480 writeDomainVerificationsLPr(serializer, ivi);
2481 }
2482 serializer.endTag(null, "restored-ivi");
2483 } else {
2484 if (DEBUG_DOMAIN_VERIFICATION) {
2485 Slog.i(TAG, " no restored IVI entries to write");
2486 }
2487 }
2488
dcashman55b10782014-04-09 14:20:38 -07002489 mKeySetManagerService.writeKeySetManagerServiceLPr(serializer);
Geremy Condraf1bcca82013-01-07 22:35:24 -08002490
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002491 serializer.endTag(null, "packages");
2492
2493 serializer.endDocument();
2494
2495 str.flush();
2496 FileUtils.sync(fstr);
2497 str.close();
2498
2499 // New settings successfully written, old ones are no longer
2500 // needed.
2501 mBackupSettingsFilename.delete();
2502 FileUtils.setPermissions(mSettingsFilename.toString(),
2503 FileUtils.S_IRUSR|FileUtils.S_IWUSR
Nick Kralevich70522ad2012-01-06 13:58:01 -08002504 |FileUtils.S_IRGRP|FileUtils.S_IWGRP,
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002505 -1, -1);
2506
Jeff Sharkey2271ba32016-02-01 17:57:08 -07002507 writeKernelMappingLPr();
Jeff Sharkey91edde22015-05-20 12:04:42 -07002508 writePackageListLPr();
Amith Yamasani483f3b02012-03-13 16:08:00 -07002509 writeAllUsersPackageRestrictionsLPr();
Svetoslavc6d1c342015-02-26 14:44:43 -08002510 writeAllRuntimePermissionsLPr();
Dianne Hackborne17b4452018-01-10 13:15:40 -08002511 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
2512 "package", SystemClock.uptimeMillis() - startTime);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002513 return;
2514
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002515 } catch(java.io.IOException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002516 Slog.wtf(PackageManagerService.TAG, "Unable to write package manager settings, "
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002517 + "current changes will be lost at reboot", e);
2518 }
2519 // Clean up partially written files
2520 if (mSettingsFilename.exists()) {
2521 if (!mSettingsFilename.delete()) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002522 Slog.wtf(PackageManagerService.TAG, "Failed to clean up mangled file: "
Amith Yamasani483f3b02012-03-13 16:08:00 -07002523 + mSettingsFilename);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002524 }
2525 }
2526 //Debug.stopMethodTracing();
2527 }
2528
Amith Yamasani23ab7f52017-01-22 17:43:24 -08002529 private void writeKernelRemoveUserLPr(int userId) {
2530 if (mKernelMappingFilename == null) return;
2531
2532 File removeUserIdFile = new File(mKernelMappingFilename, "remove_userid");
2533 if (DEBUG_KERNEL) Slog.d(TAG, "Writing " + userId + " to " + removeUserIdFile
2534 .getAbsolutePath());
2535 writeIntToFile(removeUserIdFile, userId);
2536 }
2537
Jeff Sharkey2271ba32016-02-01 17:57:08 -07002538 void writeKernelMappingLPr() {
2539 if (mKernelMappingFilename == null) return;
2540
2541 final String[] known = mKernelMappingFilename.list();
2542 final ArraySet<String> knownSet = new ArraySet<>(known.length);
2543 for (String name : known) {
2544 knownSet.add(name);
2545 }
2546
2547 for (final PackageSetting ps : mPackages.values()) {
2548 // Package is actively claimed
2549 knownSet.remove(ps.name);
2550 writeKernelMappingLPr(ps);
2551 }
2552
Sudheer Shanka12783cb2018-10-18 08:53:02 -07002553 for (final SharedUserSetting sus : mSharedUsers.values()) {
Sudheer Shankad68bd602018-11-13 17:43:39 -08002554 knownSet.remove(sus.getStorageSandboxName());
Sudheer Shanka12783cb2018-10-18 08:53:02 -07002555 }
2556
Jeff Sharkey2271ba32016-02-01 17:57:08 -07002557 // Remove any unclaimed mappings
2558 for (int i = 0; i < knownSet.size(); i++) {
2559 final String name = knownSet.valueAt(i);
2560 if (DEBUG_KERNEL) Slog.d(TAG, "Dropping mapping " + name);
2561
2562 mKernelMapping.remove(name);
Jeff Sharkey800efcc2016-02-25 17:08:11 -07002563 new File(mKernelMappingFilename, name).delete();
Jeff Sharkey2271ba32016-02-01 17:57:08 -07002564 }
2565 }
2566
Sudheer Shanka12783cb2018-10-18 08:53:02 -07002567 void writeKernelMappingLPr(SharedUserSetting sus) {
2568 if (mKernelMappingFilename == null || sus == null || sus.name == null) return;
2569
Sudheer Shankad68bd602018-11-13 17:43:39 -08002570 writeKernelMappingLPr(sus.getStorageSandboxName(),
2571 sus.userId, sus.getNotInstalledUserIds());
Sudheer Shanka12783cb2018-10-18 08:53:02 -07002572 }
2573
Jeff Sharkey2271ba32016-02-01 17:57:08 -07002574 void writeKernelMappingLPr(PackageSetting ps) {
Amith Yamasani23ab7f52017-01-22 17:43:24 -08002575 if (mKernelMappingFilename == null || ps == null || ps.name == null) return;
Jeff Sharkey2271ba32016-02-01 17:57:08 -07002576
Sudheer Shanka12783cb2018-10-18 08:53:02 -07002577 writeKernelMappingLPr(ps.name, ps.appId, ps.getNotInstalledUserIds());
2578 if (ps.sharedUser != null) {
2579 writeKernelMappingLPr(ps.sharedUser);
2580 }
2581 }
2582
2583 void writeKernelMappingLPr(String name, int appId, int[] excludedUserIds) {
2584 KernelPackageState cur = mKernelMapping.get(name);
Amith Yamasani23ab7f52017-01-22 17:43:24 -08002585 final boolean firstTime = cur == null;
Amith Yamasani23ab7f52017-01-22 17:43:24 -08002586 final boolean userIdsChanged = firstTime
2587 || !Arrays.equals(excludedUserIds, cur.excludedUserIds);
2588
2589 // Package directory
Sudheer Shanka12783cb2018-10-18 08:53:02 -07002590 final File dir = new File(mKernelMappingFilename, name);
Amith Yamasani23ab7f52017-01-22 17:43:24 -08002591
2592 if (firstTime) {
2593 dir.mkdir();
2594 // Create a new mapping state
2595 cur = new KernelPackageState();
Sudheer Shanka12783cb2018-10-18 08:53:02 -07002596 mKernelMapping.put(name, cur);
Jeff Sharkey2271ba32016-02-01 17:57:08 -07002597 }
2598
Amith Yamasani23ab7f52017-01-22 17:43:24 -08002599 // If mapping is incorrect or non-existent, write the appid file
Sudheer Shanka12783cb2018-10-18 08:53:02 -07002600 if (cur.appId != appId) {
Amith Yamasani23ab7f52017-01-22 17:43:24 -08002601 final File appIdFile = new File(dir, "appid");
Sudheer Shanka12783cb2018-10-18 08:53:02 -07002602 writeIntToFile(appIdFile, appId);
2603 if (DEBUG_KERNEL) Slog.d(TAG, "Mapping " + name + " to " + appId);
Amith Yamasani23ab7f52017-01-22 17:43:24 -08002604 }
Jeff Sharkey2271ba32016-02-01 17:57:08 -07002605
Amith Yamasani23ab7f52017-01-22 17:43:24 -08002606 if (userIdsChanged) {
2607 // Build the exclusion list -- the ids to add to the exclusion list
2608 for (int i = 0; i < excludedUserIds.length; i++) {
2609 if (cur.excludedUserIds == null || !ArrayUtils.contains(cur.excludedUserIds,
2610 excludedUserIds[i])) {
2611 writeIntToFile(new File(dir, "excluded_userids"), excludedUserIds[i]);
2612 if (DEBUG_KERNEL) Slog.d(TAG, "Writing " + excludedUserIds[i] + " to "
Sudheer Shanka12783cb2018-10-18 08:53:02 -07002613 + name + "/excluded_userids");
Amith Yamasani23ab7f52017-01-22 17:43:24 -08002614 }
2615 }
2616 // Build the inclusion list -- the ids to remove from the exclusion list
2617 if (cur.excludedUserIds != null) {
2618 for (int i = 0; i < cur.excludedUserIds.length; i++) {
2619 if (!ArrayUtils.contains(excludedUserIds, cur.excludedUserIds[i])) {
2620 writeIntToFile(new File(dir, "clear_userid"),
2621 cur.excludedUserIds[i]);
2622 if (DEBUG_KERNEL) Slog.d(TAG, "Writing " + cur.excludedUserIds[i] + " to "
Sudheer Shanka12783cb2018-10-18 08:53:02 -07002623 + name + "/clear_userid");
Jeff Sharkey2271ba32016-02-01 17:57:08 -07002624
Amith Yamasani23ab7f52017-01-22 17:43:24 -08002625 }
2626 }
2627 }
2628 cur.excludedUserIds = excludedUserIds;
2629 }
2630 }
2631
2632 private void writeIntToFile(File file, int value) {
Jeff Sharkey2271ba32016-02-01 17:57:08 -07002633 try {
Narayan Kamath6d051fc2016-11-22 20:20:00 +00002634 FileUtils.bytesToFile(file.getAbsolutePath(),
Amith Yamasani23ab7f52017-01-22 17:43:24 -08002635 Integer.toString(value).getBytes(StandardCharsets.US_ASCII));
Jeff Sharkey2271ba32016-02-01 17:57:08 -07002636 } catch (IOException ignored) {
Amith Yamasani23ab7f52017-01-22 17:43:24 -08002637 Slog.w(TAG, "Couldn't write " + value + " to " + file.getAbsolutePath());
Jeff Sharkey2271ba32016-02-01 17:57:08 -07002638 }
2639 }
2640
Jeff Sharkey91edde22015-05-20 12:04:42 -07002641 void writePackageListLPr() {
2642 writePackageListLPr(-1);
2643 }
2644
2645 void writePackageListLPr(int creatingUserId) {
2646 // Only derive GIDs for active users (not dying)
2647 final List<UserInfo> users = UserManagerService.getInstance().getUsers(true);
2648 int[] userIds = new int[users.size()];
2649 for (int i = 0; i < userIds.length; i++) {
2650 userIds[i] = users.get(i).id;
2651 }
2652 if (creatingUserId != -1) {
2653 userIds = ArrayUtils.appendInt(userIds, creatingUserId);
2654 }
2655
2656 // Write package list file now, use a JournaledFile.
2657 File tempFile = new File(mPackageListFilename.getAbsolutePath() + ".tmp");
2658 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
2659
2660 final File writeTarget = journal.chooseForWrite();
Fyodor Kupolovb69056b2015-12-18 15:20:00 -08002661 FileOutputStream fstr;
2662 BufferedWriter writer = null;
Jeff Sharkey91edde22015-05-20 12:04:42 -07002663 try {
2664 fstr = new FileOutputStream(writeTarget);
Fyodor Kupolovb69056b2015-12-18 15:20:00 -08002665 writer = new BufferedWriter(new OutputStreamWriter(fstr, Charset.defaultCharset()));
Jeff Sharkey91edde22015-05-20 12:04:42 -07002666 FileUtils.setPermissions(fstr.getFD(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
2667
2668 StringBuilder sb = new StringBuilder();
2669 for (final PackageSetting pkg : mPackages.values()) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002670 if (pkg.pkg == null || pkg.pkg.applicationInfo == null
2671 || pkg.pkg.applicationInfo.dataDir == null) {
Jeff Sharkey2271ba32016-02-01 17:57:08 -07002672 if (!"android".equals(pkg.name)) {
2673 Slog.w(TAG, "Skipping " + pkg + " due to missing metadata");
2674 }
Jeff Sharkey91edde22015-05-20 12:04:42 -07002675 continue;
2676 }
2677
2678 final ApplicationInfo ai = pkg.pkg.applicationInfo;
Jeff Sharkeye84bdd32016-02-08 12:16:00 -07002679 final String dataPath = ai.dataDir;
Jeff Sharkey91edde22015-05-20 12:04:42 -07002680 final boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
2681 final int[] gids = pkg.getPermissionsState().computeGids(userIds);
2682
2683 // Avoid any application that has a space in its path.
Fyodor Kupolovb69056b2015-12-18 15:20:00 -08002684 if (dataPath.indexOf(' ') >= 0)
Jeff Sharkey91edde22015-05-20 12:04:42 -07002685 continue;
2686
2687 // we store on each line the following information for now:
2688 //
2689 // pkgName - package name
2690 // userId - application-specific user id
2691 // debugFlag - 0 or 1 if the package is debuggable.
2692 // dataPath - path to package's data path
2693 // seinfo - seinfo label for the app (assigned at install time)
2694 // gids - supplementary gids this app launches with
Yabin Cui1ced4ce2019-01-10 23:23:00 +00002695 // profileableFromShellFlag - 0 or 1 if the package is profileable from shell.
Jeff Sharkey91edde22015-05-20 12:04:42 -07002696 //
2697 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
2698 //
2699 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
2700 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
Yabin Cui1ced4ce2019-01-10 23:23:00 +00002701 // system/core/libpackagelistparser
Jeff Sharkey91edde22015-05-20 12:04:42 -07002702 //
2703 sb.setLength(0);
2704 sb.append(ai.packageName);
2705 sb.append(" ");
Fyodor Kupolovb69056b2015-12-18 15:20:00 -08002706 sb.append(ai.uid);
Jeff Sharkey91edde22015-05-20 12:04:42 -07002707 sb.append(isDebug ? " 1 " : " 0 ");
2708 sb.append(dataPath);
2709 sb.append(" ");
Todd Kennedybe0b8892017-02-15 14:13:52 -08002710 sb.append(ai.seInfo);
Jeff Sharkey91edde22015-05-20 12:04:42 -07002711 sb.append(" ");
2712 if (gids != null && gids.length > 0) {
2713 sb.append(gids[0]);
2714 for (int i = 1; i < gids.length; i++) {
2715 sb.append(",");
2716 sb.append(gids[i]);
2717 }
2718 } else {
2719 sb.append("none");
2720 }
Yabin Cui1ced4ce2019-01-10 23:23:00 +00002721 sb.append(" ");
2722 sb.append(ai.isProfileableByShell() ? "1" : "0");
Jeff Sharkey91edde22015-05-20 12:04:42 -07002723 sb.append("\n");
Fyodor Kupolovb69056b2015-12-18 15:20:00 -08002724 writer.append(sb);
Jeff Sharkey91edde22015-05-20 12:04:42 -07002725 }
Fyodor Kupolovb69056b2015-12-18 15:20:00 -08002726 writer.flush();
Jeff Sharkey91edde22015-05-20 12:04:42 -07002727 FileUtils.sync(fstr);
Fyodor Kupolovb69056b2015-12-18 15:20:00 -08002728 writer.close();
Jeff Sharkey91edde22015-05-20 12:04:42 -07002729 journal.commit();
2730 } catch (Exception e) {
2731 Slog.wtf(TAG, "Failed to write packages.list", e);
Fyodor Kupolovb69056b2015-12-18 15:20:00 -08002732 IoUtils.closeQuietly(writer);
Jeff Sharkey91edde22015-05-20 12:04:42 -07002733 journal.rollback();
2734 }
2735 }
2736
Kenny Root447106f2011-03-23 11:00:15 -07002737 void writeDisabledSysPackageLPr(XmlSerializer serializer, final PackageSetting pkg)
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002738 throws java.io.IOException {
2739 serializer.startTag(null, "updated-package");
Amith Yamasani483f3b02012-03-13 16:08:00 -07002740 serializer.attribute(null, ATTR_NAME, pkg.name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002741 if (pkg.realName != null) {
2742 serializer.attribute(null, "realName", pkg.realName);
2743 }
2744 serializer.attribute(null, "codePath", pkg.codePathString);
2745 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
2746 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
2747 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
2748 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
2749 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
2750 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
2751 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002752 if (pkg.legacyNativeLibraryPathString != null) {
2753 serializer.attribute(null, "nativeLibraryPath", pkg.legacyNativeLibraryPathString);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002754 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002755 if (pkg.primaryCpuAbiString != null) {
2756 serializer.attribute(null, "primaryCpuAbi", pkg.primaryCpuAbiString);
Narayan Kamath9e289d72014-04-10 09:26:59 +00002757 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002758 if (pkg.secondaryCpuAbiString != null) {
2759 serializer.attribute(null, "secondaryCpuAbi", pkg.secondaryCpuAbiString);
2760 }
Narayan Kamath4903f642014-08-11 13:33:45 +01002761 if (pkg.cpuAbiOverrideString != null) {
2762 serializer.attribute(null, "cpuAbiOverride", pkg.cpuAbiOverrideString);
2763 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002764
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002765 if (pkg.sharedUser == null) {
Amith Yamasani13593602012-03-22 16:16:17 -07002766 serializer.attribute(null, "userId", Integer.toString(pkg.appId));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002767 } else {
Amith Yamasani13593602012-03-22 16:16:17 -07002768 serializer.attribute(null, "sharedUserId", Integer.toString(pkg.appId));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002769 }
Svetoslavc6d1c342015-02-26 14:44:43 -08002770
Svet Ganov354cd3c2015-12-17 11:35:04 -08002771 if (pkg.parentPackageName != null) {
2772 serializer.attribute(null, "parentPackageName", pkg.parentPackageName);
2773 }
2774
2775 writeChildPackagesLPw(serializer, pkg.childPackageNames);
2776
Svet Ganov67882122016-12-11 16:36:34 -08002777 writeUsesStaticLibLPw(serializer, pkg.usesStaticLibraries, pkg.usesStaticLibrariesVersions);
2778
Svetoslavc6d1c342015-02-26 14:44:43 -08002779 // If this is a shared user, the permissions will be written there.
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002780 if (pkg.sharedUser == null) {
Svet Ganov8c7f7002015-05-07 10:48:44 -07002781 writePermissionsLPr(serializer, pkg.getPermissionsState()
2782 .getInstallPermissionStates());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002783 }
Svetoslavc6d1c342015-02-26 14:44:43 -08002784
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002785 serializer.endTag(null, "updated-package");
2786 }
2787
Kenny Root447106f2011-03-23 11:00:15 -07002788 void writePackageLPr(XmlSerializer serializer, final PackageSetting pkg)
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002789 throws java.io.IOException {
2790 serializer.startTag(null, "package");
Amith Yamasani483f3b02012-03-13 16:08:00 -07002791 serializer.attribute(null, ATTR_NAME, pkg.name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002792 if (pkg.realName != null) {
2793 serializer.attribute(null, "realName", pkg.realName);
2794 }
2795 serializer.attribute(null, "codePath", pkg.codePathString);
2796 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
2797 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
2798 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002799
2800 if (pkg.legacyNativeLibraryPathString != null) {
2801 serializer.attribute(null, "nativeLibraryPath", pkg.legacyNativeLibraryPathString);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002802 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002803 if (pkg.primaryCpuAbiString != null) {
2804 serializer.attribute(null, "primaryCpuAbi", pkg.primaryCpuAbiString);
Narayan Kamath9e289d72014-04-10 09:26:59 +00002805 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002806 if (pkg.secondaryCpuAbiString != null) {
2807 serializer.attribute(null, "secondaryCpuAbi", pkg.secondaryCpuAbiString);
2808 }
Narayan Kamath4903f642014-08-11 13:33:45 +01002809 if (pkg.cpuAbiOverrideString != null) {
2810 serializer.attribute(null, "cpuAbiOverride", pkg.cpuAbiOverrideString);
2811 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002812
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002813 serializer.attribute(null, "publicFlags", Integer.toString(pkg.pkgFlags));
2814 serializer.attribute(null, "privateFlags", Integer.toString(pkg.pkgPrivateFlags));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002815 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
2816 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
2817 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
2818 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
2819 if (pkg.sharedUser == null) {
Amith Yamasani13593602012-03-22 16:16:17 -07002820 serializer.attribute(null, "userId", Integer.toString(pkg.appId));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002821 } else {
Amith Yamasani13593602012-03-22 16:16:17 -07002822 serializer.attribute(null, "sharedUserId", Integer.toString(pkg.appId));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002823 }
2824 if (pkg.uidError) {
2825 serializer.attribute(null, "uidError", "true");
2826 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002827 if (pkg.installerPackageName != null) {
2828 serializer.attribute(null, "installer", pkg.installerPackageName);
2829 }
Sudheer Shanka8c57aea2016-04-20 16:47:50 -07002830 if (pkg.isOrphaned) {
2831 serializer.attribute(null, "isOrphaned", "true");
2832 }
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07002833 if (pkg.volumeUuid != null) {
2834 serializer.attribute(null, "volumeUuid", pkg.volumeUuid);
2835 }
Jeff Sharkey9bc89af2017-01-11 11:25:50 -07002836 if (pkg.categoryHint != ApplicationInfo.CATEGORY_UNDEFINED) {
2837 serializer.attribute(null, "categoryHint",
2838 Integer.toString(pkg.categoryHint));
2839 }
Svet Ganov354cd3c2015-12-17 11:35:04 -08002840 if (pkg.parentPackageName != null) {
2841 serializer.attribute(null, "parentPackageName", pkg.parentPackageName);
2842 }
Todd Kennedyab532892017-03-08 14:19:49 -08002843 if (pkg.updateAvailable) {
2844 serializer.attribute(null, "updateAvailable", "true");
2845 }
Svet Ganov354cd3c2015-12-17 11:35:04 -08002846
2847 writeChildPackagesLPw(serializer, pkg.childPackageNames);
2848
Svet Ganov67882122016-12-11 16:36:34 -08002849 writeUsesStaticLibLPw(serializer, pkg.usesStaticLibraries, pkg.usesStaticLibrariesVersions);
2850
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002851 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
Svet Ganov8c7f7002015-05-07 10:48:44 -07002852
2853 writePermissionsLPr(serializer, pkg.getPermissionsState()
2854 .getInstallPermissionStates());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002855
dcashman8c04fac2015-03-23 11:39:42 -07002856 writeSigningKeySetLPr(serializer, pkg.keySetData);
dcashman55b10782014-04-09 14:20:38 -07002857 writeUpgradeKeySetsLPr(serializer, pkg.keySetData);
Geremy Condraf1bcca82013-01-07 22:35:24 -08002858 writeKeySetAliasesLPr(serializer, pkg.keySetData);
Fabrice Di Meglio62271722015-04-10 17:24:02 -07002859 writeDomainVerificationsLPr(serializer, pkg.verificationInfo);
Geremy Condraf1bcca82013-01-07 22:35:24 -08002860
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002861 serializer.endTag(null, "package");
2862 }
2863
dcashman8c04fac2015-03-23 11:39:42 -07002864 void writeSigningKeySetLPr(XmlSerializer serializer,
Geremy Condraf1bcca82013-01-07 22:35:24 -08002865 PackageKeySetData data) throws IOException {
dcashman8c04fac2015-03-23 11:39:42 -07002866 serializer.startTag(null, "proper-signing-keyset");
2867 serializer.attribute(null, "identifier",
2868 Long.toString(data.getProperSigningKeySet()));
2869 serializer.endTag(null, "proper-signing-keyset");
dcashman55b10782014-04-09 14:20:38 -07002870 }
2871
2872 void writeUpgradeKeySetsLPr(XmlSerializer serializer,
2873 PackageKeySetData data) throws IOException {
2874 if (data.isUsingUpgradeKeySets()) {
2875 for (long id : data.getUpgradeKeySets()) {
2876 serializer.startTag(null, "upgrade-keyset");
2877 serializer.attribute(null, "identifier", Long.toString(id));
2878 serializer.endTag(null, "upgrade-keyset");
2879 }
Geremy Condraf1bcca82013-01-07 22:35:24 -08002880 }
2881 }
2882
2883 void writeKeySetAliasesLPr(XmlSerializer serializer,
2884 PackageKeySetData data) throws IOException {
2885 for (Map.Entry<String, Long> e: data.getAliases().entrySet()) {
2886 serializer.startTag(null, "defined-keyset");
2887 serializer.attribute(null, "alias", e.getKey());
2888 serializer.attribute(null, "identifier", Long.toString(e.getValue()));
2889 serializer.endTag(null, "defined-keyset");
2890 }
2891 }
2892
Todd Kennedy91a39d12017-09-27 12:37:04 -07002893 void writePermissionLPr(XmlSerializer serializer, BasePermission bp) throws IOException {
2894 bp.writeLPr(serializer);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002895 }
2896
Xiaohui Chen594f2082015-08-18 11:04:20 -07002897 boolean readLPw(@NonNull List<UserInfo> users) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002898 FileInputStream str = null;
2899 if (mBackupSettingsFilename.exists()) {
2900 try {
2901 str = new FileInputStream(mBackupSettingsFilename);
2902 mReadMessages.append("Reading from backup settings file\n");
2903 PackageManagerService.reportSettingsProblem(Log.INFO,
2904 "Need to read from backup settings file");
2905 if (mSettingsFilename.exists()) {
2906 // If both the backup and settings file exist, we
2907 // ignore the settings since it might have been
2908 // corrupted.
2909 Slog.w(PackageManagerService.TAG, "Cleaning up settings file "
2910 + mSettingsFilename);
2911 mSettingsFilename.delete();
2912 }
2913 } catch (java.io.IOException e) {
2914 // We'll try for the normal settings file.
2915 }
2916 }
2917
Kenny Root447106f2011-03-23 11:00:15 -07002918 mPendingPackages.clear();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002919 mPastSignatures.clear();
dcashman8c04fac2015-03-23 11:39:42 -07002920 mKeySetRefs.clear();
Sudheer Shanka29283372016-04-04 20:56:27 -07002921 mInstallerPackages.clear();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002922
2923 try {
2924 if (str == null) {
2925 if (!mSettingsFilename.exists()) {
2926 mReadMessages.append("No settings file found\n");
2927 PackageManagerService.reportSettingsProblem(Log.INFO,
2928 "No settings file; creating initial state");
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07002929 // It's enough to just touch version details to create them
2930 // with default values
longhaibc62b212016-01-29 14:22:22 +08002931 findOrCreateVersion(StorageManager.UUID_PRIVATE_INTERNAL).forceCurrent();
2932 findOrCreateVersion(StorageManager.UUID_PRIMARY_PHYSICAL).forceCurrent();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002933 return false;
2934 }
2935 str = new FileInputStream(mSettingsFilename);
2936 }
2937 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002938 parser.setInput(str, StandardCharsets.UTF_8.name());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002939
2940 int type;
2941 while ((type = parser.next()) != XmlPullParser.START_TAG
2942 && type != XmlPullParser.END_DOCUMENT) {
2943 ;
2944 }
2945
2946 if (type != XmlPullParser.START_TAG) {
2947 mReadMessages.append("No start tag found in settings file\n");
2948 PackageManagerService.reportSettingsProblem(Log.WARN,
2949 "No start tag found in package manager settings");
Dianne Hackborn8d051722014-10-01 14:59:58 -07002950 Slog.wtf(PackageManagerService.TAG,
Dianne Hackborn58f42a52011-10-10 13:46:34 -07002951 "No start tag found in package manager settings");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002952 return false;
2953 }
2954
2955 int outerDepth = parser.getDepth();
2956 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2957 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2958 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2959 continue;
2960 }
2961
2962 String tagName = parser.getName();
2963 if (tagName.equals("package")) {
Kenny Root447106f2011-03-23 11:00:15 -07002964 readPackageLPw(parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002965 } else if (tagName.equals("permissions")) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07002966 mPermissions.readPermissions(parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002967 } else if (tagName.equals("permission-trees")) {
Todd Kennedyc8423932017-10-05 08:58:36 -07002968 mPermissions.readPermissionTrees(parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002969 } else if (tagName.equals("shared-user")) {
Kenny Root447106f2011-03-23 11:00:15 -07002970 readSharedUserLPw(parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002971 } else if (tagName.equals("preferred-packages")) {
2972 // no longer used.
2973 } else if (tagName.equals("preferred-activities")) {
Dianne Hackborn63092712012-10-07 14:45:35 -07002974 // Upgrading from old single-user implementation;
2975 // these are the preferred activities for user 0.
2976 readPreferredActivitiesLPw(parser, 0);
Sander Alewijnseaf597622014-03-20 18:44:57 +00002977 } else if (tagName.equals(TAG_PERSISTENT_PREFERRED_ACTIVITIES)) {
Sander Alewijnsef475ca32014-02-17 15:13:58 +00002978 // TODO: check whether this is okay! as it is very
2979 // similar to how preferred-activities are treated
2980 readPersistentPreferredActivitiesLPw(parser, 0);
Nicolas Prevot29762c32014-07-29 18:51:32 +01002981 } else if (tagName.equals(TAG_CROSS_PROFILE_INTENT_FILTERS)) {
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00002982 // TODO: check whether this is okay! as it is very
2983 // similar to how preferred-activities are treated
Nicolas Prevot81948992014-05-16 18:25:26 +01002984 readCrossProfileIntentFiltersLPw(parser, 0);
Fabrice Di Meglio62271722015-04-10 17:24:02 -07002985 } else if (tagName.equals(TAG_DEFAULT_BROWSER)) {
2986 readDefaultAppsLPw(parser, 0);
2987 } else if (tagName.equals("updated-package")) {
Kenny Root447106f2011-03-23 11:00:15 -07002988 readDisabledSysPackageLPw(parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002989 } else if (tagName.equals("renamed-package")) {
2990 String nname = parser.getAttributeValue(null, "new");
2991 String oname = parser.getAttributeValue(null, "old");
2992 if (nname != null && oname != null) {
2993 mRenamedPackages.put(nname, oname);
2994 }
Christopher Tate6038d152015-06-17 13:07:46 -07002995 } else if (tagName.equals("restored-ivi")) {
2996 readRestoredIntentFilterVerifications(parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002997 } else if (tagName.equals("last-platform-version")) {
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07002998 // Upgrade from older XML schema
2999 final VersionInfo internal = findOrCreateVersion(
3000 StorageManager.UUID_PRIVATE_INTERNAL);
3001 final VersionInfo external = findOrCreateVersion(
3002 StorageManager.UUID_PRIMARY_PHYSICAL);
Svet Ganovadc1cf42015-06-15 16:36:24 -07003003
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07003004 internal.sdkVersion = XmlUtils.readIntAttribute(parser, "internal", 0);
3005 external.sdkVersion = XmlUtils.readIntAttribute(parser, "external", 0);
3006 internal.fingerprint = external.fingerprint =
3007 XmlUtils.readStringAttribute(parser, "fingerprint");
3008
Kenny Rootc1c0d3c2014-04-24 13:36:40 -07003009 } else if (tagName.equals("database-version")) {
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07003010 // Upgrade from older XML schema
3011 final VersionInfo internal = findOrCreateVersion(
3012 StorageManager.UUID_PRIVATE_INTERNAL);
3013 final VersionInfo external = findOrCreateVersion(
3014 StorageManager.UUID_PRIMARY_PHYSICAL);
3015
3016 internal.databaseVersion = XmlUtils.readIntAttribute(parser, "internal", 0);
3017 external.databaseVersion = XmlUtils.readIntAttribute(parser, "external", 0);
3018
Kenny Root0aaa0d92011-09-12 16:42:55 -07003019 } else if (tagName.equals("verifier")) {
3020 final String deviceIdentity = parser.getAttributeValue(null, "device");
3021 try {
3022 mVerifierDeviceIdentity = VerifierDeviceIdentity.parse(deviceIdentity);
3023 } catch (IllegalArgumentException e) {
3024 Slog.w(PackageManagerService.TAG, "Discard invalid verifier device id: "
3025 + e.getMessage());
3026 }
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07003027 } else if (TAG_READ_EXTERNAL_STORAGE.equals(tagName)) {
3028 final String enforcement = parser.getAttributeValue(null, ATTR_ENFORCEMENT);
Todd Kennedy91a39d12017-09-27 12:37:04 -07003029 mReadExternalStorageEnforced =
3030 "1".equals(enforcement) ? Boolean.TRUE : Boolean.FALSE;
Geremy Condraf1bcca82013-01-07 22:35:24 -08003031 } else if (tagName.equals("keyset-settings")) {
dcashman8c04fac2015-03-23 11:39:42 -07003032 mKeySetManagerService.readKeySetsLPw(parser, mKeySetRefs);
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07003033 } else if (TAG_VERSION.equals(tagName)) {
3034 final String volumeUuid = XmlUtils.readStringAttribute(parser,
3035 ATTR_VOLUME_UUID);
3036 final VersionInfo ver = findOrCreateVersion(volumeUuid);
3037 ver.sdkVersion = XmlUtils.readIntAttribute(parser, ATTR_SDK_VERSION);
khmel80bdce02018-01-02 16:39:05 -08003038 ver.databaseVersion = XmlUtils.readIntAttribute(parser, ATTR_DATABASE_VERSION);
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07003039 ver.fingerprint = XmlUtils.readStringAttribute(parser, ATTR_FINGERPRINT);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003040 } else {
3041 Slog.w(PackageManagerService.TAG, "Unknown element under <packages>: "
3042 + parser.getName());
3043 XmlUtils.skipCurrentTag(parser);
3044 }
3045 }
3046
3047 str.close();
3048
3049 } catch (XmlPullParserException e) {
3050 mReadMessages.append("Error reading: " + e.toString());
3051 PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07003052 Slog.wtf(PackageManagerService.TAG, "Error reading package manager settings", e);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003053
3054 } catch (java.io.IOException e) {
3055 mReadMessages.append("Error reading: " + e.toString());
3056 PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07003057 Slog.wtf(PackageManagerService.TAG, "Error reading package manager settings", e);
Amith Yamasani258848d2012-08-10 17:06:33 -07003058 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003059
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07003060 // If the build is setup to drop runtime permissions
3061 // on update drop the files before loading them.
3062 if (PackageManagerService.CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE) {
3063 final VersionInfo internal = getInternalVersion();
3064 if (!Build.FINGERPRINT.equals(internal.fingerprint)) {
Xiaohui Chen594f2082015-08-18 11:04:20 -07003065 for (UserInfo user : users) {
3066 mRuntimePermissionsPersistence.deleteUserRuntimePermissionsFile(user.id);
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07003067 }
3068 }
3069 }
3070
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003071 final int N = mPendingPackages.size();
dcashman8c04fac2015-03-23 11:39:42 -07003072
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003073 for (int i = 0; i < N; i++) {
Todd Kennedy788c8422016-08-10 10:52:34 -07003074 final PackageSetting p = mPendingPackages.get(i);
3075 final int sharedUserId = p.getSharedUserId();
Patrick Baumann649a8572018-11-20 11:16:58 -08003076 final Object idObj = getSettingLPr(sharedUserId);
Todd Kennedy788c8422016-08-10 10:52:34 -07003077 if (idObj instanceof SharedUserSetting) {
3078 final SharedUserSetting sharedUser = (SharedUserSetting) idObj;
3079 p.sharedUser = sharedUser;
3080 p.appId = sharedUser.userId;
3081 addPackageSettingLPw(p, sharedUser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003082 } else if (idObj != null) {
Todd Kennedy788c8422016-08-10 10:52:34 -07003083 String msg = "Bad package setting: package " + p.name + " has shared uid "
3084 + sharedUserId + " that is not a shared uid\n";
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003085 mReadMessages.append(msg);
3086 PackageManagerService.reportSettingsProblem(Log.ERROR, msg);
3087 } else {
Todd Kennedy788c8422016-08-10 10:52:34 -07003088 String msg = "Bad package setting: package " + p.name + " has shared uid "
3089 + sharedUserId + " that is not defined\n";
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003090 mReadMessages.append(msg);
3091 PackageManagerService.reportSettingsProblem(Log.ERROR, msg);
3092 }
3093 }
3094 mPendingPackages.clear();
3095
Amith Yamasanif031f232012-10-26 15:35:21 -07003096 if (mBackupStoppedPackagesFilename.exists()
3097 || mStoppedPackagesFilename.exists()) {
3098 // Read old file
3099 readStoppedLPw();
3100 mBackupStoppedPackagesFilename.delete();
3101 mStoppedPackagesFilename.delete();
3102 // Migrate to new file format
Xiaohui Chen594f2082015-08-18 11:04:20 -07003103 writePackageRestrictionsLPr(UserHandle.USER_SYSTEM);
Amith Yamasanif031f232012-10-26 15:35:21 -07003104 } else {
Xiaohui Chen594f2082015-08-18 11:04:20 -07003105 for (UserInfo user : users) {
3106 readPackageRestrictionsLPr(user.id);
Amith Yamasanif031f232012-10-26 15:35:21 -07003107 }
3108 }
3109
Xiaohui Chen594f2082015-08-18 11:04:20 -07003110 for (UserInfo user : users) {
3111 mRuntimePermissionsPersistence.readStateForUserSyncLPr(user.id);
Svet Ganovadc1cf42015-06-15 16:36:24 -07003112 }
3113
Kenny Root1d1b4892011-04-08 14:25:24 -07003114 /*
3115 * Make sure all the updated system packages have their shared users
3116 * associated with them.
3117 */
3118 final Iterator<PackageSetting> disabledIt = mDisabledSysPackages.values().iterator();
3119 while (disabledIt.hasNext()) {
3120 final PackageSetting disabledPs = disabledIt.next();
Patrick Baumann649a8572018-11-20 11:16:58 -08003121 final Object id = getSettingLPr(disabledPs.appId);
Kenny Root1d1b4892011-04-08 14:25:24 -07003122 if (id != null && id instanceof SharedUserSetting) {
3123 disabledPs.sharedUser = (SharedUserSetting) id;
3124 }
3125 }
3126
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003127 mReadMessages.append("Read completed successfully: " + mPackages.size() + " packages, "
3128 + mSharedUsers.size() + " shared uids\n");
3129
Jeff Sharkey2271ba32016-02-01 17:57:08 -07003130 writeKernelMappingLPr();
3131
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003132 return true;
3133 }
3134
Todd Kennedycf827032018-07-03 13:17:22 -07003135 void applyDefaultPreferredAppsLPw(int userId) {
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003136 // First pull data from any pre-installed apps.
Todd Kennedycf827032018-07-03 13:17:22 -07003137 final PackageManagerInternal pmInternal =
3138 LocalServices.getService(PackageManagerInternal.class);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003139 for (PackageSetting ps : mPackages.values()) {
3140 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0 && ps.pkg != null
3141 && ps.pkg.preferredActivityFilters != null) {
3142 ArrayList<PackageParser.ActivityIntentInfo> intents
3143 = ps.pkg.preferredActivityFilters;
3144 for (int i=0; i<intents.size(); i++) {
3145 PackageParser.ActivityIntentInfo aii = intents.get(i);
Todd Kennedycf827032018-07-03 13:17:22 -07003146 applyDefaultPreferredActivityLPw(pmInternal, aii, new ComponentName(
3147 ps.name, aii.activity.className), userId);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003148 }
3149 }
3150 }
3151
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07003152 // Read preferred apps from .../etc/preferred-apps directory.
3153 File preferredDir = new File(Environment.getRootDirectory(), "etc/preferred-apps");
3154 if (!preferredDir.exists() || !preferredDir.isDirectory()) {
3155 return;
3156 }
3157 if (!preferredDir.canRead()) {
3158 Slog.w(TAG, "Directory " + preferredDir + " cannot be read");
3159 return;
3160 }
3161
3162 // Iterate over the files in the directory and scan .xml files
3163 for (File f : preferredDir.listFiles()) {
3164 if (!f.getPath().endsWith(".xml")) {
3165 Slog.i(TAG, "Non-xml file " + f + " in " + preferredDir + " directory, ignoring");
3166 continue;
3167 }
3168 if (!f.canRead()) {
3169 Slog.w(TAG, "Preferred apps file " + f + " cannot be read");
3170 continue;
3171 }
3172
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08003173 if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Reading default preferred " + f);
Fyodor Kupolovb35b34c2015-12-17 14:16:51 -08003174 InputStream str = null;
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07003175 try {
Fyodor Kupolovb35b34c2015-12-17 14:16:51 -08003176 str = new BufferedInputStream(new FileInputStream(f));
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07003177 XmlPullParser parser = Xml.newPullParser();
3178 parser.setInput(str, null);
3179
3180 int type;
3181 while ((type = parser.next()) != XmlPullParser.START_TAG
3182 && type != XmlPullParser.END_DOCUMENT) {
3183 ;
3184 }
3185
3186 if (type != XmlPullParser.START_TAG) {
3187 Slog.w(TAG, "Preferred apps file " + f + " does not have start tag");
3188 continue;
3189 }
3190 if (!"preferred-activities".equals(parser.getName())) {
3191 Slog.w(TAG, "Preferred apps file " + f
3192 + " does not start with 'preferred-activities'");
3193 continue;
3194 }
Todd Kennedycf827032018-07-03 13:17:22 -07003195 readDefaultPreferredActivitiesLPw(parser, userId);
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07003196 } catch (XmlPullParserException e) {
3197 Slog.w(TAG, "Error reading apps file " + f, e);
3198 } catch (IOException e) {
3199 Slog.w(TAG, "Error reading apps file " + f, e);
3200 } finally {
3201 if (str != null) {
3202 try {
3203 str.close();
3204 } catch (IOException e) {
3205 }
3206 }
3207 }
3208 }
3209 }
3210
Todd Kennedycf827032018-07-03 13:17:22 -07003211 private void applyDefaultPreferredActivityLPw(
3212 PackageManagerInternal pmInternal, IntentFilter tmpPa, ComponentName cn, int userId) {
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003213 // The initial preferences only specify the target activity
3214 // component and intent-filter, not the set of matches. So we
3215 // now need to query for the matches to build the correct
3216 // preferred activity entry.
3217 if (PackageManagerService.DEBUG_PREFERRED) {
3218 Log.d(TAG, "Processing preferred:");
3219 tmpPa.dump(new LogPrinter(Log.DEBUG, TAG), " ");
3220 }
3221 Intent intent = new Intent();
Jeff Sharkey8a372a02016-03-16 16:25:45 -06003222 int flags = PackageManager.MATCH_DIRECT_BOOT_AWARE
3223 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003224 intent.setAction(tmpPa.getAction(0));
3225 for (int i=0; i<tmpPa.countCategories(); i++) {
3226 String cat = tmpPa.getCategory(i);
3227 if (cat.equals(Intent.CATEGORY_DEFAULT)) {
Jeff Sharkey2a90f6732016-01-06 12:26:11 -07003228 flags |= MATCH_DEFAULT_ONLY;
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003229 } else {
3230 intent.addCategory(cat);
3231 }
3232 }
3233
3234 boolean doNonData = true;
Christopher Tate2298ef22013-11-04 17:02:10 -08003235 boolean hasSchemes = false;
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003236
Todd Kennedycf827032018-07-03 13:17:22 -07003237 final int dataSchemesCount = tmpPa.countDataSchemes();
3238 for (int ischeme = 0; ischeme < dataSchemesCount; ischeme++) {
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003239 boolean doScheme = true;
Todd Kennedycf827032018-07-03 13:17:22 -07003240 final String scheme = tmpPa.getDataScheme(ischeme);
Christopher Tate2298ef22013-11-04 17:02:10 -08003241 if (scheme != null && !scheme.isEmpty()) {
3242 hasSchemes = true;
3243 }
Todd Kennedycf827032018-07-03 13:17:22 -07003244 final int dataSchemeSpecificPartsCount = tmpPa.countDataSchemeSpecificParts();
3245 for (int issp = 0; issp < dataSchemeSpecificPartsCount; issp++) {
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003246 Uri.Builder builder = new Uri.Builder();
3247 builder.scheme(scheme);
3248 PatternMatcher ssp = tmpPa.getDataSchemeSpecificPart(issp);
3249 builder.opaquePart(ssp.getPath());
3250 Intent finalIntent = new Intent(intent);
3251 finalIntent.setData(builder.build());
Todd Kennedycf827032018-07-03 13:17:22 -07003252 applyDefaultPreferredActivityLPw(pmInternal, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003253 scheme, ssp, null, null, userId);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003254 doScheme = false;
3255 }
Todd Kennedycf827032018-07-03 13:17:22 -07003256 final int dataAuthoritiesCount = tmpPa.countDataAuthorities();
3257 for (int iauth = 0; iauth < dataAuthoritiesCount; iauth++) {
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003258 boolean doAuth = true;
Todd Kennedycf827032018-07-03 13:17:22 -07003259 final IntentFilter.AuthorityEntry auth = tmpPa.getDataAuthority(iauth);
3260 final int dataPathsCount = tmpPa.countDataPaths();
3261 for (int ipath = 0; ipath < dataPathsCount; ipath++) {
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003262 Uri.Builder builder = new Uri.Builder();
3263 builder.scheme(scheme);
3264 if (auth.getHost() != null) {
3265 builder.authority(auth.getHost());
3266 }
3267 PatternMatcher path = tmpPa.getDataPath(ipath);
3268 builder.path(path.getPath());
3269 Intent finalIntent = new Intent(intent);
3270 finalIntent.setData(builder.build());
Todd Kennedycf827032018-07-03 13:17:22 -07003271 applyDefaultPreferredActivityLPw(pmInternal, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003272 scheme, null, auth, path, userId);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003273 doAuth = doScheme = false;
3274 }
3275 if (doAuth) {
3276 Uri.Builder builder = new Uri.Builder();
3277 builder.scheme(scheme);
3278 if (auth.getHost() != null) {
3279 builder.authority(auth.getHost());
3280 }
3281 Intent finalIntent = new Intent(intent);
3282 finalIntent.setData(builder.build());
Todd Kennedycf827032018-07-03 13:17:22 -07003283 applyDefaultPreferredActivityLPw(pmInternal, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003284 scheme, null, auth, null, userId);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003285 doScheme = false;
3286 }
3287 }
3288 if (doScheme) {
3289 Uri.Builder builder = new Uri.Builder();
3290 builder.scheme(scheme);
3291 Intent finalIntent = new Intent(intent);
3292 finalIntent.setData(builder.build());
Todd Kennedycf827032018-07-03 13:17:22 -07003293 applyDefaultPreferredActivityLPw(pmInternal, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003294 scheme, null, null, null, userId);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003295 }
3296 doNonData = false;
3297 }
3298
3299 for (int idata=0; idata<tmpPa.countDataTypes(); idata++) {
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003300 String mimeType = tmpPa.getDataType(idata);
Christopher Tate2298ef22013-11-04 17:02:10 -08003301 if (hasSchemes) {
3302 Uri.Builder builder = new Uri.Builder();
3303 for (int ischeme=0; ischeme<tmpPa.countDataSchemes(); ischeme++) {
3304 String scheme = tmpPa.getDataScheme(ischeme);
3305 if (scheme != null && !scheme.isEmpty()) {
3306 Intent finalIntent = new Intent(intent);
3307 builder.scheme(scheme);
3308 finalIntent.setDataAndType(builder.build(), mimeType);
Todd Kennedycf827032018-07-03 13:17:22 -07003309 applyDefaultPreferredActivityLPw(pmInternal, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003310 scheme, null, null, null, userId);
Christopher Tate2298ef22013-11-04 17:02:10 -08003311 }
3312 }
3313 } else {
3314 Intent finalIntent = new Intent(intent);
3315 finalIntent.setType(mimeType);
Todd Kennedycf827032018-07-03 13:17:22 -07003316 applyDefaultPreferredActivityLPw(pmInternal, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003317 null, null, null, null, userId);
Christopher Tate2298ef22013-11-04 17:02:10 -08003318 }
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003319 doNonData = false;
3320 }
3321
3322 if (doNonData) {
Todd Kennedycf827032018-07-03 13:17:22 -07003323 applyDefaultPreferredActivityLPw(pmInternal, intent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003324 null, null, null, null, userId);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003325 }
3326 }
3327
Todd Kennedycf827032018-07-03 13:17:22 -07003328 private void applyDefaultPreferredActivityLPw(PackageManagerInternal pmInternal, Intent intent,
3329 int flags, ComponentName cn, String scheme, PatternMatcher ssp,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003330 IntentFilter.AuthorityEntry auth, PatternMatcher path, int userId) {
Todd Kennedycf827032018-07-03 13:17:22 -07003331 final List<ResolveInfo> ri =
3332 pmInternal.queryIntentActivities(intent, flags, Binder.getCallingUid(), 0);
3333 if (PackageManagerService.DEBUG_PREFERRED) {
3334 Log.d(TAG, "Queried " + intent + " results: " + ri);
3335 }
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07003336 int systemMatch = 0;
3337 int thirdPartyMatch = 0;
Todd Kennedycf827032018-07-03 13:17:22 -07003338 final int numMatches = (ri == null ? 0 : ri.size());
3339 if (numMatches <= 1) {
3340 Slog.w(TAG, "No potential matches found for " + intent
3341 + " while setting preferred " + cn.flattenToShortString());
3342 return;
3343 }
3344 boolean haveAct = false;
3345 ComponentName haveNonSys = null;
3346 ComponentName[] set = new ComponentName[ri.size()];
3347 for (int i = 0; i < numMatches; i++) {
3348 final ActivityInfo ai = ri.get(i).activityInfo;
3349 set[i] = new ComponentName(ai.packageName, ai.name);
3350 if ((ai.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
3351 if (ri.get(i).match >= thirdPartyMatch) {
3352 // Keep track of the best match we find of all third
3353 // party apps, for use later to determine if we actually
3354 // want to set a preferred app for this intent.
3355 if (PackageManagerService.DEBUG_PREFERRED) {
3356 Log.d(TAG, "Result " + ai.packageName + "/" + ai.name + ": non-system!");
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003357 }
Todd Kennedycf827032018-07-03 13:17:22 -07003358 haveNonSys = set[i];
3359 break;
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003360 }
Todd Kennedycf827032018-07-03 13:17:22 -07003361 } else if (cn.getPackageName().equals(ai.packageName)
3362 && cn.getClassName().equals(ai.name)) {
3363 if (PackageManagerService.DEBUG_PREFERRED) {
3364 Log.d(TAG, "Result " + ai.packageName + "/" + ai.name + ": default!");
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003365 }
Todd Kennedycf827032018-07-03 13:17:22 -07003366 haveAct = true;
3367 systemMatch = ri.get(i).match;
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003368 } else {
Todd Kennedycf827032018-07-03 13:17:22 -07003369 if (PackageManagerService.DEBUG_PREFERRED) {
3370 Log.d(TAG, "Result " + ai.packageName + "/" + ai.name + ": skipped");
3371 }
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003372 }
Todd Kennedycf827032018-07-03 13:17:22 -07003373 }
3374 if (haveNonSys != null && thirdPartyMatch < systemMatch) {
3375 // If we have a matching third party app, but its match is not as
3376 // good as the built-in system app, then we don't want to actually
3377 // consider it a match because presumably the built-in app is still
3378 // the thing we want users to see by default.
3379 haveNonSys = null;
3380 }
3381 if (haveAct && haveNonSys == null) {
3382 IntentFilter filter = new IntentFilter();
3383 if (intent.getAction() != null) {
3384 filter.addAction(intent.getAction());
3385 }
3386 if (intent.getCategories() != null) {
3387 for (String cat : intent.getCategories()) {
3388 filter.addCategory(cat);
3389 }
3390 }
3391 if ((flags & MATCH_DEFAULT_ONLY) != 0) {
3392 filter.addCategory(Intent.CATEGORY_DEFAULT);
3393 }
3394 if (scheme != null) {
3395 filter.addDataScheme(scheme);
3396 }
3397 if (ssp != null) {
3398 filter.addDataSchemeSpecificPart(ssp.getPath(), ssp.getType());
3399 }
3400 if (auth != null) {
3401 filter.addDataAuthority(auth);
3402 }
3403 if (path != null) {
3404 filter.addDataPath(path);
3405 }
3406 if (intent.getType() != null) {
3407 try {
3408 filter.addDataType(intent.getType());
3409 } catch (IntentFilter.MalformedMimeTypeException ex) {
3410 Slog.w(TAG, "Malformed mimetype " + intent.getType() + " for " + cn);
3411 }
3412 }
3413 PreferredActivity pa = new PreferredActivity(filter, systemMatch, set, cn, true);
3414 editPreferredActivitiesLPw(userId).addFilter(pa);
3415 } else if (haveNonSys == null) {
3416 StringBuilder sb = new StringBuilder();
3417 sb.append("No component ");
3418 sb.append(cn.flattenToShortString());
3419 sb.append(" found setting preferred ");
3420 sb.append(intent);
3421 sb.append("; possible matches are ");
3422 for (int i = 0; i < set.length; i++) {
3423 if (i > 0) sb.append(", ");
3424 sb.append(set[i].flattenToShortString());
3425 }
3426 Slog.w(TAG, sb.toString());
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003427 } else {
Todd Kennedycf827032018-07-03 13:17:22 -07003428 Slog.i(TAG, "Not setting preferred " + intent + "; found third party match "
3429 + haveNonSys.flattenToShortString());
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003430 }
3431 }
3432
Todd Kennedycf827032018-07-03 13:17:22 -07003433 private void readDefaultPreferredActivitiesLPw(XmlPullParser parser, int userId)
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08003434 throws XmlPullParserException, IOException {
Todd Kennedycf827032018-07-03 13:17:22 -07003435 final PackageManagerInternal pmInternal =
3436 LocalServices.getService(PackageManagerInternal.class);
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08003437 int outerDepth = parser.getDepth();
3438 int type;
3439 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3440 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3441 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3442 continue;
3443 }
3444
3445 String tagName = parser.getName();
3446 if (tagName.equals(TAG_ITEM)) {
3447 PreferredActivity tmpPa = new PreferredActivity(parser);
3448 if (tmpPa.mPref.getParseError() == null) {
Todd Kennedycf827032018-07-03 13:17:22 -07003449 applyDefaultPreferredActivityLPw(
3450 pmInternal, tmpPa, tmpPa.mPref.mComponent, userId);
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08003451 } else {
3452 PackageManagerService.reportSettingsProblem(Log.WARN,
3453 "Error in package manager settings: <preferred-activity> "
3454 + tmpPa.mPref.getParseError() + " at "
3455 + parser.getPositionDescription());
3456 }
3457 } else {
3458 PackageManagerService.reportSettingsProblem(Log.WARN,
3459 "Unknown element under <preferred-activities>: " + parser.getName());
3460 XmlUtils.skipCurrentTag(parser);
3461 }
3462 }
3463 }
3464
Kenny Root447106f2011-03-23 11:00:15 -07003465 private void readDisabledSysPackageLPw(XmlPullParser parser) throws XmlPullParserException,
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003466 IOException {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003467 String name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003468 String realName = parser.getAttributeValue(null, "realName");
3469 String codePathStr = parser.getAttributeValue(null, "codePath");
3470 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Narayan Kamathff110bd2014-07-04 18:30:45 +01003471
3472 String legacyCpuAbiStr = parser.getAttributeValue(null, "requiredCpuAbi");
3473 String legacyNativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
3474
Svet Ganov354cd3c2015-12-17 11:35:04 -08003475 String parentPackageName = parser.getAttributeValue(null, "parentPackageName");
3476
Narayan Kamathff110bd2014-07-04 18:30:45 +01003477 String primaryCpuAbiStr = parser.getAttributeValue(null, "primaryCpuAbi");
3478 String secondaryCpuAbiStr = parser.getAttributeValue(null, "secondaryCpuAbi");
Narayan Kamath4903f642014-08-11 13:33:45 +01003479 String cpuAbiOverrideStr = parser.getAttributeValue(null, "cpuAbiOverride");
Narayan Kamathff110bd2014-07-04 18:30:45 +01003480
3481 if (primaryCpuAbiStr == null && legacyCpuAbiStr != null) {
3482 primaryCpuAbiStr = legacyCpuAbiStr;
3483 }
Narayan Kamath9e289d72014-04-10 09:26:59 +00003484
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003485 if (resourcePathStr == null) {
3486 resourcePathStr = codePathStr;
3487 }
3488 String version = parser.getAttributeValue(null, "version");
Dianne Hackborn3accca02013-09-20 09:32:11 -07003489 long versionCode = 0;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003490 if (version != null) {
3491 try {
Dianne Hackborn3accca02013-09-20 09:32:11 -07003492 versionCode = Long.parseLong(version);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003493 } catch (NumberFormatException e) {
3494 }
3495 }
3496
3497 int pkgFlags = 0;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003498 int pkgPrivateFlags = 0;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003499 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Todd Kennedyddaaf4c2017-11-07 10:01:25 -08003500 if (PackageManagerService.locationIsPrivileged(codePathStr)) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003501 pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
Christopher Tate628946a2013-10-18 18:11:05 -07003502 }
Todd Kennedyddaaf4c2017-11-07 10:01:25 -08003503 PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
Narayan Kamathff110bd2014-07-04 18:30:45 +01003504 new File(resourcePathStr), legacyNativeLibraryPathStr, primaryCpuAbiStr,
Svet Ganov354cd3c2015-12-17 11:35:04 -08003505 secondaryCpuAbiStr, cpuAbiOverrideStr, versionCode, pkgFlags, pkgPrivateFlags,
Svet Ganov67882122016-12-11 16:36:34 -08003506 parentPackageName, null /*childPackageNames*/, 0 /*sharedUserId*/, null, null);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003507 String timeStampStr = parser.getAttributeValue(null, "ft");
3508 if (timeStampStr != null) {
3509 try {
3510 long timeStamp = Long.parseLong(timeStampStr, 16);
3511 ps.setTimeStamp(timeStamp);
3512 } catch (NumberFormatException e) {
3513 }
3514 } else {
3515 timeStampStr = parser.getAttributeValue(null, "ts");
3516 if (timeStampStr != null) {
3517 try {
3518 long timeStamp = Long.parseLong(timeStampStr);
3519 ps.setTimeStamp(timeStamp);
3520 } catch (NumberFormatException e) {
3521 }
3522 }
3523 }
3524 timeStampStr = parser.getAttributeValue(null, "it");
3525 if (timeStampStr != null) {
3526 try {
3527 ps.firstInstallTime = Long.parseLong(timeStampStr, 16);
3528 } catch (NumberFormatException e) {
3529 }
3530 }
3531 timeStampStr = parser.getAttributeValue(null, "ut");
3532 if (timeStampStr != null) {
3533 try {
3534 ps.lastUpdateTime = Long.parseLong(timeStampStr, 16);
3535 } catch (NumberFormatException e) {
3536 }
3537 }
3538 String idStr = parser.getAttributeValue(null, "userId");
Amith Yamasani13593602012-03-22 16:16:17 -07003539 ps.appId = idStr != null ? Integer.parseInt(idStr) : 0;
3540 if (ps.appId <= 0) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003541 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
Amith Yamasani13593602012-03-22 16:16:17 -07003542 ps.appId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003543 }
Svetoslavc6d1c342015-02-26 14:44:43 -08003544
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003545 int outerDepth = parser.getDepth();
3546 int type;
3547 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3548 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3549 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3550 continue;
3551 }
3552
Svetoslavc6d1c342015-02-26 14:44:43 -08003553 if (parser.getName().equals(TAG_PERMISSIONS)) {
3554 readInstallPermissionsLPr(parser, ps.getPermissionsState());
Svet Ganov354cd3c2015-12-17 11:35:04 -08003555 } else if (parser.getName().equals(TAG_CHILD_PACKAGE)) {
3556 String childPackageName = parser.getAttributeValue(null, ATTR_NAME);
3557 if (ps.childPackageNames == null) {
3558 ps.childPackageNames = new ArrayList<>();
3559 }
3560 ps.childPackageNames.add(childPackageName);
Svet Ganov67882122016-12-11 16:36:34 -08003561 } else if (parser.getName().equals(TAG_USES_STATIC_LIB)) {
3562 readUsesStaticLibLPw(parser, ps);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003563 } else {
3564 PackageManagerService.reportSettingsProblem(Log.WARN,
3565 "Unknown element under <updated-package>: " + parser.getName());
3566 XmlUtils.skipCurrentTag(parser);
3567 }
3568 }
Christopher Tate628946a2013-10-18 18:11:05 -07003569
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003570 mDisabledSysPackages.put(name, ps);
3571 }
3572
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003573 private static int PRE_M_APP_INFO_FLAG_HIDDEN = 1<<27;
3574 private static int PRE_M_APP_INFO_FLAG_CANT_SAVE_STATE = 1<<28;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003575 private static int PRE_M_APP_INFO_FLAG_PRIVILEGED = 1<<30;
3576
Kenny Root447106f2011-03-23 11:00:15 -07003577 private void readPackageLPw(XmlPullParser parser) throws XmlPullParserException, IOException {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003578 String name = null;
3579 String realName = null;
3580 String idStr = null;
3581 String sharedIdStr = null;
3582 String codePathStr = null;
3583 String resourcePathStr = null;
Narayan Kamathff110bd2014-07-04 18:30:45 +01003584 String legacyCpuAbiString = null;
3585 String legacyNativeLibraryPathStr = null;
3586 String primaryCpuAbiString = null;
3587 String secondaryCpuAbiString = null;
Narayan Kamath4903f642014-08-11 13:33:45 +01003588 String cpuAbiOverrideString = null;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003589 String systemStr = null;
3590 String installerPackageName = null;
Sudheer Shanka8c57aea2016-04-20 16:47:50 -07003591 String isOrphaned = null;
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07003592 String volumeUuid = null;
Jeff Sharkey9bc89af2017-01-11 11:25:50 -07003593 String categoryHintString = null;
Todd Kennedyab532892017-03-08 14:19:49 -08003594 String updateAvailable = null;
Jeff Sharkey9bc89af2017-01-11 11:25:50 -07003595 int categoryHint = ApplicationInfo.CATEGORY_UNDEFINED;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003596 String uidError = null;
3597 int pkgFlags = 0;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003598 int pkgPrivateFlags = 0;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003599 long timeStamp = 0;
3600 long firstInstallTime = 0;
3601 long lastUpdateTime = 0;
Todd Kennedy788c8422016-08-10 10:52:34 -07003602 PackageSetting packageSetting = null;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003603 String version = null;
Dianne Hackborn3accca02013-09-20 09:32:11 -07003604 long versionCode = 0;
Svet Ganov354cd3c2015-12-17 11:35:04 -08003605 String parentPackageName;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003606 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003607 name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003608 realName = parser.getAttributeValue(null, "realName");
3609 idStr = parser.getAttributeValue(null, "userId");
3610 uidError = parser.getAttributeValue(null, "uidError");
3611 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
3612 codePathStr = parser.getAttributeValue(null, "codePath");
3613 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Narayan Kamath9e289d72014-04-10 09:26:59 +00003614
Narayan Kamathff110bd2014-07-04 18:30:45 +01003615 legacyCpuAbiString = parser.getAttributeValue(null, "requiredCpuAbi");
3616
Svet Ganov354cd3c2015-12-17 11:35:04 -08003617 parentPackageName = parser.getAttributeValue(null, "parentPackageName");
3618
Narayan Kamathff110bd2014-07-04 18:30:45 +01003619 legacyNativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
3620 primaryCpuAbiString = parser.getAttributeValue(null, "primaryCpuAbi");
3621 secondaryCpuAbiString = parser.getAttributeValue(null, "secondaryCpuAbi");
Narayan Kamath4903f642014-08-11 13:33:45 +01003622 cpuAbiOverrideString = parser.getAttributeValue(null, "cpuAbiOverride");
Todd Kennedyab532892017-03-08 14:19:49 -08003623 updateAvailable = parser.getAttributeValue(null, "updateAvailable");
Narayan Kamathff110bd2014-07-04 18:30:45 +01003624
3625 if (primaryCpuAbiString == null && legacyCpuAbiString != null) {
3626 primaryCpuAbiString = legacyCpuAbiString;
3627 }
Svetoslavc6d1c342015-02-26 14:44:43 -08003628
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003629 version = parser.getAttributeValue(null, "version");
3630 if (version != null) {
3631 try {
Dianne Hackborn3accca02013-09-20 09:32:11 -07003632 versionCode = Long.parseLong(version);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003633 } catch (NumberFormatException e) {
3634 }
3635 }
3636 installerPackageName = parser.getAttributeValue(null, "installer");
Sudheer Shanka8c57aea2016-04-20 16:47:50 -07003637 isOrphaned = parser.getAttributeValue(null, "isOrphaned");
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07003638 volumeUuid = parser.getAttributeValue(null, "volumeUuid");
Jeff Sharkey9bc89af2017-01-11 11:25:50 -07003639 categoryHintString = parser.getAttributeValue(null, "categoryHint");
3640 if (categoryHintString != null) {
3641 try {
3642 categoryHint = Integer.parseInt(categoryHintString);
3643 } catch (NumberFormatException e) {
3644 }
3645 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003646
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003647 systemStr = parser.getAttributeValue(null, "publicFlags");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003648 if (systemStr != null) {
3649 try {
3650 pkgFlags = Integer.parseInt(systemStr);
3651 } catch (NumberFormatException e) {
3652 }
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003653 systemStr = parser.getAttributeValue(null, "privateFlags");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003654 if (systemStr != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003655 try {
3656 pkgPrivateFlags = Integer.parseInt(systemStr);
3657 } catch (NumberFormatException e) {
3658 }
3659 }
3660 } else {
3661 // Pre-M -- both public and private flags were stored in one "flags" field.
3662 systemStr = parser.getAttributeValue(null, "flags");
3663 if (systemStr != null) {
3664 try {
3665 pkgFlags = Integer.parseInt(systemStr);
3666 } catch (NumberFormatException e) {
3667 }
3668 if ((pkgFlags & PRE_M_APP_INFO_FLAG_HIDDEN) != 0) {
3669 pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_HIDDEN;
3670 }
3671 if ((pkgFlags & PRE_M_APP_INFO_FLAG_CANT_SAVE_STATE) != 0) {
3672 pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE;
3673 }
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003674 if ((pkgFlags & PRE_M_APP_INFO_FLAG_PRIVILEGED) != 0) {
3675 pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
3676 }
3677 pkgFlags &= ~(PRE_M_APP_INFO_FLAG_HIDDEN
3678 | PRE_M_APP_INFO_FLAG_CANT_SAVE_STATE
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003679 | PRE_M_APP_INFO_FLAG_PRIVILEGED);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003680 } else {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003681 // For backward compatibility
3682 systemStr = parser.getAttributeValue(null, "system");
3683 if (systemStr != null) {
3684 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM
3685 : 0;
3686 } else {
3687 // Old settings that don't specify system... just treat
3688 // them as system, good enough.
3689 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
3690 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003691 }
3692 }
3693 String timeStampStr = parser.getAttributeValue(null, "ft");
3694 if (timeStampStr != null) {
3695 try {
3696 timeStamp = Long.parseLong(timeStampStr, 16);
3697 } catch (NumberFormatException e) {
3698 }
3699 } else {
3700 timeStampStr = parser.getAttributeValue(null, "ts");
3701 if (timeStampStr != null) {
3702 try {
3703 timeStamp = Long.parseLong(timeStampStr);
3704 } catch (NumberFormatException e) {
3705 }
3706 }
3707 }
3708 timeStampStr = parser.getAttributeValue(null, "it");
3709 if (timeStampStr != null) {
3710 try {
3711 firstInstallTime = Long.parseLong(timeStampStr, 16);
3712 } catch (NumberFormatException e) {
3713 }
3714 }
3715 timeStampStr = parser.getAttributeValue(null, "ut");
3716 if (timeStampStr != null) {
3717 try {
3718 lastUpdateTime = Long.parseLong(timeStampStr, 16);
3719 } catch (NumberFormatException e) {
3720 }
3721 }
3722 if (PackageManagerService.DEBUG_SETTINGS)
3723 Log.v(PackageManagerService.TAG, "Reading package: " + name + " userId=" + idStr
3724 + " sharedUserId=" + sharedIdStr);
Todd Kennedy788c8422016-08-10 10:52:34 -07003725 final int userId = idStr != null ? Integer.parseInt(idStr) : 0;
3726 final int sharedUserId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003727 if (resourcePathStr == null) {
3728 resourcePathStr = codePathStr;
3729 }
3730 if (realName != null) {
3731 realName = realName.intern();
3732 }
3733 if (name == null) {
3734 PackageManagerService.reportSettingsProblem(Log.WARN,
3735 "Error in package manager settings: <package> has no name at "
3736 + parser.getPositionDescription());
3737 } else if (codePathStr == null) {
3738 PackageManagerService.reportSettingsProblem(Log.WARN,
3739 "Error in package manager settings: <package> has no codePath at "
3740 + parser.getPositionDescription());
3741 } else if (userId > 0) {
Kenny Root447106f2011-03-23 11:00:15 -07003742 packageSetting = addPackageLPw(name.intern(), realName, new File(codePathStr),
Narayan Kamathff110bd2014-07-04 18:30:45 +01003743 new File(resourcePathStr), legacyNativeLibraryPathStr, primaryCpuAbiString,
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003744 secondaryCpuAbiString, cpuAbiOverrideString, userId, versionCode, pkgFlags,
Svet Ganov67882122016-12-11 16:36:34 -08003745 pkgPrivateFlags, parentPackageName, null /*childPackageNames*/,
3746 null /*usesStaticLibraries*/, null /*usesStaticLibraryVersions*/);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003747 if (PackageManagerService.DEBUG_SETTINGS)
3748 Log.i(PackageManagerService.TAG, "Reading package " + name + ": userId="
3749 + userId + " pkg=" + packageSetting);
3750 if (packageSetting == null) {
3751 PackageManagerService.reportSettingsProblem(Log.ERROR, "Failure adding uid "
3752 + userId + " while parsing settings at "
3753 + parser.getPositionDescription());
3754 } else {
3755 packageSetting.setTimeStamp(timeStamp);
3756 packageSetting.firstInstallTime = firstInstallTime;
3757 packageSetting.lastUpdateTime = lastUpdateTime;
3758 }
3759 } else if (sharedIdStr != null) {
Todd Kennedy788c8422016-08-10 10:52:34 -07003760 if (sharedUserId > 0) {
3761 packageSetting = new PackageSetting(name.intern(), realName, new File(
Narayan Kamathff110bd2014-07-04 18:30:45 +01003762 codePathStr), new File(resourcePathStr), legacyNativeLibraryPathStr,
Narayan Kamath4903f642014-08-11 13:33:45 +01003763 primaryCpuAbiString, secondaryCpuAbiString, cpuAbiOverrideString,
Todd Kennedy788c8422016-08-10 10:52:34 -07003764 versionCode, pkgFlags, pkgPrivateFlags, parentPackageName,
Svet Ganov67882122016-12-11 16:36:34 -08003765 null /*childPackageNames*/, sharedUserId,
3766 null /*usesStaticLibraries*/, null /*usesStaticLibraryVersions*/);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003767 packageSetting.setTimeStamp(timeStamp);
3768 packageSetting.firstInstallTime = firstInstallTime;
3769 packageSetting.lastUpdateTime = lastUpdateTime;
Todd Kennedy788c8422016-08-10 10:52:34 -07003770 mPendingPackages.add(packageSetting);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003771 if (PackageManagerService.DEBUG_SETTINGS)
3772 Log.i(PackageManagerService.TAG, "Reading package " + name
Todd Kennedy788c8422016-08-10 10:52:34 -07003773 + ": sharedUserId=" + sharedUserId + " pkg=" + packageSetting);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003774 } else {
3775 PackageManagerService.reportSettingsProblem(Log.WARN,
3776 "Error in package manager settings: package " + name
3777 + " has bad sharedId " + sharedIdStr + " at "
3778 + parser.getPositionDescription());
3779 }
3780 } else {
3781 PackageManagerService.reportSettingsProblem(Log.WARN,
3782 "Error in package manager settings: package " + name + " has bad userId "
3783 + idStr + " at " + parser.getPositionDescription());
3784 }
3785 } catch (NumberFormatException e) {
3786 PackageManagerService.reportSettingsProblem(Log.WARN,
3787 "Error in package manager settings: package " + name + " has bad userId "
3788 + idStr + " at " + parser.getPositionDescription());
3789 }
3790 if (packageSetting != null) {
3791 packageSetting.uidError = "true".equals(uidError);
3792 packageSetting.installerPackageName = installerPackageName;
Sudheer Shanka8c57aea2016-04-20 16:47:50 -07003793 packageSetting.isOrphaned = "true".equals(isOrphaned);
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07003794 packageSetting.volumeUuid = volumeUuid;
Jeff Sharkey9bc89af2017-01-11 11:25:50 -07003795 packageSetting.categoryHint = categoryHint;
Narayan Kamathff110bd2014-07-04 18:30:45 +01003796 packageSetting.legacyNativeLibraryPathString = legacyNativeLibraryPathStr;
3797 packageSetting.primaryCpuAbiString = primaryCpuAbiString;
3798 packageSetting.secondaryCpuAbiString = secondaryCpuAbiString;
Todd Kennedyab532892017-03-08 14:19:49 -08003799 packageSetting.updateAvailable = "true".equals(updateAvailable);
Amith Yamasani483f3b02012-03-13 16:08:00 -07003800 // Handle legacy string here for single-user mode
3801 final String enabledStr = parser.getAttributeValue(null, ATTR_ENABLED);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003802 if (enabledStr != null) {
Dianne Hackbornb8f40002011-07-19 15:17:43 -07003803 try {
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07003804 packageSetting.setEnabled(Integer.parseInt(enabledStr), 0 /* userId */, null);
Dianne Hackbornb8f40002011-07-19 15:17:43 -07003805 } catch (NumberFormatException e) {
3806 if (enabledStr.equalsIgnoreCase("true")) {
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07003807 packageSetting.setEnabled(COMPONENT_ENABLED_STATE_ENABLED, 0, null);
Dianne Hackbornb8f40002011-07-19 15:17:43 -07003808 } else if (enabledStr.equalsIgnoreCase("false")) {
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07003809 packageSetting.setEnabled(COMPONENT_ENABLED_STATE_DISABLED, 0, null);
Dianne Hackbornb8f40002011-07-19 15:17:43 -07003810 } else if (enabledStr.equalsIgnoreCase("default")) {
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07003811 packageSetting.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 0, null);
Dianne Hackbornb8f40002011-07-19 15:17:43 -07003812 } else {
3813 PackageManagerService.reportSettingsProblem(Log.WARN,
3814 "Error in package manager settings: package " + name
3815 + " has bad enabled value: " + idStr + " at "
3816 + parser.getPositionDescription());
3817 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003818 }
3819 } else {
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07003820 packageSetting.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 0, null);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003821 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003822
Sudheer Shanka29283372016-04-04 20:56:27 -07003823 if (installerPackageName != null) {
3824 mInstallerPackages.add(installerPackageName);
3825 }
3826
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003827 int outerDepth = parser.getDepth();
3828 int type;
3829 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3830 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3831 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3832 continue;
3833 }
3834
3835 String tagName = parser.getName();
Selim Gurun5c8acb42016-04-07 16:34:02 -07003836 // Legacy
Amith Yamasani483f3b02012-03-13 16:08:00 -07003837 if (tagName.equals(TAG_DISABLED_COMPONENTS)) {
3838 readDisabledComponentsLPw(packageSetting, parser, 0);
3839 } else if (tagName.equals(TAG_ENABLED_COMPONENTS)) {
3840 readEnabledComponentsLPw(packageSetting, parser, 0);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003841 } else if (tagName.equals("sigs")) {
3842 packageSetting.signatures.readXml(parser, mPastSignatures);
Svetoslavc6d1c342015-02-26 14:44:43 -08003843 } else if (tagName.equals(TAG_PERMISSIONS)) {
3844 readInstallPermissionsLPr(parser,
3845 packageSetting.getPermissionsState());
Svetoslavcf959f62015-03-26 20:53:34 -07003846 packageSetting.installPermissionsFixed = true;
dcashman3a0dbfb2014-07-07 13:53:36 -07003847 } else if (tagName.equals("proper-signing-keyset")) {
3848 long id = Long.parseLong(parser.getAttributeValue(null, "identifier"));
dcashman8c04fac2015-03-23 11:39:42 -07003849 Integer refCt = mKeySetRefs.get(id);
3850 if (refCt != null) {
3851 mKeySetRefs.put(id, refCt + 1);
3852 } else {
3853 mKeySetRefs.put(id, 1);
3854 }
dcashman3a0dbfb2014-07-07 13:53:36 -07003855 packageSetting.keySetData.setProperSigningKeySet(id);
Geremy Condraf1bcca82013-01-07 22:35:24 -08003856 } else if (tagName.equals("signing-keyset")) {
dcashman8c04fac2015-03-23 11:39:42 -07003857 // from v1 of keysetmanagerservice - no longer used
dcashman55b10782014-04-09 14:20:38 -07003858 } else if (tagName.equals("upgrade-keyset")) {
3859 long id = Long.parseLong(parser.getAttributeValue(null, "identifier"));
3860 packageSetting.keySetData.addUpgradeKeySetById(id);
Geremy Condraf1bcca82013-01-07 22:35:24 -08003861 } else if (tagName.equals("defined-keyset")) {
3862 long id = Long.parseLong(parser.getAttributeValue(null, "identifier"));
3863 String alias = parser.getAttributeValue(null, "alias");
dcashman8c04fac2015-03-23 11:39:42 -07003864 Integer refCt = mKeySetRefs.get(id);
3865 if (refCt != null) {
3866 mKeySetRefs.put(id, refCt + 1);
3867 } else {
3868 mKeySetRefs.put(id, 1);
3869 }
Geremy Condraf1bcca82013-01-07 22:35:24 -08003870 packageSetting.keySetData.addDefinedKeySet(id, alias);
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08003871 } else if (tagName.equals(TAG_DOMAIN_VERIFICATION)) {
3872 readDomainVerificationLPw(parser, packageSetting);
Svet Ganov354cd3c2015-12-17 11:35:04 -08003873 } else if (tagName.equals(TAG_CHILD_PACKAGE)) {
3874 String childPackageName = parser.getAttributeValue(null, ATTR_NAME);
3875 if (packageSetting.childPackageNames == null) {
3876 packageSetting.childPackageNames = new ArrayList<>();
3877 }
3878 packageSetting.childPackageNames.add(childPackageName);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003879 } else {
3880 PackageManagerService.reportSettingsProblem(Log.WARN,
3881 "Unknown element under <package>: " + parser.getName());
3882 XmlUtils.skipCurrentTag(parser);
3883 }
3884 }
3885 } else {
3886 XmlUtils.skipCurrentTag(parser);
3887 }
3888 }
3889
Amith Yamasani483f3b02012-03-13 16:08:00 -07003890 private void readDisabledComponentsLPw(PackageSettingBase packageSetting, XmlPullParser parser,
3891 int userId) throws IOException, XmlPullParserException {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003892 int outerDepth = parser.getDepth();
3893 int type;
3894 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3895 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3896 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3897 continue;
3898 }
3899
3900 String tagName = parser.getName();
Amith Yamasani483f3b02012-03-13 16:08:00 -07003901 if (tagName.equals(TAG_ITEM)) {
3902 String name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003903 if (name != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003904 packageSetting.addDisabledComponent(name.intern(), userId);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003905 } else {
3906 PackageManagerService.reportSettingsProblem(Log.WARN,
3907 "Error in package manager settings: <disabled-components> has"
3908 + " no name at " + parser.getPositionDescription());
3909 }
3910 } else {
3911 PackageManagerService.reportSettingsProblem(Log.WARN,
3912 "Unknown element under <disabled-components>: " + parser.getName());
3913 }
3914 XmlUtils.skipCurrentTag(parser);
3915 }
3916 }
3917
Amith Yamasani483f3b02012-03-13 16:08:00 -07003918 private void readEnabledComponentsLPw(PackageSettingBase packageSetting, XmlPullParser parser,
3919 int userId) throws IOException, XmlPullParserException {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003920 int outerDepth = parser.getDepth();
3921 int type;
3922 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3923 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3924 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3925 continue;
3926 }
3927
3928 String tagName = parser.getName();
Amith Yamasani483f3b02012-03-13 16:08:00 -07003929 if (tagName.equals(TAG_ITEM)) {
3930 String name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003931 if (name != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003932 packageSetting.addEnabledComponent(name.intern(), userId);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003933 } else {
3934 PackageManagerService.reportSettingsProblem(Log.WARN,
3935 "Error in package manager settings: <enabled-components> has"
3936 + " no name at " + parser.getPositionDescription());
3937 }
3938 } else {
3939 PackageManagerService.reportSettingsProblem(Log.WARN,
3940 "Unknown element under <enabled-components>: " + parser.getName());
3941 }
3942 XmlUtils.skipCurrentTag(parser);
3943 }
3944 }
3945
Amith Yamasani483f3b02012-03-13 16:08:00 -07003946 private void readSharedUserLPw(XmlPullParser parser) throws XmlPullParserException,IOException {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003947 String name = null;
3948 String idStr = null;
3949 int pkgFlags = 0;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003950 int pkgPrivateFlags = 0;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003951 SharedUserSetting su = null;
3952 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003953 name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003954 idStr = parser.getAttributeValue(null, "userId");
3955 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
3956 if ("true".equals(parser.getAttributeValue(null, "system"))) {
3957 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
3958 }
3959 if (name == null) {
3960 PackageManagerService.reportSettingsProblem(Log.WARN,
3961 "Error in package manager settings: <shared-user> has no name at "
3962 + parser.getPositionDescription());
3963 } else if (userId == 0) {
3964 PackageManagerService.reportSettingsProblem(Log.WARN,
3965 "Error in package manager settings: shared-user " + name
3966 + " has bad userId " + idStr + " at "
3967 + parser.getPositionDescription());
3968 } else {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003969 if ((su = addSharedUserLPw(name.intern(), userId, pkgFlags, pkgPrivateFlags))
3970 == null) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003971 PackageManagerService
3972 .reportSettingsProblem(Log.ERROR, "Occurred while parsing settings at "
3973 + parser.getPositionDescription());
3974 }
3975 }
3976 } catch (NumberFormatException e) {
3977 PackageManagerService.reportSettingsProblem(Log.WARN,
3978 "Error in package manager settings: package " + name + " has bad userId "
3979 + idStr + " at " + parser.getPositionDescription());
3980 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003981
3982 if (su != null) {
3983 int outerDepth = parser.getDepth();
3984 int type;
3985 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3986 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3987 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3988 continue;
3989 }
3990
3991 String tagName = parser.getName();
3992 if (tagName.equals("sigs")) {
3993 su.signatures.readXml(parser, mPastSignatures);
3994 } else if (tagName.equals("perms")) {
Svetoslavc6d1c342015-02-26 14:44:43 -08003995 readInstallPermissionsLPr(parser, su.getPermissionsState());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003996 } else {
3997 PackageManagerService.reportSettingsProblem(Log.WARN,
3998 "Unknown element under <shared-user>: " + parser.getName());
3999 XmlUtils.skipCurrentTag(parser);
4000 }
4001 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07004002 } else {
4003 XmlUtils.skipCurrentTag(parser);
4004 }
4005 }
4006
Fyodor Kupolovd8327bd2015-11-30 17:42:43 -08004007 void createNewUserLI(@NonNull PackageManagerService service, @NonNull Installer installer,
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07004008 int userHandle, String[] disallowedPackages) {
Fyodor Kupolovd8327bd2015-11-30 17:42:43 -08004009 String[] volumeUuids;
4010 String[] names;
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -07004011 int[] appIds;
Fyodor Kupolovd8327bd2015-11-30 17:42:43 -08004012 String[] seinfos;
Janis Danisevskisf3409742016-01-12 14:46:33 +00004013 int[] targetSdkVersions;
Fyodor Kupolovd8327bd2015-11-30 17:42:43 -08004014 int packagesCount;
4015 synchronized (mPackages) {
4016 Collection<PackageSetting> packages = mPackages.values();
4017 packagesCount = packages.size();
4018 volumeUuids = new String[packagesCount];
4019 names = new String[packagesCount];
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -07004020 appIds = new int[packagesCount];
Fyodor Kupolovd8327bd2015-11-30 17:42:43 -08004021 seinfos = new String[packagesCount];
Janis Danisevskisf3409742016-01-12 14:46:33 +00004022 targetSdkVersions = new int[packagesCount];
Fyodor Kupolovd8327bd2015-11-30 17:42:43 -08004023 Iterator<PackageSetting> packagesIterator = packages.iterator();
4024 for (int i = 0; i < packagesCount; i++) {
4025 PackageSetting ps = packagesIterator.next();
4026 if (ps.pkg == null || ps.pkg.applicationInfo == null) {
4027 continue;
4028 }
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07004029 final boolean shouldInstall = ps.isSystem() &&
Rhed Jaocd47c262018-06-13 11:16:16 +08004030 !ArrayUtils.contains(disallowedPackages, ps.name) &&
4031 !ps.pkg.applicationInfo.hiddenUntilInstalled;
Fyodor Kupolovd8327bd2015-11-30 17:42:43 -08004032 // Only system apps are initially installed.
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07004033 ps.setInstalled(shouldInstall, userHandle);
Amith Yamasani23ab7f52017-01-22 17:43:24 -08004034 if (!shouldInstall) {
4035 writeKernelMappingLPr(ps);
4036 }
Fyodor Kupolovd8327bd2015-11-30 17:42:43 -08004037 // Need to create a data directory for all apps under this user. Accumulate all
4038 // required args and call the installer after mPackages lock has been released
4039 volumeUuids[i] = ps.volumeUuid;
4040 names[i] = ps.name;
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -07004041 appIds[i] = ps.appId;
Todd Kennedybe0b8892017-02-15 14:13:52 -08004042 seinfos[i] = ps.pkg.applicationInfo.seInfo;
Janis Danisevskisf3409742016-01-12 14:46:33 +00004043 targetSdkVersions[i] = ps.pkg.applicationInfo.targetSdkVersion;
Fyodor Kupolovd8327bd2015-11-30 17:42:43 -08004044 }
4045 }
4046 for (int i = 0; i < packagesCount; i++) {
4047 if (names[i] == null) {
Amith Yamasani41cd5772014-07-10 15:26:00 -07004048 continue;
4049 }
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -07004050 // TODO: triage flags!
Jeff Sharkey47f71082016-02-01 17:03:54 -07004051 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -07004052 try {
4053 installer.createAppData(volumeUuids[i], names[i], userHandle, flags, appIds[i],
Janis Danisevskisf3409742016-01-12 14:46:33 +00004054 seinfos[i], targetSdkVersions[i]);
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -07004055 } catch (InstallerException e) {
4056 Slog.w(TAG, "Failed to prepare app data", e);
4057 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07004058 }
Fyodor Kupolovd8327bd2015-11-30 17:42:43 -08004059 synchronized (mPackages) {
Todd Kennedycf827032018-07-03 13:17:22 -07004060 applyDefaultPreferredAppsLPw(userHandle);
Fyodor Kupolovd8327bd2015-11-30 17:42:43 -08004061 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07004062 }
4063
Alexandra Gherghina539a7ef2014-07-07 12:27:54 +01004064 void removeUserLPw(int userId) {
Dianne Hackborn63092712012-10-07 14:45:35 -07004065 Set<Entry<String, PackageSetting>> entries = mPackages.entrySet();
4066 for (Entry<String, PackageSetting> entry : entries) {
4067 entry.getValue().removeUser(userId);
4068 }
4069 mPreferredActivities.remove(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07004070 File file = getUserPackagesStateFile(userId);
4071 file.delete();
4072 file = getUserPackagesStateBackupFile(userId);
4073 file.delete();
Nicolas Prevote7024042014-07-08 15:47:17 +01004074 removeCrossProfileIntentFiltersLPw(userId);
Svetoslavc6d1c342015-02-26 14:44:43 -08004075
Fyodor Kupolov69542592016-05-23 14:22:38 -07004076 mRuntimePermissionsPersistence.onUserRemovedLPw(userId);
Jeff Sharkey91edde22015-05-20 12:04:42 -07004077
4078 writePackageListLPr();
Amith Yamasani23ab7f52017-01-22 17:43:24 -08004079
4080 // Inform kernel that the user was removed, so that packages are marked uninstalled
4081 // for sdcardfs
4082 writeKernelRemoveUserLPr(userId);
Nicolas Prevota0f48852014-05-27 11:21:11 +01004083 }
4084
Nicolas Prevote7024042014-07-08 15:47:17 +01004085 void removeCrossProfileIntentFiltersLPw(int userId) {
4086 synchronized (mCrossProfileIntentResolvers) {
4087 // userId is the source user
4088 if (mCrossProfileIntentResolvers.get(userId) != null) {
4089 mCrossProfileIntentResolvers.remove(userId);
4090 writePackageRestrictionsLPr(userId);
Nicolas Prevota0f48852014-05-27 11:21:11 +01004091 }
Nicolas Prevote7024042014-07-08 15:47:17 +01004092 // userId is the target user
4093 int count = mCrossProfileIntentResolvers.size();
4094 for (int i = 0; i < count; i++) {
4095 int sourceUserId = mCrossProfileIntentResolvers.keyAt(i);
4096 CrossProfileIntentResolver cpir = mCrossProfileIntentResolvers.get(sourceUserId);
4097 boolean needsWriting = false;
Jeff Sharkey9f837a92014-10-24 12:07:24 -07004098 ArraySet<CrossProfileIntentFilter> cpifs =
4099 new ArraySet<CrossProfileIntentFilter>(cpir.filterSet());
Nicolas Prevote7024042014-07-08 15:47:17 +01004100 for (CrossProfileIntentFilter cpif : cpifs) {
4101 if (cpif.getTargetUserId() == userId) {
4102 needsWriting = true;
4103 cpir.removeFilter(cpif);
4104 }
4105 }
4106 if (needsWriting) {
4107 writePackageRestrictionsLPr(sourceUserId);
4108 }
Nicolas Prevota0f48852014-05-27 11:21:11 +01004109 }
4110 }
Amith Yamasani13593602012-03-22 16:16:17 -07004111 }
4112
Geremy Condra12c18382013-03-06 16:49:06 -08004113 // This should be called (at least) whenever an application is removed
4114 private void setFirstAvailableUid(int uid) {
4115 if (uid > mFirstAvailableUid) {
4116 mFirstAvailableUid = uid;
4117 }
4118 }
4119
Patrick Baumann649a8572018-11-20 11:16:58 -08004120 /** Returns a new AppID or -1 if we could not find an available AppID to assign */
4121 private int acquireAndRegisterNewAppIdLPw(SettingBase obj) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07004122 // Let's be stupidly inefficient for now...
Patrick Baumann649a8572018-11-20 11:16:58 -08004123 final int size = mAppIds.size();
4124 for (int i = mFirstAvailableUid; i < size; i++) {
4125 if (mAppIds.get(i) == null) {
4126 mAppIds.set(i, obj);
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08004127 return Process.FIRST_APPLICATION_UID + i;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07004128 }
4129 }
4130
4131 // None left?
Patrick Baumann649a8572018-11-20 11:16:58 -08004132 if (size > (Process.LAST_APPLICATION_UID - Process.FIRST_APPLICATION_UID)) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07004133 return -1;
4134 }
4135
Patrick Baumann649a8572018-11-20 11:16:58 -08004136 mAppIds.add(obj);
4137 return Process.FIRST_APPLICATION_UID + size;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07004138 }
4139
Kenny Root0aaa0d92011-09-12 16:42:55 -07004140 public VerifierDeviceIdentity getVerifierDeviceIdentityLPw() {
4141 if (mVerifierDeviceIdentity == null) {
4142 mVerifierDeviceIdentity = VerifierDeviceIdentity.generate();
4143
4144 writeLPr();
4145 }
4146
4147 return mVerifierDeviceIdentity;
4148 }
4149
Todd Kennedyff35e662016-09-20 12:53:52 -07004150 boolean hasOtherDisabledSystemPkgWithChildLPr(String parentPackageName,
Svet Ganov354cd3c2015-12-17 11:35:04 -08004151 String childPackageName) {
4152 final int packageCount = mDisabledSysPackages.size();
4153 for (int i = 0; i < packageCount; i++) {
4154 PackageSetting disabledPs = mDisabledSysPackages.valueAt(i);
4155 if (disabledPs.childPackageNames == null || disabledPs.childPackageNames.isEmpty()) {
4156 continue;
4157 }
4158 if (disabledPs.name.equals(parentPackageName)) {
4159 continue;
4160 }
4161 final int childCount = disabledPs.childPackageNames.size();
4162 for (int j = 0; j < childCount; j++) {
4163 String currChildPackageName = disabledPs.childPackageNames.get(j);
4164 if (currChildPackageName.equals(childPackageName)) {
4165 return true;
4166 }
4167 }
4168 }
4169 return false;
4170 }
4171
Patrick Baumann41407832018-11-09 15:02:38 -08004172 /**
4173 * Returns the disabled {@link PackageSetting} for the provided package name if one exists,
4174 * {@code null} otherwise.
4175 */
4176 @Nullable
Kenny Root447106f2011-03-23 11:00:15 -07004177 public PackageSetting getDisabledSystemPkgLPr(String name) {
4178 PackageSetting ps = mDisabledSysPackages.get(name);
4179 return ps;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07004180 }
4181
Patrick Baumann41407832018-11-09 15:02:38 -08004182 /**
4183 * Returns the disabled {@link PackageSetting} for the provided enabled {@link PackageSetting}
4184 * if one exists, {@code null} otherwise.
4185 */
4186 @Nullable
4187 public PackageSetting getDisabledSystemPkgLPr(PackageSetting enabledPackageSetting) {
4188 if (enabledPackageSetting == null) {
4189 return null;
4190 }
4191 return getDisabledSystemPkgLPr(enabledPackageSetting.name);
4192 }
4193
4194 /**
4195 * Fetches an array of the child {@link PackageSetting}s for all child package names referenced
4196 * by the provided parent {@link PackageSetting} or {@code null} if no children are referenced.
4197 *
4198 * Note: Any child packages not found will be null in the returned array.
4199 */
4200 @Nullable
4201 public PackageSetting[] getChildSettingsLPr(PackageSetting parentPackageSetting) {
4202 if (parentPackageSetting == null || !parentPackageSetting.hasChildPackages()) {
4203 return null;
4204 }
4205 final int childCount = parentPackageSetting.childPackageNames.size();
4206 PackageSetting[] children =
4207 new PackageSetting[childCount];
4208 for (int i = 0; i < childCount; i++) {
4209 children[i] = mPackages.get(parentPackageSetting.childPackageNames.get(i));
4210 }
4211 return children;
4212 }
4213
Jeff Sharkey5217cac2015-12-20 15:34:01 -07004214 boolean isEnabledAndMatchLPr(ComponentInfo componentInfo, int flags, int userId) {
Jeff Sharkey2bd31db2016-01-09 16:58:14 -07004215 final PackageSetting ps = mPackages.get(componentInfo.packageName);
4216 if (ps == null) return false;
Jeff Sharkeye17ac152015-11-06 22:40:29 -08004217
Jeff Sharkey2bd31db2016-01-09 16:58:14 -07004218 final PackageUserState userState = ps.readUserState(userId);
4219 return userState.isMatch(componentInfo, flags);
Jeff Sharkeye17ac152015-11-06 22:40:29 -08004220 }
4221
Kenny Root447106f2011-03-23 11:00:15 -07004222 String getInstallerPackageNameLPr(String packageName) {
4223 final PackageSetting pkg = mPackages.get(packageName);
4224 if (pkg == null) {
4225 throw new IllegalArgumentException("Unknown package: " + packageName);
4226 }
4227 return pkg.installerPackageName;
4228 }
4229
Sudheer Shanka8c57aea2016-04-20 16:47:50 -07004230 boolean isOrphaned(String packageName) {
4231 final PackageSetting pkg = mPackages.get(packageName);
4232 if (pkg == null) {
4233 throw new IllegalArgumentException("Unknown package: " + packageName);
4234 }
4235 return pkg.isOrphaned;
4236 }
4237
Amith Yamasani483f3b02012-03-13 16:08:00 -07004238 int getApplicationEnabledSettingLPr(String packageName, int userId) {
Kenny Root447106f2011-03-23 11:00:15 -07004239 final PackageSetting pkg = mPackages.get(packageName);
4240 if (pkg == null) {
4241 throw new IllegalArgumentException("Unknown package: " + packageName);
4242 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07004243 return pkg.getEnabled(userId);
Kenny Root447106f2011-03-23 11:00:15 -07004244 }
4245
Amith Yamasani483f3b02012-03-13 16:08:00 -07004246 int getComponentEnabledSettingLPr(ComponentName componentName, int userId) {
Kenny Root447106f2011-03-23 11:00:15 -07004247 final String packageName = componentName.getPackageName();
4248 final PackageSetting pkg = mPackages.get(packageName);
4249 if (pkg == null) {
4250 throw new IllegalArgumentException("Unknown component: " + componentName);
4251 }
4252 final String classNameStr = componentName.getClassName();
Amith Yamasani483f3b02012-03-13 16:08:00 -07004253 return pkg.getCurrentEnabledStateLPr(classNameStr, userId);
Kenny Root447106f2011-03-23 11:00:15 -07004254 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07004255
Svet Ganov973edd192016-09-08 20:15:55 -07004256 boolean wasPackageEverLaunchedLPr(String packageName, int userId) {
4257 final PackageSetting pkgSetting = mPackages.get(packageName);
4258 if (pkgSetting == null) {
4259 throw new IllegalArgumentException("Unknown package: " + packageName);
4260 }
4261 return !pkgSetting.getNotLaunched(userId);
4262 }
4263
Christopher Tate5cf55782016-04-25 17:08:56 -07004264 boolean setPackageStoppedStateLPw(PackageManagerService pm, String packageName,
Jeff Sharkeybd0e9e42015-04-30 16:04:50 -07004265 boolean stopped, boolean allowedByPermission, int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004266 int appId = UserHandle.getAppId(uid);
Kenny Root447106f2011-03-23 11:00:15 -07004267 final PackageSetting pkgSetting = mPackages.get(packageName);
4268 if (pkgSetting == null) {
4269 throw new IllegalArgumentException("Unknown package: " + packageName);
4270 }
Amith Yamasani13593602012-03-22 16:16:17 -07004271 if (!allowedByPermission && (appId != pkgSetting.appId)) {
Kenny Root447106f2011-03-23 11:00:15 -07004272 throw new SecurityException(
4273 "Permission Denial: attempt to change stopped state from pid="
4274 + Binder.getCallingPid()
Amith Yamasani13593602012-03-22 16:16:17 -07004275 + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
Kenny Root447106f2011-03-23 11:00:15 -07004276 }
4277 if (DEBUG_STOPPED) {
4278 if (stopped) {
4279 RuntimeException e = new RuntimeException("here");
4280 e.fillInStackTrace();
4281 Slog.i(TAG, "Stopping package " + packageName, e);
4282 }
4283 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07004284 if (pkgSetting.getStopped(userId) != stopped) {
4285 pkgSetting.setStopped(stopped, userId);
4286 // pkgSetting.pkg.mSetStopped = stopped;
4287 if (pkgSetting.getNotLaunched(userId)) {
Kenny Root447106f2011-03-23 11:00:15 -07004288 if (pkgSetting.installerPackageName != null) {
Christopher Tate5cf55782016-04-25 17:08:56 -07004289 pm.notifyFirstLaunch(pkgSetting.name, pkgSetting.installerPackageName, userId);
Kenny Root447106f2011-03-23 11:00:15 -07004290 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07004291 pkgSetting.setNotLaunched(false, userId);
Kenny Root447106f2011-03-23 11:00:15 -07004292 }
4293 return true;
4294 }
4295 return false;
4296 }
4297
Ben Gruver1ab3d6e2017-12-07 13:45:08 -08004298 void setHarmfulAppWarningLPw(String packageName, CharSequence warning, int userId) {
4299 final PackageSetting pkgSetting = mPackages.get(packageName);
4300 if (pkgSetting == null) {
4301 throw new IllegalArgumentException("Unknown package: " + packageName);
4302 }
4303 pkgSetting.setHarmfulAppWarning(userId, warning == null ? null : warning.toString());
4304 }
4305
4306 String getHarmfulAppWarningLPr(String packageName, int userId) {
4307 final PackageSetting pkgSetting = mPackages.get(packageName);
4308 if (pkgSetting == null) {
4309 throw new IllegalArgumentException("Unknown package: " + packageName);
4310 }
4311 return pkgSetting.getHarmfulAppWarning(userId);
4312 }
4313
Todd Kennedy13715d52016-08-01 13:38:57 -07004314 private static List<UserInfo> getAllUsers(UserManagerService userManager) {
Amith Yamasani7ea3e7d2012-04-20 15:19:35 -07004315 long id = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07004316 try {
Todd Kennedy13715d52016-08-01 13:38:57 -07004317 return userManager.getUsers(false);
Amith Yamasani483f3b02012-03-13 16:08:00 -07004318 } catch (NullPointerException npe) {
4319 // packagemanager not yet initialized
Amith Yamasani7ea3e7d2012-04-20 15:19:35 -07004320 } finally {
4321 Binder.restoreCallingIdentity(id);
Amith Yamasani483f3b02012-03-13 16:08:00 -07004322 }
4323 return null;
4324 }
4325
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07004326 /**
4327 * Return all {@link PackageSetting} that are actively installed on the
4328 * given {@link VolumeInfo#fsUuid}.
4329 */
4330 List<PackageSetting> getVolumePackagesLPr(String volumeUuid) {
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07004331 ArrayList<PackageSetting> res = new ArrayList<>();
4332 for (int i = 0; i < mPackages.size(); i++) {
4333 final PackageSetting setting = mPackages.valueAt(i);
4334 if (Objects.equals(volumeUuid, setting.volumeUuid)) {
4335 res.add(setting);
4336 }
4337 }
4338 return res;
4339 }
4340
Svetoslavc6d1c342015-02-26 14:44:43 -08004341 static void printFlags(PrintWriter pw, int val, Object[] spec) {
Joe Onorato20963df2012-01-04 18:13:24 -08004342 pw.print("[ ");
4343 for (int i=0; i<spec.length; i+=2) {
4344 int mask = (Integer)spec[i];
4345 if ((val & mask) != 0) {
4346 pw.print(spec[i+1]);
4347 pw.print(" ");
4348 }
4349 }
4350 pw.print("]");
4351 }
4352
4353 static final Object[] FLAG_DUMP_SPEC = new Object[] {
4354 ApplicationInfo.FLAG_SYSTEM, "SYSTEM",
4355 ApplicationInfo.FLAG_DEBUGGABLE, "DEBUGGABLE",
4356 ApplicationInfo.FLAG_HAS_CODE, "HAS_CODE",
4357 ApplicationInfo.FLAG_PERSISTENT, "PERSISTENT",
4358 ApplicationInfo.FLAG_FACTORY_TEST, "FACTORY_TEST",
4359 ApplicationInfo.FLAG_ALLOW_TASK_REPARENTING, "ALLOW_TASK_REPARENTING",
4360 ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA, "ALLOW_CLEAR_USER_DATA",
4361 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, "UPDATED_SYSTEM_APP",
4362 ApplicationInfo.FLAG_TEST_ONLY, "TEST_ONLY",
4363 ApplicationInfo.FLAG_VM_SAFE_MODE, "VM_SAFE_MODE",
4364 ApplicationInfo.FLAG_ALLOW_BACKUP, "ALLOW_BACKUP",
4365 ApplicationInfo.FLAG_KILL_AFTER_RESTORE, "KILL_AFTER_RESTORE",
4366 ApplicationInfo.FLAG_RESTORE_ANY_VERSION, "RESTORE_ANY_VERSION",
4367 ApplicationInfo.FLAG_EXTERNAL_STORAGE, "EXTERNAL_STORAGE",
4368 ApplicationInfo.FLAG_LARGE_HEAP, "LARGE_HEAP",
Alex Klyubinb9f8a522015-02-03 11:12:59 -08004369 };
4370
Wale Ogunwale72a73e32016-10-13 12:16:39 -07004371 private static final Object[] PRIVATE_FLAG_DUMP_SPEC = new Object[] {
Svet Ganov087dce22017-09-07 15:42:16 -07004372 ApplicationInfo.PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_RESIZEABLE, "PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_RESIZEABLE",
4373 ApplicationInfo.PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION, "PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION",
4374 ApplicationInfo.PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_UNRESIZEABLE, "PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_UNRESIZEABLE",
Kevin Rocardf91d50b2019-02-21 14:32:46 -08004375 ApplicationInfo.PRIVATE_FLAG_ALLOW_AUDIO_PLAYBACK_CAPTURE, "ALLOW_AUDIO_PLAYBACK_CAPTURE",
Svet Ganov087dce22017-09-07 15:42:16 -07004376 ApplicationInfo.PRIVATE_FLAG_BACKUP_IN_FOREGROUND, "BACKUP_IN_FOREGROUND",
4377 ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE, "CANT_SAVE_STATE",
4378 ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE, "DEFAULT_TO_DEVICE_PROTECTED_STORAGE",
4379 ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE, "DIRECT_BOOT_AWARE",
Svet Ganov087dce22017-09-07 15:42:16 -07004380 ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS, "HAS_DOMAIN_URLS",
4381 ApplicationInfo.PRIVATE_FLAG_HIDDEN, "HIDDEN",
4382 ApplicationInfo.PRIVATE_FLAG_INSTANT, "EPHEMERAL",
4383 ApplicationInfo.PRIVATE_FLAG_ISOLATED_SPLIT_LOADING, "ISOLATED_SPLIT_LOADING",
4384 ApplicationInfo.PRIVATE_FLAG_OEM, "OEM",
4385 ApplicationInfo.PRIVATE_FLAG_PARTIALLY_DIRECT_BOOT_AWARE, "PARTIALLY_DIRECT_BOOT_AWARE",
4386 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED, "PRIVILEGED",
4387 ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER, "REQUIRED_FOR_SYSTEM_USER",
4388 ApplicationInfo.PRIVATE_FLAG_STATIC_SHARED_LIBRARY, "STATIC_SHARED_LIBRARY",
Jiyong Park002fdbd2017-02-13 20:50:31 +09004389 ApplicationInfo.PRIVATE_FLAG_VENDOR, "VENDOR",
Jaekyun Seok1713d9e2018-01-12 21:47:26 +09004390 ApplicationInfo.PRIVATE_FLAG_PRODUCT, "PRODUCT",
Dario Freni2bef1762018-06-01 14:02:08 +01004391 ApplicationInfo.PRIVATE_FLAG_PRODUCT_SERVICES, "PRODUCT_SERVICES",
Svet Ganov087dce22017-09-07 15:42:16 -07004392 ApplicationInfo.PRIVATE_FLAG_VIRTUAL_PRELOAD, "VIRTUAL_PRELOAD",
Joe Onorato20963df2012-01-04 18:13:24 -08004393 };
4394
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07004395 void dumpVersionLPr(IndentingPrintWriter pw) {
4396 pw.increaseIndent();
4397 for (int i= 0; i < mVersion.size(); i++) {
4398 final String volumeUuid = mVersion.keyAt(i);
4399 final VersionInfo ver = mVersion.valueAt(i);
4400 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
4401 pw.println("Internal:");
4402 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
4403 pw.println("External:");
4404 } else {
4405 pw.println("UUID " + volumeUuid + ":");
4406 }
4407 pw.increaseIndent();
4408 pw.printPair("sdkVersion", ver.sdkVersion);
4409 pw.printPair("databaseVersion", ver.databaseVersion);
4410 pw.println();
4411 pw.printPair("fingerprint", ver.fingerprint);
4412 pw.println();
4413 pw.decreaseIndent();
4414 }
4415 pw.decreaseIndent();
4416 }
4417
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004418 void dumpPackageLPr(PrintWriter pw, String prefix, String checkinTag,
4419 ArraySet<String> permissionNames, PackageSetting ps, SimpleDateFormat sdf,
Makoto Onuki0a068582018-06-13 10:57:34 -07004420 Date date, List<UserInfo> users, boolean dumpAll, boolean dumpAllComponents) {
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004421 if (checkinTag != null) {
4422 pw.print(checkinTag);
4423 pw.print(",");
4424 pw.print(ps.realName != null ? ps.realName : ps.name);
4425 pw.print(",");
4426 pw.print(ps.appId);
4427 pw.print(",");
4428 pw.print(ps.versionCode);
4429 pw.print(",");
4430 pw.print(ps.firstInstallTime);
4431 pw.print(",");
4432 pw.print(ps.lastUpdateTime);
4433 pw.print(",");
4434 pw.print(ps.installerPackageName != null ? ps.installerPackageName : "?");
4435 pw.println();
Jeff Sharkeyc4d05fc2014-12-01 16:24:01 -08004436 if (ps.pkg != null) {
4437 pw.print(checkinTag); pw.print("-"); pw.print("splt,");
4438 pw.print("base,");
4439 pw.println(ps.pkg.baseRevisionCode);
4440 if (ps.pkg.splitNames != null) {
4441 for (int i = 0; i < ps.pkg.splitNames.length; i++) {
4442 pw.print(checkinTag); pw.print("-"); pw.print("splt,");
4443 pw.print(ps.pkg.splitNames[i]); pw.print(",");
4444 pw.println(ps.pkg.splitRevisionCodes[i]);
4445 }
4446 }
4447 }
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004448 for (UserInfo user : users) {
4449 pw.print(checkinTag);
4450 pw.print("-");
4451 pw.print("usr");
4452 pw.print(",");
4453 pw.print(user.id);
4454 pw.print(",");
4455 pw.print(ps.getInstalled(user.id) ? "I" : "i");
Amith Yamasanie5bcff62014-07-19 15:44:09 -07004456 pw.print(ps.getHidden(user.id) ? "B" : "b");
Andrei Stingaceanu1e283912015-11-26 15:26:28 +00004457 pw.print(ps.getSuspended(user.id) ? "SU" : "su");
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004458 pw.print(ps.getStopped(user.id) ? "S" : "s");
4459 pw.print(ps.getNotLaunched(user.id) ? "l" : "L");
Todd Kennedybe0b8892017-02-15 14:13:52 -08004460 pw.print(ps.getInstantApp(user.id) ? "IA" : "ia");
Todd Kennedy5eb5a7d2017-08-01 07:42:47 -07004461 pw.print(ps.getVirtulalPreload(user.id) ? "VPI" : "vpi");
Ben Gruver1ab3d6e2017-12-07 13:45:08 -08004462 String harmfulAppWarning = ps.getHarmfulAppWarning(user.id);
4463 pw.print(harmfulAppWarning != null ? "HA" : "ha");
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004464 pw.print(",");
4465 pw.print(ps.getEnabled(user.id));
4466 String lastDisabledAppCaller = ps.getLastDisabledAppCaller(user.id);
4467 pw.print(",");
4468 pw.print(lastDisabledAppCaller != null ? lastDisabledAppCaller : "?");
Ben Gruver1ab3d6e2017-12-07 13:45:08 -08004469 pw.print(",");
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004470 pw.println();
4471 }
4472 return;
4473 }
4474
Dianne Hackbornc895be72013-03-11 17:48:43 -07004475 pw.print(prefix); pw.print("Package [");
4476 pw.print(ps.realName != null ? ps.realName : ps.name);
4477 pw.print("] (");
4478 pw.print(Integer.toHexString(System.identityHashCode(ps)));
4479 pw.println("):");
4480
4481 if (ps.realName != null) {
4482 pw.print(prefix); pw.print(" compat name=");
4483 pw.println(ps.name);
4484 }
4485
Svetoslavc6d1c342015-02-26 14:44:43 -08004486 pw.print(prefix); pw.print(" userId="); pw.println(ps.appId);
4487
Dianne Hackbornc895be72013-03-11 17:48:43 -07004488 if (ps.sharedUser != null) {
4489 pw.print(prefix); pw.print(" sharedUser="); pw.println(ps.sharedUser);
4490 }
4491 pw.print(prefix); pw.print(" pkg="); pw.println(ps.pkg);
4492 pw.print(prefix); pw.print(" codePath="); pw.println(ps.codePathString);
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004493 if (permissionNames == null) {
4494 pw.print(prefix); pw.print(" resourcePath="); pw.println(ps.resourcePathString);
4495 pw.print(prefix); pw.print(" legacyNativeLibraryDir=");
4496 pw.println(ps.legacyNativeLibraryPathString);
4497 pw.print(prefix); pw.print(" primaryCpuAbi="); pw.println(ps.primaryCpuAbiString);
4498 pw.print(prefix); pw.print(" secondaryCpuAbi="); pw.println(ps.secondaryCpuAbiString);
4499 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004500 pw.print(prefix); pw.print(" versionCode="); pw.print(ps.versionCode);
4501 if (ps.pkg != null) {
Todd Kennedy89d60182016-03-11 11:18:32 -08004502 pw.print(" minSdk="); pw.print(ps.pkg.applicationInfo.minSdkVersion);
Dianne Hackbornc895be72013-03-11 17:48:43 -07004503 pw.print(" targetSdk="); pw.print(ps.pkg.applicationInfo.targetSdkVersion);
4504 }
4505 pw.println();
4506 if (ps.pkg != null) {
Svet Ganov354cd3c2015-12-17 11:35:04 -08004507 if (ps.pkg.parentPackage != null) {
4508 PackageParser.Package parentPkg = ps.pkg.parentPackage;
4509 PackageSetting pps = mPackages.get(parentPkg.packageName);
4510 if (pps == null || !pps.codePathString.equals(parentPkg.codePath)) {
4511 pps = mDisabledSysPackages.get(parentPkg.packageName);
4512 }
4513 if (pps != null) {
4514 pw.print(prefix); pw.print(" parentPackage=");
4515 pw.println(pps.realName != null ? pps.realName : pps.name);
4516 }
4517 } else if (ps.pkg.childPackages != null) {
4518 pw.print(prefix); pw.print(" childPackages=[");
4519 final int childCount = ps.pkg.childPackages.size();
4520 for (int i = 0; i < childCount; i++) {
4521 PackageParser.Package childPkg = ps.pkg.childPackages.get(i);
4522 PackageSetting cps = mPackages.get(childPkg.packageName);
4523 if (cps == null || !cps.codePathString.equals(childPkg.codePath)) {
4524 cps = mDisabledSysPackages.get(childPkg.packageName);
4525 }
4526 if (cps != null) {
4527 if (i > 0) {
4528 pw.print(", ");
4529 }
4530 pw.print(cps.realName != null ? cps.realName : cps.name);
4531 }
4532 }
4533 pw.println("]");
4534 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004535 pw.print(prefix); pw.print(" versionName="); pw.println(ps.pkg.mVersionName);
Jeff Sharkeyc4d05fc2014-12-01 16:24:01 -08004536 pw.print(prefix); pw.print(" splits="); dumpSplitNames(pw, ps.pkg); pw.println();
Patrick Baumann420d58a2017-12-19 10:17:21 -08004537 final int apkSigningVersion = ps.pkg.mSigningDetails.signatureSchemeVersion;
4538 pw.print(prefix); pw.print(" apkSigningVersion="); pw.println(apkSigningVersion);
Dianne Hackbornc895be72013-03-11 17:48:43 -07004539 pw.print(prefix); pw.print(" applicationInfo=");
4540 pw.println(ps.pkg.applicationInfo.toString());
4541 pw.print(prefix); pw.print(" flags="); printFlags(pw, ps.pkg.applicationInfo.flags,
4542 FLAG_DUMP_SPEC); pw.println();
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004543 if (ps.pkg.applicationInfo.privateFlags != 0) {
4544 pw.print(prefix); pw.print(" privateFlags="); printFlags(pw,
4545 ps.pkg.applicationInfo.privateFlags, PRIVATE_FLAG_DUMP_SPEC); pw.println();
4546 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004547 pw.print(prefix); pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Dianne Hackbornc895be72013-03-11 17:48:43 -07004548 pw.print(prefix); pw.print(" supportsScreens=[");
4549 boolean first = true;
4550 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
4551 if (!first)
4552 pw.print(", ");
4553 first = false;
4554 pw.print("small");
4555 }
4556 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
4557 if (!first)
4558 pw.print(", ");
4559 first = false;
4560 pw.print("medium");
4561 }
4562 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
4563 if (!first)
4564 pw.print(", ");
4565 first = false;
4566 pw.print("large");
4567 }
4568 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
4569 if (!first)
4570 pw.print(", ");
4571 first = false;
4572 pw.print("xlarge");
4573 }
4574 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
4575 if (!first)
4576 pw.print(", ");
4577 first = false;
4578 pw.print("resizeable");
4579 }
4580 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
4581 if (!first)
4582 pw.print(", ");
4583 first = false;
4584 pw.print("anyDensity");
4585 }
4586 pw.println("]");
4587 if (ps.pkg.libraryNames != null && ps.pkg.libraryNames.size() > 0) {
Svet Ganov67882122016-12-11 16:36:34 -08004588 pw.print(prefix); pw.println(" dynamic libraries:");
4589 for (int i = 0; i<ps.pkg.libraryNames.size(); i++) {
4590 pw.print(prefix); pw.print(" ");
4591 pw.println(ps.pkg.libraryNames.get(i));
Dianne Hackbornc895be72013-03-11 17:48:43 -07004592 }
4593 }
Svet Ganov67882122016-12-11 16:36:34 -08004594 if (ps.pkg.staticSharedLibName != null) {
4595 pw.print(prefix); pw.println(" static library:");
4596 pw.print(prefix); pw.print(" ");
4597 pw.print("name:"); pw.print(ps.pkg.staticSharedLibName);
4598 pw.print(" version:"); pw.println(ps.pkg.staticSharedLibVersion);
4599 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004600 if (ps.pkg.usesLibraries != null && ps.pkg.usesLibraries.size() > 0) {
4601 pw.print(prefix); pw.println(" usesLibraries:");
4602 for (int i=0; i<ps.pkg.usesLibraries.size(); i++) {
4603 pw.print(prefix); pw.print(" "); pw.println(ps.pkg.usesLibraries.get(i));
4604 }
4605 }
Svet Ganov67882122016-12-11 16:36:34 -08004606 if (ps.pkg.usesStaticLibraries != null
4607 && ps.pkg.usesStaticLibraries.size() > 0) {
4608 pw.print(prefix); pw.println(" usesStaticLibraries:");
4609 for (int i=0; i<ps.pkg.usesStaticLibraries.size(); i++) {
4610 pw.print(prefix); pw.print(" ");
4611 pw.print(ps.pkg.usesStaticLibraries.get(i)); pw.print(" version:");
4612 pw.println(ps.pkg.usesStaticLibrariesVersions[i]);
4613 }
4614 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004615 if (ps.pkg.usesOptionalLibraries != null
4616 && ps.pkg.usesOptionalLibraries.size() > 0) {
4617 pw.print(prefix); pw.println(" usesOptionalLibraries:");
4618 for (int i=0; i<ps.pkg.usesOptionalLibraries.size(); i++) {
4619 pw.print(prefix); pw.print(" ");
Svet Ganov67882122016-12-11 16:36:34 -08004620 pw.println(ps.pkg.usesOptionalLibraries.get(i));
Dianne Hackbornc895be72013-03-11 17:48:43 -07004621 }
4622 }
4623 if (ps.pkg.usesLibraryFiles != null
4624 && ps.pkg.usesLibraryFiles.length > 0) {
4625 pw.print(prefix); pw.println(" usesLibraryFiles:");
4626 for (int i=0; i<ps.pkg.usesLibraryFiles.length; i++) {
4627 pw.print(prefix); pw.print(" "); pw.println(ps.pkg.usesLibraryFiles[i]);
4628 }
4629 }
4630 }
4631 pw.print(prefix); pw.print(" timeStamp=");
4632 date.setTime(ps.timeStamp);
4633 pw.println(sdf.format(date));
4634 pw.print(prefix); pw.print(" firstInstallTime=");
4635 date.setTime(ps.firstInstallTime);
4636 pw.println(sdf.format(date));
4637 pw.print(prefix); pw.print(" lastUpdateTime=");
4638 date.setTime(ps.lastUpdateTime);
4639 pw.println(sdf.format(date));
4640 if (ps.installerPackageName != null) {
4641 pw.print(prefix); pw.print(" installerPackageName=");
4642 pw.println(ps.installerPackageName);
4643 }
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07004644 if (ps.volumeUuid != null) {
4645 pw.print(prefix); pw.print(" volumeUuid=");
4646 pw.println(ps.volumeUuid);
4647 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004648 pw.print(prefix); pw.print(" signatures="); pw.println(ps.signatures);
Svetoslavcf959f62015-03-26 20:53:34 -07004649 pw.print(prefix); pw.print(" installPermissionsFixed=");
4650 pw.print(ps.installPermissionsFixed);
Todd Kennedyaf6f1952018-02-13 11:09:50 -08004651 pw.println();
Dianne Hackbornc895be72013-03-11 17:48:43 -07004652 pw.print(prefix); pw.print(" pkgFlags="); printFlags(pw, ps.pkgFlags, FLAG_DUMP_SPEC);
4653 pw.println();
Svetoslavc6d1c342015-02-26 14:44:43 -08004654
Patrick Baumann7438dcb2018-05-08 14:31:45 -07004655 if (ps.pkg != null && ps.pkg.mOverlayTarget != null) {
Adrian Roosc84df772018-01-19 21:20:22 +01004656 pw.print(prefix); pw.print(" overlayTarget="); pw.println(ps.pkg.mOverlayTarget);
4657 pw.print(prefix); pw.print(" overlayCategory="); pw.println(ps.pkg.mOverlayCategory);
4658 }
4659
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004660 if (ps.pkg != null && ps.pkg.permissions != null && ps.pkg.permissions.size() > 0) {
4661 final ArrayList<PackageParser.Permission> perms = ps.pkg.permissions;
4662 pw.print(prefix); pw.println(" declared permissions:");
4663 for (int i=0; i<perms.size(); i++) {
4664 PackageParser.Permission perm = perms.get(i);
4665 if (permissionNames != null
4666 && !permissionNames.contains(perm.info.name)) {
4667 continue;
4668 }
4669 pw.print(prefix); pw.print(" "); pw.print(perm.info.name);
4670 pw.print(": prot=");
4671 pw.print(PermissionInfo.protectionToString(perm.info.protectionLevel));
4672 if ((perm.info.flags&PermissionInfo.FLAG_COSTS_MONEY) != 0) {
4673 pw.print(", COSTS_MONEY");
4674 }
Svet Ganov2a1376d2016-02-22 17:20:35 -08004675 if ((perm.info.flags&PermissionInfo.FLAG_REMOVED) != 0) {
Svet Ganov52153f42015-08-11 08:59:12 -07004676 pw.print(", HIDDEN");
Svet Ganov3e0be742015-08-07 23:06:00 -07004677 }
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004678 if ((perm.info.flags&PermissionInfo.FLAG_INSTALLED) != 0) {
4679 pw.print(", INSTALLED");
4680 }
4681 pw.println();
4682 }
4683 }
4684
Dianne Hackborn9cfba352016-03-24 17:31:28 -07004685 if ((permissionNames != null || dumpAll) && ps.pkg != null
4686 && ps.pkg.requestedPermissions != null
Dianne Hackborn9f5b0a22015-08-13 18:25:20 -07004687 && ps.pkg.requestedPermissions.size() > 0) {
4688 final ArrayList<String> perms = ps.pkg.requestedPermissions;
4689 pw.print(prefix); pw.println(" requested permissions:");
4690 for (int i=0; i<perms.size(); i++) {
4691 String perm = perms.get(i);
4692 if (permissionNames != null
4693 && !permissionNames.contains(perm)) {
4694 continue;
4695 }
4696 pw.print(prefix); pw.print(" "); pw.println(perm);
4697 }
4698 }
4699
4700 if (ps.sharedUser == null || permissionNames != null || dumpAll) {
Svetoslavc6d1c342015-02-26 14:44:43 -08004701 PermissionsState permissionsState = ps.getPermissionsState();
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004702 dumpInstallPermissionsLPr(pw, prefix + " ", permissionNames, permissionsState);
Svetoslavc6d1c342015-02-26 14:44:43 -08004703 }
4704
Makoto Onuki0a068582018-06-13 10:57:34 -07004705 if (dumpAllComponents) {
4706 dumpComponents(pw, prefix + " ", ps);
4707 }
4708
Dianne Hackbornc895be72013-03-11 17:48:43 -07004709 for (UserInfo user : users) {
4710 pw.print(prefix); pw.print(" User "); pw.print(user.id); pw.print(": ");
Jeff Sharkey42884192016-04-09 16:12:01 -06004711 pw.print("ceDataInode=");
4712 pw.print(ps.getCeDataInode(user.id));
Dianne Hackbornc895be72013-03-11 17:48:43 -07004713 pw.print(" installed=");
4714 pw.print(ps.getInstalled(user.id));
Amith Yamasanie5bcff62014-07-19 15:44:09 -07004715 pw.print(" hidden=");
4716 pw.print(ps.getHidden(user.id));
Andrei Stingaceanu1e283912015-11-26 15:26:28 +00004717 pw.print(" suspended=");
4718 pw.print(ps.getSuspended(user.id));
Suprabh Shukla021b57a2018-03-08 18:21:50 -08004719 if (ps.getSuspended(user.id)) {
Suprabh Shukla3c3af142018-03-30 00:28:37 -07004720 final PackageUserState pus = ps.readUserState(user.id);
Suprabh Shukla021b57a2018-03-08 18:21:50 -08004721 pw.print(" suspendingPackage=");
Suprabh Shukla3c3af142018-03-30 00:28:37 -07004722 pw.print(pus.suspendingPackage);
Suprabh Shukla389cb6f2018-10-01 18:20:39 -07004723 pw.print(" dialogInfo=");
4724 pw.print(pus.dialogInfo);
Suprabh Shukla021b57a2018-03-08 18:21:50 -08004725 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004726 pw.print(" stopped=");
4727 pw.print(ps.getStopped(user.id));
4728 pw.print(" notLaunched=");
4729 pw.print(ps.getNotLaunched(user.id));
4730 pw.print(" enabled=");
Fyodor Kupolov09546ff2017-04-03 17:45:50 -07004731 pw.print(ps.getEnabled(user.id));
Todd Kennedybe0b8892017-02-15 14:13:52 -08004732 pw.print(" instant=");
Dianne Hackbornc50a1082017-08-15 14:10:39 -07004733 pw.print(ps.getInstantApp(user.id));
Todd Kennedy5eb5a7d2017-08-01 07:42:47 -07004734 pw.print(" virtual=");
4735 pw.println(ps.getVirtulalPreload(user.id));
Todd Kennedyb2749472017-06-13 08:24:32 -07004736
4737 String[] overlayPaths = ps.getOverlayPaths(user.id);
4738 if (overlayPaths != null && overlayPaths.length > 0) {
Todd Kennedy560830c2017-06-16 13:55:13 -07004739 pw.print(prefix); pw.println(" overlay paths:");
Todd Kennedyb2749472017-06-13 08:24:32 -07004740 for (String path : overlayPaths) {
Todd Kennedy560830c2017-06-16 13:55:13 -07004741 pw.print(prefix); pw.print(" "); pw.println(path);
Todd Kennedyb2749472017-06-13 08:24:32 -07004742 }
4743 }
4744
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07004745 String lastDisabledAppCaller = ps.getLastDisabledAppCaller(user.id);
4746 if (lastDisabledAppCaller != null) {
4747 pw.print(prefix); pw.print(" lastDisabledCaller: ");
4748 pw.println(lastDisabledAppCaller);
4749 }
Svetoslavc6d1c342015-02-26 14:44:43 -08004750
4751 if (ps.sharedUser == null) {
4752 PermissionsState permissionsState = ps.getPermissionsState();
4753 dumpGidsLPr(pw, prefix + " ", permissionsState.computeGids(user.id));
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004754 dumpRuntimePermissionsLPr(pw, prefix + " ", permissionNames, permissionsState
Dianne Hackborn9f5b0a22015-08-13 18:25:20 -07004755 .getRuntimePermissionStates(user.id), dumpAll);
Svetoslavc6d1c342015-02-26 14:44:43 -08004756 }
4757
Ben Gruver1ab3d6e2017-12-07 13:45:08 -08004758 String harmfulAppWarning = ps.getHarmfulAppWarning(user.id);
4759 if (harmfulAppWarning != null) {
4760 pw.print(prefix); pw.print(" harmfulAppWarning: ");
4761 pw.println(harmfulAppWarning);
4762 }
4763
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004764 if (permissionNames == null) {
4765 ArraySet<String> cmp = ps.getDisabledComponents(user.id);
4766 if (cmp != null && cmp.size() > 0) {
4767 pw.print(prefix); pw.println(" disabledComponents:");
4768 for (String s : cmp) {
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004769 pw.print(prefix); pw.print(" "); pw.println(s);
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004770 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004771 }
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004772 cmp = ps.getEnabledComponents(user.id);
4773 if (cmp != null && cmp.size() > 0) {
4774 pw.print(prefix); pw.println(" enabledComponents:");
4775 for (String s : cmp) {
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004776 pw.print(prefix); pw.print(" "); pw.println(s);
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004777 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004778 }
4779 }
4780 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004781 }
4782
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004783 void dumpPackagesLPr(PrintWriter pw, String packageName, ArraySet<String> permissionNames,
4784 DumpState dumpState, boolean checkin) {
Kenny Root447106f2011-03-23 11:00:15 -07004785 final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
4786 final Date date = new Date();
4787 boolean printedSomething = false;
Makoto Onuki0a068582018-06-13 10:57:34 -07004788 final boolean dumpAllComponents =
4789 dumpState.isOptionEnabled(DumpState.OPTION_DUMP_ALL_COMPONENTS);
Todd Kennedy13715d52016-08-01 13:38:57 -07004790 List<UserInfo> users = getAllUsers(UserManagerService.getInstance());
Kenny Root447106f2011-03-23 11:00:15 -07004791 for (final PackageSetting ps : mPackages.values()) {
4792 if (packageName != null && !packageName.equals(ps.realName)
4793 && !packageName.equals(ps.name)) {
4794 continue;
4795 }
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004796 if (permissionNames != null
4797 && !ps.getPermissionsState().hasRequestedPermission(permissionNames)) {
4798 continue;
4799 }
Kenny Root447106f2011-03-23 11:00:15 -07004800
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004801 if (!checkin && packageName != null) {
Kenny Root447106f2011-03-23 11:00:15 -07004802 dumpState.setSharedUser(ps.sharedUser);
4803 }
4804
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004805 if (!checkin && !printedSomething) {
Kenny Root447106f2011-03-23 11:00:15 -07004806 if (dumpState.onTitlePrinted())
Dianne Hackborncbfd23e2013-06-11 14:26:53 -07004807 pw.println();
Kenny Root447106f2011-03-23 11:00:15 -07004808 pw.println("Packages:");
4809 printedSomething = true;
4810 }
Dianne Hackborn9f5b0a22015-08-13 18:25:20 -07004811 dumpPackageLPr(pw, " ", checkin ? "pkg" : null, permissionNames, ps, sdf, date, users,
Makoto Onuki0a068582018-06-13 10:57:34 -07004812 packageName != null, dumpAllComponents);
Kenny Root447106f2011-03-23 11:00:15 -07004813 }
4814
4815 printedSomething = false;
Dianne Hackborn9f5b0a22015-08-13 18:25:20 -07004816 if (mRenamedPackages.size() > 0 && permissionNames == null) {
Andy McFadden2f362292012-01-20 14:43:38 -08004817 for (final Map.Entry<String, String> e : mRenamedPackages.entrySet()) {
Kenny Root447106f2011-03-23 11:00:15 -07004818 if (packageName != null && !packageName.equals(e.getKey())
4819 && !packageName.equals(e.getValue())) {
4820 continue;
4821 }
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004822 if (!checkin) {
4823 if (!printedSomething) {
4824 if (dumpState.onTitlePrinted())
4825 pw.println();
4826 pw.println("Renamed packages:");
4827 printedSomething = true;
4828 }
4829 pw.print(" ");
4830 } else {
4831 pw.print("ren,");
Kenny Root447106f2011-03-23 11:00:15 -07004832 }
Kenny Root447106f2011-03-23 11:00:15 -07004833 pw.print(e.getKey());
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004834 pw.print(checkin ? " -> " : ",");
Kenny Root447106f2011-03-23 11:00:15 -07004835 pw.println(e.getValue());
4836 }
4837 }
4838
4839 printedSomething = false;
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004840 if (mDisabledSysPackages.size() > 0 && permissionNames == null) {
Kenny Root447106f2011-03-23 11:00:15 -07004841 for (final PackageSetting ps : mDisabledSysPackages.values()) {
4842 if (packageName != null && !packageName.equals(ps.realName)
4843 && !packageName.equals(ps.name)) {
4844 continue;
4845 }
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004846 if (!checkin && !printedSomething) {
Kenny Root447106f2011-03-23 11:00:15 -07004847 if (dumpState.onTitlePrinted())
Dianne Hackborncbfd23e2013-06-11 14:26:53 -07004848 pw.println();
Kenny Root447106f2011-03-23 11:00:15 -07004849 pw.println("Hidden system packages:");
4850 printedSomething = true;
4851 }
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004852 dumpPackageLPr(pw, " ", checkin ? "dis" : null, permissionNames, ps, sdf, date,
Makoto Onuki0a068582018-06-13 10:57:34 -07004853 users, packageName != null, dumpAllComponents);
Kenny Root447106f2011-03-23 11:00:15 -07004854 }
4855 }
4856 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07004857
Netta P426cbef2017-02-10 14:38:39 -08004858 void dumpPackagesProto(ProtoOutputStream proto) {
4859 List<UserInfo> users = getAllUsers(UserManagerService.getInstance());
4860
4861 final int count = mPackages.size();
4862 for (int i = 0; i < count; i++) {
4863 final PackageSetting ps = mPackages.valueAt(i);
4864 ps.writeToProto(proto, PackageServiceDumpProto.PACKAGES, users);
4865 }
4866 }
4867
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004868 void dumpPermissionsLPr(PrintWriter pw, String packageName, ArraySet<String> permissionNames,
4869 DumpState dumpState) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07004870 mPermissions.dumpPermissions(pw, packageName, permissionNames,
4871 (mReadExternalStorageEnforced == Boolean.TRUE), dumpState);
Kenny Root447106f2011-03-23 11:00:15 -07004872 }
Jeff Sharkey1c27576a2012-04-11 19:07:08 -07004873
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004874 void dumpSharedUsersLPr(PrintWriter pw, String packageName, ArraySet<String> permissionNames,
4875 DumpState dumpState, boolean checkin) {
Kenny Root447106f2011-03-23 11:00:15 -07004876 boolean printedSomething = false;
4877 for (SharedUserSetting su : mSharedUsers.values()) {
4878 if (packageName != null && su != dumpState.getSharedUser()) {
4879 continue;
4880 }
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004881 if (permissionNames != null
4882 && !su.getPermissionsState().hasRequestedPermission(permissionNames)) {
4883 continue;
4884 }
Dianne Hackbornd052a942014-11-21 15:23:13 -08004885 if (!checkin) {
4886 if (!printedSomething) {
4887 if (dumpState.onTitlePrinted())
4888 pw.println();
4889 pw.println("Shared users:");
4890 printedSomething = true;
4891 }
4892 pw.print(" SharedUser [");
4893 pw.print(su.name);
4894 pw.print("] (");
4895 pw.print(Integer.toHexString(System.identityHashCode(su)));
4896 pw.println("):");
Svetoslavc6d1c342015-02-26 14:44:43 -08004897
4898 String prefix = " ";
4899 pw.print(prefix); pw.print("userId="); pw.println(su.userId);
4900
4901 PermissionsState permissionsState = su.getPermissionsState();
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004902 dumpInstallPermissionsLPr(pw, prefix, permissionNames, permissionsState);
Svetoslavc6d1c342015-02-26 14:44:43 -08004903
4904 for (int userId : UserManagerService.getInstance().getUserIds()) {
4905 final int[] gids = permissionsState.computeGids(userId);
Svet Ganov8c7f7002015-05-07 10:48:44 -07004906 List<PermissionState> permissions = permissionsState
4907 .getRuntimePermissionStates(userId);
Svetoslavc6d1c342015-02-26 14:44:43 -08004908 if (!ArrayUtils.isEmpty(gids) || !permissions.isEmpty()) {
4909 pw.print(prefix); pw.print("User "); pw.print(userId); pw.println(": ");
4910 dumpGidsLPr(pw, prefix + " ", gids);
Dianne Hackborn9f5b0a22015-08-13 18:25:20 -07004911 dumpRuntimePermissionsLPr(pw, prefix + " ", permissionNames, permissions,
4912 packageName != null);
Svetoslavc6d1c342015-02-26 14:44:43 -08004913 }
Dianne Hackbornd052a942014-11-21 15:23:13 -08004914 }
4915 } else {
4916 pw.print("suid,"); pw.print(su.userId); pw.print(","); pw.println(su.name);
Kenny Root447106f2011-03-23 11:00:15 -07004917 }
4918 }
4919 }
4920
Netta P426cbef2017-02-10 14:38:39 -08004921 void dumpSharedUsersProto(ProtoOutputStream proto) {
4922 final int count = mSharedUsers.size();
4923 for (int i = 0; i < count; i++) {
Yi Jind6759d42017-10-12 15:08:49 -07004924 mSharedUsers.valueAt(i).writeToProto(proto, PackageServiceDumpProto.SHARED_USERS);
Netta P426cbef2017-02-10 14:38:39 -08004925 }
4926 }
4927
Kenny Root447106f2011-03-23 11:00:15 -07004928 void dumpReadMessagesLPr(PrintWriter pw, DumpState dumpState) {
4929 pw.println("Settings parse messages:");
4930 pw.print(mReadMessages.toString());
4931 }
Jeff Sharkeyc4d05fc2014-12-01 16:24:01 -08004932
4933 private static void dumpSplitNames(PrintWriter pw, PackageParser.Package pkg) {
4934 if (pkg == null) {
4935 pw.print("unknown");
4936 } else {
4937 // [base:10, config.mdpi, config.xhdpi:12]
4938 pw.print("[");
4939 pw.print("base");
4940 if (pkg.baseRevisionCode != 0) {
4941 pw.print(":"); pw.print(pkg.baseRevisionCode);
4942 }
4943 if (pkg.splitNames != null) {
4944 for (int i = 0; i < pkg.splitNames.length; i++) {
4945 pw.print(", ");
4946 pw.print(pkg.splitNames[i]);
4947 if (pkg.splitRevisionCodes[i] != 0) {
4948 pw.print(":"); pw.print(pkg.splitRevisionCodes[i]);
4949 }
4950 }
4951 }
4952 pw.print("]");
4953 }
4954 }
Svetoslavc6d1c342015-02-26 14:44:43 -08004955
4956 void dumpGidsLPr(PrintWriter pw, String prefix, int[] gids) {
4957 if (!ArrayUtils.isEmpty(gids)) {
Fabrice Di Meglio62271722015-04-10 17:24:02 -07004958 pw.print(prefix);
4959 pw.print("gids="); pw.println(
Svetoslavc6d1c342015-02-26 14:44:43 -08004960 PackageManagerService.arrayToString(gids));
4961 }
4962 }
4963
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004964 void dumpRuntimePermissionsLPr(PrintWriter pw, String prefix, ArraySet<String> permissionNames,
Dianne Hackborn9f5b0a22015-08-13 18:25:20 -07004965 List<PermissionState> permissionStates, boolean dumpAll) {
4966 if (!permissionStates.isEmpty() || dumpAll) {
Svetoslavc6d1c342015-02-26 14:44:43 -08004967 pw.print(prefix); pw.println("runtime permissions:");
Svet Ganov8c7f7002015-05-07 10:48:44 -07004968 for (PermissionState permissionState : permissionStates) {
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004969 if (permissionNames != null
4970 && !permissionNames.contains(permissionState.getName())) {
4971 continue;
4972 }
Svet Ganov8c7f7002015-05-07 10:48:44 -07004973 pw.print(prefix); pw.print(" "); pw.print(permissionState.getName());
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004974 pw.print(": granted="); pw.print(permissionState.isGranted());
4975 pw.println(permissionFlagsToString(", flags=",
4976 permissionState.getFlags()));
Svetoslavc6d1c342015-02-26 14:44:43 -08004977 }
4978 }
4979 }
4980
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004981 private static String permissionFlagsToString(String prefix, int flags) {
4982 StringBuilder flagsString = null;
Svet Ganov77ab6a82015-07-03 12:03:02 -07004983 while (flags != 0) {
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004984 if (flagsString == null) {
4985 flagsString = new StringBuilder();
4986 flagsString.append(prefix);
4987 flagsString.append("[ ");
4988 }
Svet Ganov77ab6a82015-07-03 12:03:02 -07004989 final int flag = 1 << Integer.numberOfTrailingZeros(flags);
4990 flags &= ~flag;
4991 flagsString.append(PackageManager.permissionFlagToString(flag));
4992 flagsString.append(' ');
4993 }
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004994 if (flagsString != null) {
4995 flagsString.append(']');
4996 return flagsString.toString();
4997 } else {
4998 return "";
4999 }
Svet Ganov77ab6a82015-07-03 12:03:02 -07005000 }
5001
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07005002 void dumpInstallPermissionsLPr(PrintWriter pw, String prefix, ArraySet<String> permissionNames,
Svetoslavc6d1c342015-02-26 14:44:43 -08005003 PermissionsState permissionsState) {
Svet Ganov8c7f7002015-05-07 10:48:44 -07005004 List<PermissionState> permissionStates = permissionsState.getInstallPermissionStates();
5005 if (!permissionStates.isEmpty()) {
Svetoslavc6d1c342015-02-26 14:44:43 -08005006 pw.print(prefix); pw.println("install permissions:");
Svet Ganov8c7f7002015-05-07 10:48:44 -07005007 for (PermissionState permissionState : permissionStates) {
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07005008 if (permissionNames != null
5009 && !permissionNames.contains(permissionState.getName())) {
5010 continue;
5011 }
Svet Ganov8c7f7002015-05-07 10:48:44 -07005012 pw.print(prefix); pw.print(" "); pw.print(permissionState.getName());
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07005013 pw.print(": granted="); pw.print(permissionState.isGranted());
5014 pw.println(permissionFlagsToString(", flags=",
Svet Ganov8c7f7002015-05-07 10:48:44 -07005015 permissionState.getFlags()));
Svetoslavc6d1c342015-02-26 14:44:43 -08005016 }
5017 }
5018 }
5019
Makoto Onuki0a068582018-06-13 10:57:34 -07005020 void dumpComponents(PrintWriter pw, String prefix, PackageSetting ps) {
5021 dumpComponents(pw, prefix, ps, "activities:", ps.pkg.activities);
5022 dumpComponents(pw, prefix, ps, "services:", ps.pkg.services);
5023 dumpComponents(pw, prefix, ps, "receivers:", ps.pkg.receivers);
5024 dumpComponents(pw, prefix, ps, "providers:", ps.pkg.providers);
5025 dumpComponents(pw, prefix, ps, "instrumentations:", ps.pkg.instrumentation);
5026 }
5027
5028 void dumpComponents(PrintWriter pw, String prefix, PackageSetting ps,
5029 String label, List<? extends PackageParser.Component<?>> list) {
5030 final int size = CollectionUtils.size(list);
5031 if (size == 0) {
5032 return;
5033 }
5034 pw.print(prefix);pw.println(label);
5035 for (int i = 0; i < size; i++) {
5036 final PackageParser.Component<?> component = list.get(i);
5037 pw.print(prefix);pw.print(" ");
5038 pw.println(component.getComponentName().flattenToShortString());
5039 }
5040 }
5041
Svetoslavc6d1c342015-02-26 14:44:43 -08005042 public void writeRuntimePermissionsForUserLPr(int userId, boolean sync) {
5043 if (sync) {
5044 mRuntimePermissionsPersistence.writePermissionsForUserSyncLPr(userId);
5045 } else {
5046 mRuntimePermissionsPersistence.writePermissionsForUserAsyncLPr(userId);
5047 }
5048 }
5049
5050 private final class RuntimePermissionPersistence {
5051 private static final long WRITE_PERMISSIONS_DELAY_MILLIS = 200;
Svetoslavc6d1c342015-02-26 14:44:43 -08005052 private static final long MAX_WRITE_PERMISSIONS_DELAY_MILLIS = 2000;
5053
5054 private final Handler mHandler = new MyHandler();
5055
Todd Kennedy91a39d12017-09-27 12:37:04 -07005056 private final Object mPersistenceLock;
Svetoslavc6d1c342015-02-26 14:44:43 -08005057
5058 @GuardedBy("mLock")
Svet Ganovba3ba812015-06-26 10:54:06 -07005059 private final SparseBooleanArray mWriteScheduled = new SparseBooleanArray();
Svetoslavc6d1c342015-02-26 14:44:43 -08005060
5061 @GuardedBy("mLock")
Svet Ganovba3ba812015-06-26 10:54:06 -07005062 // The mapping keys are user ids.
5063 private final SparseLongArray mLastNotWrittenMutationTimesMillis = new SparseLongArray();
5064
5065 @GuardedBy("mLock")
5066 // The mapping keys are user ids.
5067 private final SparseArray<String> mFingerprints = new SparseArray<>();
5068
5069 @GuardedBy("mLock")
5070 // The mapping keys are user ids.
5071 private final SparseBooleanArray mDefaultPermissionsGranted = new SparseBooleanArray();
Svetoslavc6d1c342015-02-26 14:44:43 -08005072
Todd Kennedy91a39d12017-09-27 12:37:04 -07005073 public RuntimePermissionPersistence(Object persistenceLock) {
5074 mPersistenceLock = persistenceLock;
Svetoslavc6d1c342015-02-26 14:44:43 -08005075 }
5076
Andreas Gampe2e8c7672018-07-20 13:01:08 -07005077 @GuardedBy("Settings.this.mLock")
Svet Ganovba3ba812015-06-26 10:54:06 -07005078 public boolean areDefaultRuntimPermissionsGrantedLPr(int userId) {
5079 return mDefaultPermissionsGranted.get(userId);
5080 }
5081
Andreas Gampe2e8c7672018-07-20 13:01:08 -07005082 @GuardedBy("Settings.this.mLock")
Svet Ganovba3ba812015-06-26 10:54:06 -07005083 public void onDefaultRuntimePermissionsGrantedLPr(int userId) {
5084 mFingerprints.put(userId, Build.FINGERPRINT);
5085 writePermissionsForUserAsyncLPr(userId);
5086 }
5087
Svetoslavc6d1c342015-02-26 14:44:43 -08005088 public void writePermissionsForUserSyncLPr(int userId) {
5089 mHandler.removeMessages(userId);
5090 writePermissionsSync(userId);
5091 }
5092
Andreas Gampe2e8c7672018-07-20 13:01:08 -07005093 @GuardedBy("Settings.this.mLock")
Svetoslavc6d1c342015-02-26 14:44:43 -08005094 public void writePermissionsForUserAsyncLPr(int userId) {
5095 final long currentTimeMillis = SystemClock.uptimeMillis();
5096
5097 if (mWriteScheduled.get(userId)) {
5098 mHandler.removeMessages(userId);
5099
5100 // If enough time passed, write without holding off anymore.
5101 final long lastNotWrittenMutationTimeMillis = mLastNotWrittenMutationTimesMillis
5102 .get(userId);
5103 final long timeSinceLastNotWrittenMutationMillis = currentTimeMillis
5104 - lastNotWrittenMutationTimeMillis;
5105 if (timeSinceLastNotWrittenMutationMillis >= MAX_WRITE_PERMISSIONS_DELAY_MILLIS) {
5106 mHandler.obtainMessage(userId).sendToTarget();
5107 return;
5108 }
5109
5110 // Hold off a bit more as settings are frequently changing.
5111 final long maxDelayMillis = Math.max(lastNotWrittenMutationTimeMillis
5112 + MAX_WRITE_PERMISSIONS_DELAY_MILLIS - currentTimeMillis, 0);
5113 final long writeDelayMillis = Math.min(WRITE_PERMISSIONS_DELAY_MILLIS,
5114 maxDelayMillis);
5115
5116 Message message = mHandler.obtainMessage(userId);
5117 mHandler.sendMessageDelayed(message, writeDelayMillis);
5118 } else {
5119 mLastNotWrittenMutationTimesMillis.put(userId, currentTimeMillis);
5120 Message message = mHandler.obtainMessage(userId);
5121 mHandler.sendMessageDelayed(message, WRITE_PERMISSIONS_DELAY_MILLIS);
5122 mWriteScheduled.put(userId, true);
5123 }
5124 }
5125
5126 private void writePermissionsSync(int userId) {
Dianne Hackborne17b4452018-01-10 13:15:40 -08005127 AtomicFile destination = new AtomicFile(getUserRuntimePermissionsFile(userId),
5128 "package-perms-" + userId);
Svetoslavc6d1c342015-02-26 14:44:43 -08005129
Svet Ganov8c7f7002015-05-07 10:48:44 -07005130 ArrayMap<String, List<PermissionState>> permissionsForPackage = new ArrayMap<>();
5131 ArrayMap<String, List<PermissionState>> permissionsForSharedUser = new ArrayMap<>();
Svetoslavc6d1c342015-02-26 14:44:43 -08005132
Todd Kennedy91a39d12017-09-27 12:37:04 -07005133 synchronized (mPersistenceLock) {
Svetoslavc6d1c342015-02-26 14:44:43 -08005134 mWriteScheduled.delete(userId);
5135
5136 final int packageCount = mPackages.size();
5137 for (int i = 0; i < packageCount; i++) {
5138 String packageName = mPackages.keyAt(i);
5139 PackageSetting packageSetting = mPackages.valueAt(i);
5140 if (packageSetting.sharedUser == null) {
5141 PermissionsState permissionsState = packageSetting.getPermissionsState();
Svet Ganov8c7f7002015-05-07 10:48:44 -07005142 List<PermissionState> permissionsStates = permissionsState
5143 .getRuntimePermissionStates(userId);
5144 if (!permissionsStates.isEmpty()) {
5145 permissionsForPackage.put(packageName, permissionsStates);
Svetoslavc6d1c342015-02-26 14:44:43 -08005146 }
5147 }
5148 }
5149
5150 final int sharedUserCount = mSharedUsers.size();
5151 for (int i = 0; i < sharedUserCount; i++) {
5152 String sharedUserName = mSharedUsers.keyAt(i);
5153 SharedUserSetting sharedUser = mSharedUsers.valueAt(i);
5154 PermissionsState permissionsState = sharedUser.getPermissionsState();
Svet Ganov8c7f7002015-05-07 10:48:44 -07005155 List<PermissionState> permissionsStates = permissionsState
5156 .getRuntimePermissionStates(userId);
5157 if (!permissionsStates.isEmpty()) {
5158 permissionsForSharedUser.put(sharedUserName, permissionsStates);
Svetoslavc6d1c342015-02-26 14:44:43 -08005159 }
5160 }
5161 }
5162
5163 FileOutputStream out = null;
5164 try {
5165 out = destination.startWrite();
5166
5167 XmlSerializer serializer = Xml.newSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01005168 serializer.setOutput(out, StandardCharsets.UTF_8.name());
Svetoslavc6d1c342015-02-26 14:44:43 -08005169 serializer.setFeature(
5170 "http://xmlpull.org/v1/doc/features.html#indent-output", true);
5171 serializer.startDocument(null, true);
Christopher Tatee9fd1fa2015-09-15 16:43:07 -07005172
Svetoslavc6d1c342015-02-26 14:44:43 -08005173 serializer.startTag(null, TAG_RUNTIME_PERMISSIONS);
5174
Svet Ganovba3ba812015-06-26 10:54:06 -07005175 String fingerprint = mFingerprints.get(userId);
Svetoslavcdfd2302015-06-25 19:07:31 -07005176 if (fingerprint != null) {
5177 serializer.attribute(null, ATTR_FINGERPRINT, fingerprint);
5178 }
Svet Ganovba3ba812015-06-26 10:54:06 -07005179
Svetoslavc6d1c342015-02-26 14:44:43 -08005180 final int packageCount = permissionsForPackage.size();
5181 for (int i = 0; i < packageCount; i++) {
5182 String packageName = permissionsForPackage.keyAt(i);
Svet Ganov8c7f7002015-05-07 10:48:44 -07005183 List<PermissionState> permissionStates = permissionsForPackage.valueAt(i);
Svetoslavc6d1c342015-02-26 14:44:43 -08005184 serializer.startTag(null, TAG_PACKAGE);
5185 serializer.attribute(null, ATTR_NAME, packageName);
Svet Ganov8c7f7002015-05-07 10:48:44 -07005186 writePermissions(serializer, permissionStates);
Svetoslavc6d1c342015-02-26 14:44:43 -08005187 serializer.endTag(null, TAG_PACKAGE);
5188 }
5189
5190 final int sharedUserCount = permissionsForSharedUser.size();
5191 for (int i = 0; i < sharedUserCount; i++) {
5192 String packageName = permissionsForSharedUser.keyAt(i);
Svet Ganov8c7f7002015-05-07 10:48:44 -07005193 List<PermissionState> permissionStates = permissionsForSharedUser.valueAt(i);
Svetoslavc6d1c342015-02-26 14:44:43 -08005194 serializer.startTag(null, TAG_SHARED_USER);
5195 serializer.attribute(null, ATTR_NAME, packageName);
Svet Ganov8c7f7002015-05-07 10:48:44 -07005196 writePermissions(serializer, permissionStates);
Svetoslavc6d1c342015-02-26 14:44:43 -08005197 serializer.endTag(null, TAG_SHARED_USER);
5198 }
5199
5200 serializer.endTag(null, TAG_RUNTIME_PERMISSIONS);
Christopher Tatee9fd1fa2015-09-15 16:43:07 -07005201
Svetoslavc6d1c342015-02-26 14:44:43 -08005202 serializer.endDocument();
5203 destination.finishWrite(out);
Svet Ganovba0821e2015-04-22 13:34:31 -07005204
Svet Ganovba3ba812015-06-26 10:54:06 -07005205 if (Build.FINGERPRINT.equals(fingerprint)) {
5206 mDefaultPermissionsGranted.put(userId, true);
5207 }
5208 // Any error while writing is fatal.
Svet Ganovba0821e2015-04-22 13:34:31 -07005209 } catch (Throwable t) {
Svetoslavc6d1c342015-02-26 14:44:43 -08005210 Slog.wtf(PackageManagerService.TAG,
Svet Ganovba0821e2015-04-22 13:34:31 -07005211 "Failed to write settings, restoring backup", t);
Svetoslavc6d1c342015-02-26 14:44:43 -08005212 destination.failWrite(out);
5213 } finally {
5214 IoUtils.closeQuietly(out);
5215 }
5216 }
5217
Andreas Gampe2e8c7672018-07-20 13:01:08 -07005218 @GuardedBy("Settings.this.mLock")
Fyodor Kupolov69542592016-05-23 14:22:38 -07005219 private void onUserRemovedLPw(int userId) {
Svetoslavc6d1c342015-02-26 14:44:43 -08005220 // Make sure we do not
5221 mHandler.removeMessages(userId);
5222
5223 for (SettingBase sb : mPackages.values()) {
Svet Ganov8c7f7002015-05-07 10:48:44 -07005224 revokeRuntimePermissionsAndClearFlags(sb, userId);
Svetoslavc6d1c342015-02-26 14:44:43 -08005225 }
5226
5227 for (SettingBase sb : mSharedUsers.values()) {
Svet Ganov8c7f7002015-05-07 10:48:44 -07005228 revokeRuntimePermissionsAndClearFlags(sb, userId);
Svetoslavc6d1c342015-02-26 14:44:43 -08005229 }
Fyodor Kupolov69542592016-05-23 14:22:38 -07005230
5231 mDefaultPermissionsGranted.delete(userId);
5232 mFingerprints.remove(userId);
Svetoslavc6d1c342015-02-26 14:44:43 -08005233 }
5234
Svet Ganov8c7f7002015-05-07 10:48:44 -07005235 private void revokeRuntimePermissionsAndClearFlags(SettingBase sb, int userId) {
Svetoslavc6d1c342015-02-26 14:44:43 -08005236 PermissionsState permissionsState = sb.getPermissionsState();
Svet Ganov8c7f7002015-05-07 10:48:44 -07005237 for (PermissionState permissionState
5238 : permissionsState.getRuntimePermissionStates(userId)) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07005239 BasePermission bp = mPermissions.getPermission(permissionState.getName());
Svetoslavc6d1c342015-02-26 14:44:43 -08005240 if (bp != null) {
5241 permissionsState.revokeRuntimePermission(bp, userId);
Svet Ganov8c7f7002015-05-07 10:48:44 -07005242 permissionsState.updatePermissionFlags(bp, userId,
Philip P. Moltmann76597692019-03-02 13:18:41 -08005243 PackageManager.MASK_PERMISSION_FLAGS_ALL, 0);
Svetoslavc6d1c342015-02-26 14:44:43 -08005244 }
5245 }
5246 }
5247
Svet Ganovadc1cf42015-06-15 16:36:24 -07005248 public void deleteUserRuntimePermissionsFile(int userId) {
5249 getUserRuntimePermissionsFile(userId).delete();
5250 }
5251
Andreas Gampe2e8c7672018-07-20 13:01:08 -07005252 @GuardedBy("Settings.this.mLock")
Svetoslavc6d1c342015-02-26 14:44:43 -08005253 public void readStateForUserSyncLPr(int userId) {
5254 File permissionsFile = getUserRuntimePermissionsFile(userId);
5255 if (!permissionsFile.exists()) {
5256 return;
5257 }
5258
5259 FileInputStream in;
5260 try {
Svetoslav3dcdd372015-05-29 13:00:32 -07005261 in = new AtomicFile(permissionsFile).openRead();
Svetoslavc6d1c342015-02-26 14:44:43 -08005262 } catch (FileNotFoundException fnfe) {
5263 Slog.i(PackageManagerService.TAG, "No permissions state");
5264 return;
5265 }
5266
5267 try {
5268 XmlPullParser parser = Xml.newPullParser();
5269 parser.setInput(in, null);
5270 parseRuntimePermissionsLPr(parser, userId);
Svet Ganovba0821e2015-04-22 13:34:31 -07005271
Svet Ganove723e542015-04-23 11:58:26 -07005272 } catch (XmlPullParserException | IOException e) {
Svetoslavc6d1c342015-02-26 14:44:43 -08005273 throw new IllegalStateException("Failed parsing permissions file: "
Svet Ganove723e542015-04-23 11:58:26 -07005274 + permissionsFile , e);
Svetoslavc6d1c342015-02-26 14:44:43 -08005275 } finally {
5276 IoUtils.closeQuietly(in);
5277 }
5278 }
5279
Christopher Tatee9fd1fa2015-09-15 16:43:07 -07005280 // Private internals
5281
Andreas Gampe2e8c7672018-07-20 13:01:08 -07005282 @GuardedBy("Settings.this.mLock")
Svetoslavc6d1c342015-02-26 14:44:43 -08005283 private void parseRuntimePermissionsLPr(XmlPullParser parser, int userId)
5284 throws IOException, XmlPullParserException {
Svet Ganov12a692a2015-03-28 19:34:15 -07005285 final int outerDepth = parser.getDepth();
5286 int type;
5287 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
5288 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
5289 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
5290 continue;
5291 }
Svetoslavc6d1c342015-02-26 14:44:43 -08005292
Svet Ganov12a692a2015-03-28 19:34:15 -07005293 switch (parser.getName()) {
Svet Ganovba3ba812015-06-26 10:54:06 -07005294 case TAG_RUNTIME_PERMISSIONS: {
5295 String fingerprint = parser.getAttributeValue(null, ATTR_FINGERPRINT);
5296 mFingerprints.put(userId, fingerprint);
5297 final boolean defaultsGranted = Build.FINGERPRINT.equals(fingerprint);
5298 mDefaultPermissionsGranted.put(userId, defaultsGranted);
5299 } break;
5300
Svet Ganov12a692a2015-03-28 19:34:15 -07005301 case TAG_PACKAGE: {
5302 String name = parser.getAttributeValue(null, ATTR_NAME);
5303 PackageSetting ps = mPackages.get(name);
5304 if (ps == null) {
5305 Slog.w(PackageManagerService.TAG, "Unknown package:" + name);
5306 XmlUtils.skipCurrentTag(parser);
5307 continue;
5308 }
5309 parsePermissionsLPr(parser, ps.getPermissionsState(), userId);
5310 } break;
Svetoslavc6d1c342015-02-26 14:44:43 -08005311
Svet Ganov12a692a2015-03-28 19:34:15 -07005312 case TAG_SHARED_USER: {
5313 String name = parser.getAttributeValue(null, ATTR_NAME);
5314 SharedUserSetting sus = mSharedUsers.get(name);
5315 if (sus == null) {
5316 Slog.w(PackageManagerService.TAG, "Unknown shared user:" + name);
5317 XmlUtils.skipCurrentTag(parser);
5318 continue;
5319 }
5320 parsePermissionsLPr(parser, sus.getPermissionsState(), userId);
5321 } break;
Svetoslavc6d1c342015-02-26 14:44:43 -08005322 }
5323 }
Svetoslavc6d1c342015-02-26 14:44:43 -08005324 }
5325
Svet Ganov12a692a2015-03-28 19:34:15 -07005326 private void parsePermissionsLPr(XmlPullParser parser, PermissionsState permissionsState,
Svetoslavc6d1c342015-02-26 14:44:43 -08005327 int userId) throws IOException, XmlPullParserException {
Svet Ganov12a692a2015-03-28 19:34:15 -07005328 final int outerDepth = parser.getDepth();
5329 int type;
5330 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
5331 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
5332 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
5333 continue;
Svetoslavc6d1c342015-02-26 14:44:43 -08005334 }
Svetoslavc6d1c342015-02-26 14:44:43 -08005335
Svet Ganov12a692a2015-03-28 19:34:15 -07005336 switch (parser.getName()) {
5337 case TAG_ITEM: {
5338 String name = parser.getAttributeValue(null, ATTR_NAME);
Todd Kennedy0eb97382017-10-03 16:57:22 -07005339 BasePermission bp = mPermissions.getPermission(name);
Svet Ganov12a692a2015-03-28 19:34:15 -07005340 if (bp == null) {
5341 Slog.w(PackageManagerService.TAG, "Unknown permission:" + name);
5342 XmlUtils.skipCurrentTag(parser);
5343 continue;
5344 }
Svetoslavc6d1c342015-02-26 14:44:43 -08005345
Svet Ganov8c7f7002015-05-07 10:48:44 -07005346 String grantedStr = parser.getAttributeValue(null, ATTR_GRANTED);
5347 final boolean granted = grantedStr == null
5348 || Boolean.parseBoolean(grantedStr);
5349
5350 String flagsStr = parser.getAttributeValue(null, ATTR_FLAGS);
5351 final int flags = (flagsStr != null)
5352 ? Integer.parseInt(flagsStr, 16) : 0;
5353
5354 if (granted) {
Svet Ganovadc1cf42015-06-15 16:36:24 -07005355 permissionsState.grantRuntimePermission(bp, userId);
5356 permissionsState.updatePermissionFlags(bp, userId,
Philip P. Moltmann76597692019-03-02 13:18:41 -08005357 PackageManager.MASK_PERMISSION_FLAGS_ALL, flags);
Svet Ganov8c7f7002015-05-07 10:48:44 -07005358 } else {
Svet Ganovadc1cf42015-06-15 16:36:24 -07005359 permissionsState.updatePermissionFlags(bp, userId,
Philip P. Moltmann76597692019-03-02 13:18:41 -08005360 PackageManager.MASK_PERMISSION_FLAGS_ALL, flags);
Svet Ganov12a692a2015-03-28 19:34:15 -07005361 }
Svet Ganov8c7f7002015-05-07 10:48:44 -07005362
Svet Ganov12a692a2015-03-28 19:34:15 -07005363 } break;
Svetoslavc6d1c342015-02-26 14:44:43 -08005364 }
Svetoslavc6d1c342015-02-26 14:44:43 -08005365 }
Svetoslavc6d1c342015-02-26 14:44:43 -08005366 }
5367
Svet Ganov8c7f7002015-05-07 10:48:44 -07005368 private void writePermissions(XmlSerializer serializer,
5369 List<PermissionState> permissionStates) throws IOException {
5370 for (PermissionState permissionState : permissionStates) {
Svetoslavc6d1c342015-02-26 14:44:43 -08005371 serializer.startTag(null, TAG_ITEM);
Svet Ganov8c7f7002015-05-07 10:48:44 -07005372 serializer.attribute(null, ATTR_NAME,permissionState.getName());
5373 serializer.attribute(null, ATTR_GRANTED,
5374 String.valueOf(permissionState.isGranted()));
5375 serializer.attribute(null, ATTR_FLAGS,
5376 Integer.toHexString(permissionState.getFlags()));
Svetoslavc6d1c342015-02-26 14:44:43 -08005377 serializer.endTag(null, TAG_ITEM);
5378 }
5379 }
5380
5381 private final class MyHandler extends Handler {
5382 public MyHandler() {
5383 super(BackgroundThread.getHandler().getLooper());
5384 }
5385
5386 @Override
5387 public void handleMessage(Message message) {
5388 final int userId = message.what;
5389 Runnable callback = (Runnable) message.obj;
5390 writePermissionsSync(userId);
5391 if (callback != null) {
5392 callback.run();
5393 }
5394 }
5395 }
5396 }
Andy McFadden2f362292012-01-20 14:43:38 -08005397}