blob: 7dc04dee65eefeb4e394e1c256c0856ce07425ec [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;
Dianne Hackbornfd7aded2013-01-22 17:10:23 -080021import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
Dianne Hackborn0ac30312011-06-17 14:49:23 -070022import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070023import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
Jeff Sharkey1c27576a2012-04-11 19:07:08 -070024import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
Fabrice Di Meglio07885952015-04-06 19:41:28 -070025import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
26import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -080027import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
Jeff Sharkey184a0102013-07-10 16:19:52 -070028import static android.os.Process.SYSTEM_UID;
29import static android.os.Process.PACKAGE_INFO_GID;
Christopher Tate72c10a22015-06-12 18:31:24 -070030import static com.android.server.pm.PackageManagerService.DEBUG_DOMAIN_VERIFICATION;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070031
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080032import android.content.IntentFilter;
33import android.content.pm.ActivityInfo;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -080034import android.content.pm.IntentFilterVerificationInfo;
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080035import android.content.pm.ResolveInfo;
36import android.net.Uri;
Narayan Kamathff110bd2014-07-04 18:30:45 +010037import android.os.Binder;
Jeff Sharkey4ed745d2014-07-15 20:39:15 -070038import android.os.Build;
Narayan Kamathff110bd2014-07-04 18:30:45 +010039import android.os.Environment;
40import android.os.FileUtils;
Svetoslavc6d1c342015-02-26 14:44:43 -080041import android.os.Handler;
42import android.os.Message;
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080043import android.os.PatternMatcher;
Narayan Kamathff110bd2014-07-04 18:30:45 +010044import android.os.Process;
Svetoslavc6d1c342015-02-26 14:44:43 -080045import android.os.SystemClock;
Narayan Kamathff110bd2014-07-04 18:30:45 +010046import android.os.UserHandle;
Amith Yamasani26f9ea32014-09-11 10:56:51 -070047import android.os.UserManager;
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -070048import android.os.storage.StorageManager;
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -070049import android.os.storage.VolumeInfo;
Svetoslavc6d1c342015-02-26 14:44:43 -080050import android.util.AtomicFile;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -080051import android.text.TextUtils;
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080052import android.util.LogPrinter;
Svetoslavc6d1c342015-02-26 14:44:43 -080053import android.util.SparseBooleanArray;
54import android.util.SparseLongArray;
Christopher Tatee012a232015-04-01 17:18:50 -070055
Svetoslavc6d1c342015-02-26 14:44:43 -080056import com.android.internal.annotations.GuardedBy;
57import com.android.internal.os.BackgroundThread;
58import com.android.internal.util.ArrayUtils;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070059import com.android.internal.util.FastXmlSerializer;
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -070060import com.android.internal.util.IndentingPrintWriter;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070061import com.android.internal.util.JournaledFile;
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -070062import com.android.internal.util.Preconditions;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070063import com.android.internal.util.XmlUtils;
Christopher Tatee012a232015-04-01 17:18:50 -070064import com.android.server.backup.PreferredActivityBackupHelper;
Kenny Root447106f2011-03-23 11:00:15 -070065import com.android.server.pm.PackageManagerService.DumpState;
Svet Ganov8c7f7002015-05-07 10:48:44 -070066import com.android.server.pm.PermissionsState.PermissionState;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070067
Svetoslavc6d1c342015-02-26 14:44:43 -080068import java.io.FileNotFoundException;
Narayan Kamathdf6d6dc2014-04-28 14:18:34 +010069import java.util.Collection;
Alexandra Gherghina6e2ae252014-06-12 16:03:58 +010070
Kenny Rootcf0b38c2011-03-22 14:17:59 -070071import org.xmlpull.v1.XmlPullParser;
72import org.xmlpull.v1.XmlPullParserException;
73import org.xmlpull.v1.XmlSerializer;
74
Kenny Root447106f2011-03-23 11:00:15 -070075import android.content.ComponentName;
76import android.content.Intent;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070077import android.content.pm.ApplicationInfo;
78import android.content.pm.ComponentInfo;
Dianne Hackborn7767eac2012-08-23 18:25:40 -070079import android.content.pm.PackageCleanItem;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070080import android.content.pm.PackageManager;
81import android.content.pm.PackageParser;
82import android.content.pm.PermissionInfo;
83import android.content.pm.Signature;
Amith Yamasani483f3b02012-03-13 16:08:00 -070084import android.content.pm.UserInfo;
Dianne Hackborn7767eac2012-08-23 18:25:40 -070085import android.content.pm.PackageUserState;
Kenny Root0aaa0d92011-09-12 16:42:55 -070086import android.content.pm.VerifierDeviceIdentity;
Jeff Sharkey9f837a92014-10-24 12:07:24 -070087import android.util.ArrayMap;
88import android.util.ArraySet;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070089import android.util.Log;
90import android.util.Slog;
91import android.util.SparseArray;
Christopher Tatef0d6cb32015-07-10 17:44:53 -070092import android.util.SparseIntArray;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070093import android.util.Xml;
94
95import java.io.BufferedOutputStream;
96import java.io.File;
97import java.io.FileInputStream;
98import java.io.FileOutputStream;
99import java.io.IOException;
100import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100101import java.nio.charset.StandardCharsets;
Kenny Root447106f2011-03-23 11:00:15 -0700102import java.text.SimpleDateFormat;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700103import java.util.ArrayList;
104import java.util.Arrays;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -0800105import java.util.Collections;
Kenny Root447106f2011-03-23 11:00:15 -0700106import java.util.Date;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700107import java.util.Iterator;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700108import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800109import java.util.Map;
Jeff Sharkey84f12942014-07-10 17:48:11 -0700110import java.util.Objects;
Dianne Hackborn63092712012-10-07 14:45:35 -0700111import java.util.Set;
112import java.util.Map.Entry;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700113
Kenny Root62539e92011-11-10 09:35:38 -0800114import libcore.io.IoUtils;
115
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700116/**
117 * Holds information about dynamic settings.
118 */
119final class Settings {
Kenny Root447106f2011-03-23 11:00:15 -0700120 private static final String TAG = "PackageSettings";
121
Kenny Rootc1c0d3c2014-04-24 13:36:40 -0700122 /**
123 * Current version of the package database. Set it to the latest version in
124 * the {@link DatabaseVersion} class below to ensure the database upgrade
125 * doesn't happen repeatedly.
126 * <p>
127 * Note that care should be taken to make sure all database upgrades are
128 * idempotent.
129 */
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700130 public static final int CURRENT_DATABASE_VERSION = DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
Kenny Rootc1c0d3c2014-04-24 13:36:40 -0700131
132 /**
133 * This class contains constants that can be referred to from upgrade code.
134 * Insert constant values here that describe the upgrade reason. The version
135 * code must be monotonically increasing.
136 */
137 public static class DatabaseVersion {
138 /**
139 * The initial version of the database.
140 */
141 public static final int FIRST_VERSION = 1;
Kenny Roota8e65fd2014-04-24 11:44:47 -0700142
143 /**
144 * Migrating the Signature array from the entire certificate chain to
145 * just the signing certificate.
146 */
147 public static final int SIGNATURE_END_ENTITY = 2;
Jeff Sharkeyd68b87c2014-11-12 12:18:11 -0800148
149 /**
150 * There was a window of time in
151 * {@link android.os.Build.VERSION_CODES#LOLLIPOP} where we persisted
152 * certificates after potentially mutating them. To switch back to the
153 * original untouched certificates, we need to force a collection pass.
154 */
155 public static final int SIGNATURE_MALFORMED_RECOVER = 3;
Kenny Rootc1c0d3c2014-04-24 13:36:40 -0700156 }
157
Kenny Root447106f2011-03-23 11:00:15 -0700158 private static final boolean DEBUG_STOPPED = false;
Amith Yamasani258848d2012-08-10 17:06:33 -0700159 private static final boolean DEBUG_MU = false;
Kenny Root447106f2011-03-23 11:00:15 -0700160
Svetoslavc6d1c342015-02-26 14:44:43 -0800161 private static final String RUNTIME_PERMISSIONS_FILE_NAME = "runtime-permissions.xml";
162
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -0700163 private static final String TAG_READ_EXTERNAL_STORAGE = "read-external-storage";
164 private static final String ATTR_ENFORCEMENT = "enforcement";
165
Amith Yamasani483f3b02012-03-13 16:08:00 -0700166 private static final String TAG_ITEM = "item";
167 private static final String TAG_DISABLED_COMPONENTS = "disabled-components";
168 private static final String TAG_ENABLED_COMPONENTS = "enabled-components";
169 private static final String TAG_PACKAGE_RESTRICTIONS = "package-restrictions";
170 private static final String TAG_PACKAGE = "pkg";
Svetoslavc6d1c342015-02-26 14:44:43 -0800171 private static final String TAG_SHARED_USER = "shared-user";
172 private static final String TAG_RUNTIME_PERMISSIONS = "runtime-permissions";
173 private static final String TAG_PERMISSIONS = "perms";
Sander Alewijnseaf597622014-03-20 18:44:57 +0000174 private static final String TAG_PERSISTENT_PREFERRED_ACTIVITIES =
175 "persistent-preferred-activities";
Nicolas Prevot81948992014-05-16 18:25:26 +0100176 static final String TAG_CROSS_PROFILE_INTENT_FILTERS =
177 "crossProfile-intent-filters";
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700178 private static final String TAG_DOMAIN_VERIFICATION = "domain-verification";
179 private static final String TAG_DEFAULT_APPS = "default-apps";
180 private static final String TAG_ALL_INTENT_FILTER_VERIFICATION =
Christopher Tate6038d152015-06-17 13:07:46 -0700181 "all-intent-filter-verifications";
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700182 private static final String TAG_DEFAULT_BROWSER = "default-browser";
183 private static final String TAG_VERSION = "version";
Amith Yamasani483f3b02012-03-13 16:08:00 -0700184
185 private static final String ATTR_NAME = "name";
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700186 private static final String ATTR_USER = "user";
187 private static final String ATTR_CODE = "code";
Amith Yamasani483f3b02012-03-13 16:08:00 -0700188 private static final String ATTR_NOT_LAUNCHED = "nl";
189 private static final String ATTR_ENABLED = "enabled";
Svet Ganov8c7f7002015-05-07 10:48:44 -0700190 private static final String ATTR_GRANTED = "granted";
191 private static final String ATTR_FLAGS = "flags";
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -0700192 private static final String ATTR_ENABLED_CALLER = "enabledCaller";
Amith Yamasani483f3b02012-03-13 16:08:00 -0700193 private static final String ATTR_STOPPED = "stopped";
Amith Yamasanie5bcff62014-07-19 15:44:09 -0700194 // Legacy, here for reading older versions of the package-restrictions.
Amith Yamasani655d0e22013-06-12 14:19:10 -0700195 private static final String ATTR_BLOCKED = "blocked";
Amith Yamasanie5bcff62014-07-19 15:44:09 -0700196 // New name for the above attribute.
197 private static final String ATTR_HIDDEN = "hidden";
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700198 private static final String ATTR_INSTALLED = "inst";
Kenny Guyc13053b2014-05-29 14:17:17 +0100199 private static final String ATTR_BLOCK_UNINSTALL = "blockUninstall";
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -0800200 private static final String ATTR_DOMAIN_VERIFICATON_STATE = "domainVerificationStatus";
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700201 private static final String ATTR_PACKAGE_NAME = "packageName";
Svet Ganovba3ba812015-06-26 10:54:06 -0700202 private static final String ATTR_FINGERPRINT = "fingerprint";
Christopher Tatef0d6cb32015-07-10 17:44:53 -0700203 private static final String ATTR_APP_LINK_GENERATION = "app-link-generation";
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700204 private static final String ATTR_VOLUME_UUID = "volumeUuid";
205 private static final String ATTR_SDK_VERSION = "sdkVersion";
206 private static final String ATTR_DATABASE_VERSION = "databaseVersion";
Amith Yamasani483f3b02012-03-13 16:08:00 -0700207
Svetoslavc6d1c342015-02-26 14:44:43 -0800208 private final Object mLock;
Svetoslavc6d1c342015-02-26 14:44:43 -0800209
210 private final RuntimePermissionPersistence mRuntimePermissionsPersistence;
211
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700212 private final File mSettingsFilename;
213 private final File mBackupSettingsFilename;
214 private final File mPackageListFilename;
215 private final File mStoppedPackagesFilename;
216 private final File mBackupStoppedPackagesFilename;
Jeff Sharkey184a0102013-07-10 16:19:52 -0700217
Jeff Sharkey9f837a92014-10-24 12:07:24 -0700218 final ArrayMap<String, PackageSetting> mPackages =
219 new ArrayMap<String, PackageSetting>();
Christopher Tate6038d152015-06-17 13:07:46 -0700220
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700221 // List of replaced system applications
Jeff Sharkey9f837a92014-10-24 12:07:24 -0700222 private final ArrayMap<String, PackageSetting> mDisabledSysPackages =
223 new ArrayMap<String, PackageSetting>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700224
Christopher Tate6038d152015-06-17 13:07:46 -0700225 // Set of restored intent-filter verification states
226 private final ArrayMap<String, IntentFilterVerificationInfo> mRestoredIntentFilterVerifications =
227 new ArrayMap<String, IntentFilterVerificationInfo>();
228
Geremy Condra12c18382013-03-06 16:49:06 -0800229 private static int mFirstAvailableUid = 0;
230
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700231 /** Map from volume UUID to {@link VersionInfo} */
232 private ArrayMap<String, VersionInfo> mVersion = new ArrayMap<>();
Kenny Root0aaa0d92011-09-12 16:42:55 -0700233
Kenny Rootc1c0d3c2014-04-24 13:36:40 -0700234 /**
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700235 * Version details for a storage volume that may hold apps.
Kenny Rootc1c0d3c2014-04-24 13:36:40 -0700236 */
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700237 public static class VersionInfo {
238 /**
239 * These are the last platform API version we were using for the apps
240 * installed on internal and external storage. It is used to grant newer
241 * permissions one time during a system upgrade.
242 */
243 int sdkVersion;
Kenny Rootc1c0d3c2014-04-24 13:36:40 -0700244
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700245 /**
246 * The current database version for apps on internal storage. This is
247 * used to upgrade the format of the packages.xml database not
248 * necessarily tied to an SDK version.
249 */
250 int databaseVersion;
251
252 /**
253 * Last known value of {@link Build#FINGERPRINT}. Used to determine when
254 * an system update has occurred, meaning we need to clear code caches.
255 */
256 String fingerprint;
257
258 /**
259 * Force all version information to match current system values,
260 * typically after resolving any required upgrade steps.
261 */
262 public void forceCurrent() {
263 sdkVersion = Build.VERSION.SDK_INT;
264 databaseVersion = CURRENT_DATABASE_VERSION;
265 fingerprint = Build.FINGERPRINT;
266 }
267 }
Jeff Sharkey4ed745d2014-07-15 20:39:15 -0700268
Jeff Sharkeyf5385772012-05-11 14:04:41 -0700269 Boolean mReadExternalStorageEnforced;
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -0700270
Kenny Root0aaa0d92011-09-12 16:42:55 -0700271 /** Device identity for the purpose of package verification. */
272 private VerifierDeviceIdentity mVerifierDeviceIdentity;
273
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700274 // The user's preferred activities associated with particular intent
275 // filters.
Dianne Hackborn63092712012-10-07 14:45:35 -0700276 final SparseArray<PreferredIntentResolver> mPreferredActivities =
277 new SparseArray<PreferredIntentResolver>();
278
Sander Alewijnsef475ca32014-02-17 15:13:58 +0000279 // The persistent preferred activities of the user's profile/device owner
280 // associated with particular intent filters.
281 final SparseArray<PersistentPreferredIntentResolver> mPersistentPreferredActivities =
282 new SparseArray<PersistentPreferredIntentResolver>();
283
Nicolas Prevot10fa67c2014-03-24 13:44:38 +0000284 // For every user, it is used to find to which other users the intent can be forwarded.
Nicolas Prevot81948992014-05-16 18:25:26 +0100285 final SparseArray<CrossProfileIntentResolver> mCrossProfileIntentResolvers =
286 new SparseArray<CrossProfileIntentResolver>();
Nicolas Prevot10fa67c2014-03-24 13:44:38 +0000287
Jeff Sharkey9f837a92014-10-24 12:07:24 -0700288 final ArrayMap<String, SharedUserSetting> mSharedUsers =
289 new ArrayMap<String, SharedUserSetting>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700290 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
291 private final SparseArray<Object> mOtherUserIds =
292 new SparseArray<Object>();
293
294 // For reading/writing settings file.
295 private final ArrayList<Signature> mPastSignatures =
296 new ArrayList<Signature>();
dcashman8c04fac2015-03-23 11:39:42 -0700297 private final ArrayMap<Long, Integer> mKeySetRefs =
298 new ArrayMap<Long, Integer>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700299
300 // Mapping from permission names to info about them.
Jeff Sharkey9f837a92014-10-24 12:07:24 -0700301 final ArrayMap<String, BasePermission> mPermissions =
302 new ArrayMap<String, BasePermission>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700303
304 // Mapping from permission tree names to info about them.
Jeff Sharkey9f837a92014-10-24 12:07:24 -0700305 final ArrayMap<String, BasePermission> mPermissionTrees =
306 new ArrayMap<String, BasePermission>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700307
308 // Packages that have been uninstalled and still need their external
309 // storage data deleted.
Jeff Sharkey752cd922012-09-23 16:25:12 -0700310 final ArrayList<PackageCleanItem> mPackagesToBeCleaned = new ArrayList<PackageCleanItem>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700311
312 // Packages that have been renamed since they were first installed.
313 // Keys are the new names of the packages, values are the original
314 // names. The packages appear everwhere else under their original
315 // names.
Jeff Sharkey9f837a92014-10-24 12:07:24 -0700316 final ArrayMap<String, String> mRenamedPackages = new ArrayMap<String, String>();
Fabrice Di Meglio62271722015-04-10 17:24:02 -0700317
318 // For every user, it is used to find the package name of the default Browser App.
319 final SparseArray<String> mDefaultBrowserApp = new SparseArray<String>();
320
Christopher Tatef0d6cb32015-07-10 17:44:53 -0700321 // App-link priority tracking, per-user
322 final SparseIntArray mNextAppLinkGeneration = new SparseIntArray();
323
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700324 final StringBuilder mReadMessages = new StringBuilder();
325
Kenny Root447106f2011-03-23 11:00:15 -0700326 /**
327 * Used to track packages that have a shared user ID that hasn't been read
328 * in yet.
329 * <p>
330 * TODO: make this just a local variable that is passed in during package
331 * scanning to make it less confusing.
332 */
333 private final ArrayList<PendingPackage> mPendingPackages = new ArrayList<PendingPackage>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700334
Amith Yamasani483f3b02012-03-13 16:08:00 -0700335 private final File mSystemDir;
Geremy Condraf1bcca82013-01-07 22:35:24 -0800336
dcashman55b10782014-04-09 14:20:38 -0700337 public final KeySetManagerService mKeySetManagerService = new KeySetManagerService(mPackages);
Geremy Condraf1bcca82013-01-07 22:35:24 -0800338
Svet Ganov12a692a2015-03-28 19:34:15 -0700339 Settings(Object lock) {
340 this(Environment.getDataDirectory(), lock);
Amith Yamasani483f3b02012-03-13 16:08:00 -0700341 }
342
Svet Ganov12a692a2015-03-28 19:34:15 -0700343 Settings(File dataDir, Object lock) {
Svetoslavc6d1c342015-02-26 14:44:43 -0800344 mLock = lock;
345
346 mRuntimePermissionsPersistence = new RuntimePermissionPersistence(mLock);
347
Amith Yamasani483f3b02012-03-13 16:08:00 -0700348 mSystemDir = new File(dataDir, "system");
349 mSystemDir.mkdirs();
350 FileUtils.setPermissions(mSystemDir.toString(),
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700351 FileUtils.S_IRWXU|FileUtils.S_IRWXG
352 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
353 -1, -1);
Amith Yamasani483f3b02012-03-13 16:08:00 -0700354 mSettingsFilename = new File(mSystemDir, "packages.xml");
355 mBackupSettingsFilename = new File(mSystemDir, "packages-backup.xml");
356 mPackageListFilename = new File(mSystemDir, "packages.list");
Jeff Sharkeyaebb65c2014-11-24 15:00:13 -0800357 FileUtils.setPermissions(mPackageListFilename, 0640, SYSTEM_UID, PACKAGE_INFO_GID);
Jeff Sharkey184a0102013-07-10 16:19:52 -0700358
Amith Yamasani483f3b02012-03-13 16:08:00 -0700359 // Deprecated: Needed for migration
360 mStoppedPackagesFilename = new File(mSystemDir, "packages-stopped.xml");
361 mBackupStoppedPackagesFilename = new File(mSystemDir, "packages-stopped-backup.xml");
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700362 }
363
Kenny Root447106f2011-03-23 11:00:15 -0700364 PackageSetting getPackageLPw(PackageParser.Package pkg, PackageSetting origPackage,
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700365 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Narayan Kamath4903f642014-08-11 13:33:45 +0100366 String legacyNativeLibraryPathString, String primaryCpuAbi, String secondaryCpuAbi,
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800367 int pkgFlags, int pkgPrivateFlags, UserHandle user, boolean add) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700368 final String name = pkg.packageName;
Kenny Root447106f2011-03-23 11:00:15 -0700369 PackageSetting p = getPackageLPw(name, origPackage, realName, sharedUser, codePath,
Jeff Sharkey84f12942014-07-10 17:48:11 -0700370 resourcePath, legacyNativeLibraryPathString, primaryCpuAbi, secondaryCpuAbi,
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800371 pkg.mVersionCode, pkgFlags, pkgPrivateFlags, user, add, true /* allowInstall */);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700372 return p;
373 }
374
Kenny Root447106f2011-03-23 11:00:15 -0700375 PackageSetting peekPackageLPr(String name) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700376 return mPackages.get(name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700377 }
378
379 void setInstallStatus(String pkgName, int status) {
380 PackageSetting p = mPackages.get(pkgName);
381 if(p != null) {
382 if(p.getInstallStatus() != status) {
383 p.setInstallStatus(status);
384 }
385 }
386 }
387
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -0700388 void setInstallerPackageName(String pkgName, String installerPkgName) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700389 PackageSetting p = mPackages.get(pkgName);
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -0700390 if (p != null) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700391 p.setInstallerPackageName(installerPkgName);
392 }
393 }
394
Kenny Root447106f2011-03-23 11:00:15 -0700395 SharedUserSetting getSharedUserLPw(String name,
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800396 int pkgFlags, int pkgPrivateFlags, boolean create) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700397 SharedUserSetting s = mSharedUsers.get(name);
398 if (s == null) {
399 if (!create) {
400 return null;
401 }
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800402 s = new SharedUserSetting(name, pkgFlags, pkgPrivateFlags);
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800403 s.userId = newUserIdLPw(s);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700404 Log.i(PackageManagerService.TAG, "New shared user " + name + ": id=" + s.userId);
405 // < 0 means we couldn't assign a userid; fall out and return
406 // s, which is currently null
407 if (s.userId >= 0) {
408 mSharedUsers.put(name, s);
409 }
410 }
411
412 return s;
413 }
414
Narayan Kamathdf6d6dc2014-04-28 14:18:34 +0100415 Collection<SharedUserSetting> getAllSharedUsersLPw() {
416 return mSharedUsers.values();
417 }
418
419
Kenny Root447106f2011-03-23 11:00:15 -0700420 boolean disableSystemPackageLPw(String name) {
421 final PackageSetting p = mPackages.get(name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700422 if(p == null) {
423 Log.w(PackageManagerService.TAG, "Package:"+name+" is not an installed package");
424 return false;
425 }
Kenny Root447106f2011-03-23 11:00:15 -0700426 final PackageSetting dp = mDisabledSysPackages.get(name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700427 // always make sure the system package code and resource paths dont change
428 if (dp == null) {
429 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
430 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
431 }
432 mDisabledSysPackages.put(name, p);
433
434 // a little trick... when we install the new package, we don't
435 // want to modify the existing PackageSetting for the built-in
436 // version. so at this point we need a new PackageSetting that
437 // is okay to muck with.
438 PackageSetting newp = new PackageSetting(p);
Kenny Root447106f2011-03-23 11:00:15 -0700439 replacePackageLPw(name, newp);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700440 return true;
441 }
442 return false;
443 }
444
Kenny Root447106f2011-03-23 11:00:15 -0700445 PackageSetting enableSystemPackageLPw(String name) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700446 PackageSetting p = mDisabledSysPackages.get(name);
447 if(p == null) {
448 Log.w(PackageManagerService.TAG, "Package:"+name+" is not disabled");
449 return null;
450 }
451 // Reset flag in ApplicationInfo object
452 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
453 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
454 }
Kenny Root447106f2011-03-23 11:00:15 -0700455 PackageSetting ret = addPackageLPw(name, p.realName, p.codePath, p.resourcePath,
Narayan Kamathff110bd2014-07-04 18:30:45 +0100456 p.legacyNativeLibraryPathString, p.primaryCpuAbiString,
Narayan Kamath4903f642014-08-11 13:33:45 +0100457 p.secondaryCpuAbiString, p.secondaryCpuAbiString,
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800458 p.appId, p.versionCode, p.pkgFlags, p.pkgPrivateFlags);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700459 mDisabledSysPackages.remove(name);
460 return ret;
461 }
462
Kenny Rootc52d6fd2012-05-07 23:04:52 -0700463 boolean isDisabledSystemPackageLPr(String name) {
464 return mDisabledSysPackages.containsKey(name);
465 }
466
467 void removeDisabledSystemPackageLPw(String name) {
468 mDisabledSysPackages.remove(name);
469 }
470
Kenny Root447106f2011-03-23 11:00:15 -0700471 PackageSetting addPackageLPw(String name, String realName, File codePath, File resourcePath,
Narayan Kamathff110bd2014-07-04 18:30:45 +0100472 String legacyNativeLibraryPathString, String primaryCpuAbiString, String secondaryCpuAbiString,
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800473 String cpuAbiOverrideString, int uid, int vc, int pkgFlags, int pkgPrivateFlags) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700474 PackageSetting p = mPackages.get(name);
475 if (p != null) {
Amith Yamasani13593602012-03-22 16:16:17 -0700476 if (p.appId == uid) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700477 return p;
478 }
479 PackageManagerService.reportSettingsProblem(Log.ERROR,
480 "Adding duplicate package, keeping first: " + name);
481 return null;
482 }
Narayan Kamathff110bd2014-07-04 18:30:45 +0100483 p = new PackageSetting(name, realName, codePath, resourcePath,
Narayan Kamath4903f642014-08-11 13:33:45 +0100484 legacyNativeLibraryPathString, primaryCpuAbiString, secondaryCpuAbiString,
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800485 cpuAbiOverrideString, vc, pkgFlags, pkgPrivateFlags);
Amith Yamasani13593602012-03-22 16:16:17 -0700486 p.appId = uid;
Kenny Root447106f2011-03-23 11:00:15 -0700487 if (addUserIdLPw(uid, p, name)) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700488 mPackages.put(name, p);
489 return p;
490 }
491 return null;
492 }
493
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800494 SharedUserSetting addSharedUserLPw(String name, int uid, int pkgFlags, int pkgPrivateFlags) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700495 SharedUserSetting s = mSharedUsers.get(name);
496 if (s != null) {
497 if (s.userId == uid) {
498 return s;
499 }
500 PackageManagerService.reportSettingsProblem(Log.ERROR,
501 "Adding duplicate shared user, keeping first: " + name);
502 return null;
503 }
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800504 s = new SharedUserSetting(name, pkgFlags, pkgPrivateFlags);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700505 s.userId = uid;
Kenny Root447106f2011-03-23 11:00:15 -0700506 if (addUserIdLPw(uid, s, name)) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700507 mSharedUsers.put(name, s);
508 return s;
509 }
510 return null;
511 }
512
Christopher Tate86b391c2013-09-13 16:58:36 -0700513 void pruneSharedUsersLPw() {
514 ArrayList<String> removeStage = new ArrayList<String>();
515 for (Map.Entry<String,SharedUserSetting> entry : mSharedUsers.entrySet()) {
516 final SharedUserSetting sus = entry.getValue();
517 if (sus == null || sus.packages.size() == 0) {
518 removeStage.add(entry.getKey());
519 }
520 }
521 for (int i = 0; i < removeStage.size(); i++) {
522 mSharedUsers.remove(removeStage.get(i));
523 }
524 }
525
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700526 // Transfer ownership of permissions from one package to another.
Kenny Root447106f2011-03-23 11:00:15 -0700527 void transferPermissionsLPw(String origPkg, String newPkg) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700528 // Transfer ownership of permissions to the new package.
529 for (int i=0; i<2; i++) {
Jeff Sharkey9f837a92014-10-24 12:07:24 -0700530 ArrayMap<String, BasePermission> permissions =
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700531 i == 0 ? mPermissionTrees : mPermissions;
532 for (BasePermission bp : permissions.values()) {
533 if (origPkg.equals(bp.sourcePackage)) {
534 if (PackageManagerService.DEBUG_UPGRADE) Log.v(PackageManagerService.TAG,
535 "Moving permission " + bp.name
536 + " from pkg " + bp.sourcePackage
537 + " to " + newPkg);
538 bp.sourcePackage = newPkg;
539 bp.packageSetting = null;
540 bp.perm = null;
541 if (bp.pendingInfo != null) {
542 bp.pendingInfo.packageName = newPkg;
543 }
544 bp.uid = 0;
Jeff Sharkey00f39042015-03-23 16:51:22 -0700545 bp.setGids(null, false);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700546 }
547 }
548 }
549 }
Amith Yamasani483f3b02012-03-13 16:08:00 -0700550
Kenny Root447106f2011-03-23 11:00:15 -0700551 private PackageSetting getPackageLPw(String name, PackageSetting origPackage,
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700552 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Svetoslavc6d1c342015-02-26 14:44:43 -0800553 String legacyNativeLibraryPathString, String primaryCpuAbiString,
554 String secondaryCpuAbiString, int vc, int pkgFlags, int pkgPrivateFlags,
555 UserHandle installUser, boolean add, boolean allowInstall) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700556 PackageSetting p = mPackages.get(name);
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700557 UserManagerService userManager = UserManagerService.getInstance();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700558 if (p != null) {
Narayan Kamathff110bd2014-07-04 18:30:45 +0100559 p.primaryCpuAbiString = primaryCpuAbiString;
560 p.secondaryCpuAbiString = secondaryCpuAbiString;
Narayan Kamath4903f642014-08-11 13:33:45 +0100561
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700562 if (!p.codePath.equals(codePath)) {
563 // Check to see if its a disabled system app
564 if ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
565 // This is an updated system app with versions in both system
566 // and data partition. Just let the most recent version
567 // take precedence.
Amith Yamasani483f3b02012-03-13 16:08:00 -0700568 Slog.w(PackageManagerService.TAG, "Trying to update system app code path from "
569 + p.codePathString + " to " + codePath.toString());
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700570 } else {
571 // Just a change in the code path is not an issue, but
572 // let's log a message about it.
Amith Yamasani483f3b02012-03-13 16:08:00 -0700573 Slog.i(PackageManagerService.TAG, "Package " + name + " codePath changed from "
574 + p.codePath + " to " + codePath + "; Retaining data and using new");
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700575 /*
576 * Since we've changed paths, we need to prefer the new
577 * native library path over the one stored in the
578 * package settings since we might have moved from
579 * internal to external storage or vice versa.
580 */
Narayan Kamathff110bd2014-07-04 18:30:45 +0100581 p.legacyNativeLibraryPathString = legacyNativeLibraryPathString;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700582 }
583 }
584 if (p.sharedUser != sharedUser) {
585 PackageManagerService.reportSettingsProblem(Log.WARN,
586 "Package " + name + " shared user changed from "
587 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
588 + " to "
589 + (sharedUser != null ? sharedUser.name : "<nothing>")
590 + "; replacing with new");
591 p = null;
592 } else {
Christopher Tate9f088202013-10-22 15:36:01 -0700593 // If what we are scanning is a system (and possibly privileged) package,
594 // then make it so, regardless of whether it was previously installed only
595 // in the data partition.
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800596 p.pkgFlags |= pkgFlags & ApplicationInfo.FLAG_SYSTEM;
597 p.pkgPrivateFlags |= pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700598 }
599 }
600 if (p == null) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700601 if (origPackage != null) {
602 // We are consuming the data from an existing package.
603 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
Narayan Kamath4903f642014-08-11 13:33:45 +0100604 legacyNativeLibraryPathString, primaryCpuAbiString, secondaryCpuAbiString,
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800605 null /* cpuAbiOverrideString */, vc, pkgFlags, pkgPrivateFlags);
Amith Yamasani483f3b02012-03-13 16:08:00 -0700606 if (PackageManagerService.DEBUG_UPGRADE) Log.v(PackageManagerService.TAG, "Package "
607 + name + " is adopting original package " + origPackage.name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700608 // Note that we will retain the new package's signature so
609 // that we can keep its data.
610 PackageSignatures s = p.signatures;
611 p.copyFrom(origPackage);
612 p.signatures = s;
613 p.sharedUser = origPackage.sharedUser;
Amith Yamasani13593602012-03-22 16:16:17 -0700614 p.appId = origPackage.appId;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700615 p.origPackage = origPackage;
Svet Ganove7af1942015-08-04 11:13:44 -0700616 p.getPermissionsState().copyFrom(origPackage.getPermissionsState());
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700617 mRenamedPackages.put(name, origPackage.name);
618 name = origPackage.name;
619 // Update new package state.
620 p.setTimeStamp(codePath.lastModified());
621 } else {
622 p = new PackageSetting(name, realName, codePath, resourcePath,
Narayan Kamath4903f642014-08-11 13:33:45 +0100623 legacyNativeLibraryPathString, primaryCpuAbiString, secondaryCpuAbiString,
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800624 null /* cpuAbiOverrideString */, vc, pkgFlags, pkgPrivateFlags);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700625 p.setTimeStamp(codePath.lastModified());
626 p.sharedUser = sharedUser;
627 // If this is not a system app, it starts out stopped.
628 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Kenny Root447106f2011-03-23 11:00:15 -0700629 if (DEBUG_STOPPED) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700630 RuntimeException e = new RuntimeException("here");
631 e.fillInStackTrace();
632 Slog.i(PackageManagerService.TAG, "Stopping package " + name, e);
633 }
Amith Yamasani483f3b02012-03-13 16:08:00 -0700634 List<UserInfo> users = getAllUsers();
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700635 final int installUserId = installUser != null ? installUser.getIdentifier() : 0;
Amith Yamasanif031f232012-10-26 15:35:21 -0700636 if (users != null && allowInstall) {
Amith Yamasani483f3b02012-03-13 16:08:00 -0700637 for (UserInfo user : users) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700638 // By default we consider this app to be installed
639 // for the user if no user has been specified (which
640 // means to leave it at its original value, and the
641 // original default value is true), or we are being
642 // asked to install for all users, or this is the
643 // user we are installing for.
644 final boolean installed = installUser == null
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700645 || (installUserId == UserHandle.USER_ALL
646 && !isAdbInstallDisallowed(userManager, user.id))
647 || installUserId == user.id;
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700648 p.setUserState(user.id, COMPONENT_ENABLED_STATE_DEFAULT,
649 installed,
650 true, // stopped,
651 true, // notLaunched
Amith Yamasanie5bcff62014-07-19 15:44:09 -0700652 false, // hidden
Kenny Guyc13053b2014-05-29 14:17:17 +0100653 null, null, null,
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -0800654 false, // blockUninstall
Christopher Tatef0d6cb32015-07-10 17:44:53 -0700655 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
Amith Yamasani483f3b02012-03-13 16:08:00 -0700656 writePackageRestrictionsLPr(user.id);
657 }
658 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700659 }
660 if (sharedUser != null) {
Amith Yamasani13593602012-03-22 16:16:17 -0700661 p.appId = sharedUser.userId;
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800662 } else {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700663 // Clone the setting here for disabled system packages
664 PackageSetting dis = mDisabledSysPackages.get(name);
665 if (dis != null) {
666 // For disabled packages a new setting is created
667 // from the existing user id. This still has to be
668 // added to list of user id's
669 // Copy signatures from previous setting
670 if (dis.signatures.mSignatures != null) {
671 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
672 }
Amith Yamasani13593602012-03-22 16:16:17 -0700673 p.appId = dis.appId;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700674 // Clone permissions
Svetoslavc6d1c342015-02-26 14:44:43 -0800675 p.getPermissionsState().copyFrom(dis.getPermissionsState());
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700676 // Clone component info
Amith Yamasani483f3b02012-03-13 16:08:00 -0700677 List<UserInfo> users = getAllUsers();
678 if (users != null) {
679 for (UserInfo user : users) {
680 int userId = user.id;
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700681 p.setDisabledComponentsCopy(
682 dis.getDisabledComponents(userId), userId);
683 p.setEnabledComponentsCopy(
684 dis.getEnabledComponents(userId), userId);
Amith Yamasani483f3b02012-03-13 16:08:00 -0700685 }
686 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700687 // Add new setting to list of user ids
Amith Yamasani13593602012-03-22 16:16:17 -0700688 addUserIdLPw(p.appId, p, name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700689 } else {
690 // Assign new user id
Amith Yamasani13593602012-03-22 16:16:17 -0700691 p.appId = newUserIdLPw(p);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700692 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700693 }
694 }
Amith Yamasani13593602012-03-22 16:16:17 -0700695 if (p.appId < 0) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700696 PackageManagerService.reportSettingsProblem(Log.WARN,
697 "Package " + name + " could not be assigned a valid uid");
698 return null;
699 }
700 if (add) {
701 // Finish adding new package by adding it and updating shared
702 // user preferences
Kenny Root447106f2011-03-23 11:00:15 -0700703 addPackageSettingLPw(p, name, sharedUser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700704 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700705 } else {
Amith Yamasanif031f232012-10-26 15:35:21 -0700706 if (installUser != null && allowInstall) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700707 // The caller has explicitly specified the user they want this
708 // package installed for, and the package already exists.
709 // Make sure it conforms to the new request.
710 List<UserInfo> users = getAllUsers();
711 if (users != null) {
712 for (UserInfo user : users) {
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700713 if ((installUser.getIdentifier() == UserHandle.USER_ALL
714 && !isAdbInstallDisallowed(userManager, user.id))
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700715 || installUser.getIdentifier() == user.id) {
716 boolean installed = p.getInstalled(user.id);
717 if (!installed) {
718 p.setInstalled(true, user.id);
719 writePackageRestrictionsLPr(user.id);
720 }
721 }
722 }
723 }
724 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700725 }
726 return p;
727 }
728
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700729 boolean isAdbInstallDisallowed(UserManagerService userManager, int userId) {
730 return userManager.hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES,
731 userId);
732 }
733
Kenny Root447106f2011-03-23 11:00:15 -0700734 void insertPackageSettingLPw(PackageSetting p, PackageParser.Package pkg) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700735 p.pkg = pkg;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700736 // pkg.mSetEnabled = p.getEnabled(userId);
737 // pkg.mSetStopped = p.getStopped(userId);
Jeff Sharkeyb9f36742015-04-08 21:02:14 -0700738 final String volumeUuid = pkg.applicationInfo.volumeUuid;
Jeff Sharkeyd7460572014-07-06 20:44:55 -0700739 final String codePath = pkg.applicationInfo.getCodePath();
740 final String resourcePath = pkg.applicationInfo.getResourcePath();
Jeff Sharkey84f12942014-07-10 17:48:11 -0700741 final String legacyNativeLibraryPath = pkg.applicationInfo.nativeLibraryRootDir;
Jeff Sharkeyb9f36742015-04-08 21:02:14 -0700742 // Update volume if needed
743 if (!Objects.equals(volumeUuid, p.volumeUuid)) {
744 Slog.w(PackageManagerService.TAG, "Volume for " + p.pkg.packageName +
745 " changing from " + p.volumeUuid + " to " + volumeUuid);
746 p.volumeUuid = volumeUuid;
747 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700748 // Update code path if needed
Jeff Sharkey84f12942014-07-10 17:48:11 -0700749 if (!Objects.equals(codePath, p.codePathString)) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -0700750 Slog.w(PackageManagerService.TAG, "Code path for " + p.pkg.packageName +
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700751 " changing from " + p.codePathString + " to " + codePath);
752 p.codePath = new File(codePath);
753 p.codePathString = codePath;
754 }
755 //Update resource path if needed
Jeff Sharkey84f12942014-07-10 17:48:11 -0700756 if (!Objects.equals(resourcePath, p.resourcePathString)) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -0700757 Slog.w(PackageManagerService.TAG, "Resource path for " + p.pkg.packageName +
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700758 " changing from " + p.resourcePathString + " to " + resourcePath);
759 p.resourcePath = new File(resourcePath);
760 p.resourcePathString = resourcePath;
761 }
Narayan Kamathff110bd2014-07-04 18:30:45 +0100762 // Update the native library paths if needed
Jeff Sharkey84f12942014-07-10 17:48:11 -0700763 if (!Objects.equals(legacyNativeLibraryPath, p.legacyNativeLibraryPathString)) {
764 p.legacyNativeLibraryPathString = legacyNativeLibraryPath;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700765 }
Narayan Kamathff110bd2014-07-04 18:30:45 +0100766
Narayan Kamath9e289d72014-04-10 09:26:59 +0000767 // Update the required Cpu Abi
Narayan Kamathff110bd2014-07-04 18:30:45 +0100768 p.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
769 p.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
Narayan Kamath4903f642014-08-11 13:33:45 +0100770 p.cpuAbiOverrideString = pkg.cpuAbiOverride;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700771 // Update version code if needed
Amith Yamasani483f3b02012-03-13 16:08:00 -0700772 if (pkg.mVersionCode != p.versionCode) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700773 p.versionCode = pkg.mVersionCode;
774 }
Amith Yamasani483f3b02012-03-13 16:08:00 -0700775 // Update signatures if needed.
776 if (p.signatures.mSignatures == null) {
777 p.signatures.assignSignatures(pkg.mSignatures);
778 }
Kenny Root5455f682012-09-09 14:52:10 -0700779 // Update flags if needed.
780 if (pkg.applicationInfo.flags != p.pkgFlags) {
781 p.pkgFlags = pkg.applicationInfo.flags;
782 }
Amith Yamasani483f3b02012-03-13 16:08:00 -0700783 // If this app defines a shared user id initialize
784 // the shared user signatures as well.
785 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
786 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
787 }
Kenny Root447106f2011-03-23 11:00:15 -0700788 addPackageSettingLPw(p, pkg.packageName, p.sharedUser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700789 }
790
791 // Utility method that adds a PackageSetting to mPackages and
Christopher Tate6038d152015-06-17 13:07:46 -0700792 // completes updating the shared user attributes and any restored
793 // app link verification state
Kenny Root447106f2011-03-23 11:00:15 -0700794 private void addPackageSettingLPw(PackageSetting p, String name,
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700795 SharedUserSetting sharedUser) {
796 mPackages.put(name, p);
797 if (sharedUser != null) {
798 if (p.sharedUser != null && p.sharedUser != sharedUser) {
799 PackageManagerService.reportSettingsProblem(Log.ERROR,
800 "Package " + p.name + " was user "
801 + p.sharedUser + " but is now " + sharedUser
802 + "; I am not changing its files so it will probably fail!");
Ben Gruverdd72c9e2013-08-06 12:34:17 -0700803 p.sharedUser.removePackage(p);
Amith Yamasani13593602012-03-22 16:16:17 -0700804 } else if (p.appId != sharedUser.userId) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700805 PackageManagerService.reportSettingsProblem(Log.ERROR,
Amith Yamasani13593602012-03-22 16:16:17 -0700806 "Package " + p.name + " was user id " + p.appId
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700807 + " but is now user " + sharedUser
808 + " with id " + sharedUser.userId
809 + "; I am not changing its files so it will probably fail!");
810 }
811
Ben Gruverdd72c9e2013-08-06 12:34:17 -0700812 sharedUser.addPackage(p);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700813 p.sharedUser = sharedUser;
Amith Yamasani13593602012-03-22 16:16:17 -0700814 p.appId = sharedUser.userId;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700815 }
Svet Ganove7af1942015-08-04 11:13:44 -0700816
817 // If the we know about this user id, we have to update it as it
818 // has to point to the same PackageSetting instance as the package.
819 Object userIdPs = getUserIdLPr(p.appId);
820 if (sharedUser == null) {
821 if (userIdPs != null && userIdPs != p) {
822 replaceUserIdLPw(p.appId, p);
823 }
824 } else {
825 if (userIdPs != null && userIdPs != sharedUser) {
826 replaceUserIdLPw(p.appId, sharedUser);
827 }
828 }
829
Christopher Tate6038d152015-06-17 13:07:46 -0700830 IntentFilterVerificationInfo ivi = mRestoredIntentFilterVerifications.get(name);
831 if (ivi != null) {
832 if (DEBUG_DOMAIN_VERIFICATION) {
833 Slog.i(TAG, "Applying restored IVI for " + name + " : " + ivi.getStatusString());
834 }
835 mRestoredIntentFilterVerifications.remove(name);
836 p.setIntentFilterVerificationInfo(ivi);
837 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700838 }
839
840 /*
841 * Update the shared user setting when a package using
842 * specifying the shared user id is removed. The gids
843 * associated with each permission of the deleted package
844 * are removed from the shared user's gid list only if its
845 * not in use by other permissions of packages in the
846 * shared user setting.
847 */
Svetoslavc6d1c342015-02-26 14:44:43 -0800848 int updateSharedUserPermsLPw(PackageSetting deletedPs, int userId) {
Kenny Root447106f2011-03-23 11:00:15 -0700849 if ((deletedPs == null) || (deletedPs.pkg == null)) {
850 Slog.i(PackageManagerService.TAG,
851 "Trying to update info for null package. Just ignoring");
Svetoslavc6d1c342015-02-26 14:44:43 -0800852 return UserHandle.USER_NULL;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700853 }
Svetoslavc6d1c342015-02-26 14:44:43 -0800854
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700855 // No sharedUserId
856 if (deletedPs.sharedUser == null) {
Svetoslavc6d1c342015-02-26 14:44:43 -0800857 return UserHandle.USER_NULL;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700858 }
Svetoslavc6d1c342015-02-26 14:44:43 -0800859
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700860 SharedUserSetting sus = deletedPs.sharedUser;
Svetoslavc6d1c342015-02-26 14:44:43 -0800861
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700862 // Update permissions
Kenny Root447106f2011-03-23 11:00:15 -0700863 for (String eachPerm : deletedPs.pkg.requestedPermissions) {
Svetoslavc6d1c342015-02-26 14:44:43 -0800864 BasePermission bp = mPermissions.get(eachPerm);
865 if (bp == null) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700866 continue;
867 }
Svetoslavc6d1c342015-02-26 14:44:43 -0800868
Svetoslavc6d1c342015-02-26 14:44:43 -0800869 // Check if another package in the shared user needs the permission.
Svetoslav4a5f4a22015-07-07 18:18:15 -0700870 boolean used = false;
Svetoslavc6d1c342015-02-26 14:44:43 -0800871 for (PackageSetting pkg : sus.packages) {
872 if (pkg.pkg != null
873 && !pkg.pkg.packageName.equals(deletedPs.pkg.packageName)
874 && pkg.pkg.requestedPermissions.contains(eachPerm)) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700875 used = true;
876 break;
877 }
878 }
Svetoslav4a5f4a22015-07-07 18:18:15 -0700879 if (used) {
880 continue;
881 }
Svetoslavc6d1c342015-02-26 14:44:43 -0800882
Svetoslav4a5f4a22015-07-07 18:18:15 -0700883 PermissionsState permissionsState = sus.getPermissionsState();
884 PackageSetting disabledPs = getDisabledSystemPkgLPr(deletedPs.pkg.packageName);
Svet Ganov8c7f7002015-05-07 10:48:44 -0700885
Svetoslav4a5f4a22015-07-07 18:18:15 -0700886 // If the package is shadowing is a disabled system package,
887 // do not drop permissions that the shadowed package requests.
888 if (disabledPs != null) {
889 boolean reqByDisabledSysPkg = false;
890 for (String permission : disabledPs.pkg.requestedPermissions) {
891 if (permission.equals(eachPerm)) {
892 reqByDisabledSysPkg = true;
893 break;
894 }
Svetoslavc6d1c342015-02-26 14:44:43 -0800895 }
Svetoslav4a5f4a22015-07-07 18:18:15 -0700896 if (reqByDisabledSysPkg) {
897 continue;
Svetoslavc6d1c342015-02-26 14:44:43 -0800898 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700899 }
Svetoslav4a5f4a22015-07-07 18:18:15 -0700900
901 // Try to revoke as an install permission which is for all users.
902 // The package is gone - no need to keep flags for applying policy.
903 permissionsState.updatePermissionFlags(bp, userId,
904 PackageManager.MASK_PERMISSION_FLAGS, 0);
905
906 if (permissionsState.revokeInstallPermission(bp) ==
907 PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED) {
908 return UserHandle.USER_ALL;
909 }
910
911 // Try to revoke as an install permission which is per user.
912 if (permissionsState.revokeRuntimePermission(bp, userId) ==
913 PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED) {
914 return userId;
915 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700916 }
Svetoslavc6d1c342015-02-26 14:44:43 -0800917
918 return UserHandle.USER_NULL;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700919 }
920
Kenny Root447106f2011-03-23 11:00:15 -0700921 int removePackageLPw(String name) {
922 final PackageSetting p = mPackages.get(name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700923 if (p != null) {
924 mPackages.remove(name);
925 if (p.sharedUser != null) {
Ben Gruverdd72c9e2013-08-06 12:34:17 -0700926 p.sharedUser.removePackage(p);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700927 if (p.sharedUser.packages.size() == 0) {
928 mSharedUsers.remove(p.sharedUser.name);
Kenny Root447106f2011-03-23 11:00:15 -0700929 removeUserIdLPw(p.sharedUser.userId);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700930 return p.sharedUser.userId;
931 }
932 } else {
Amith Yamasani13593602012-03-22 16:16:17 -0700933 removeUserIdLPw(p.appId);
934 return p.appId;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700935 }
936 }
937 return -1;
938 }
939
Kenny Root447106f2011-03-23 11:00:15 -0700940 private void replacePackageLPw(String name, PackageSetting newp) {
941 final PackageSetting p = mPackages.get(name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700942 if (p != null) {
943 if (p.sharedUser != null) {
Ben Gruverdd72c9e2013-08-06 12:34:17 -0700944 p.sharedUser.removePackage(p);
945 p.sharedUser.addPackage(newp);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700946 } else {
Amith Yamasani13593602012-03-22 16:16:17 -0700947 replaceUserIdLPw(p.appId, newp);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700948 }
949 }
950 mPackages.put(name, newp);
951 }
952
Kenny Root447106f2011-03-23 11:00:15 -0700953 private boolean addUserIdLPw(int uid, Object obj, Object name) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800954 if (uid > Process.LAST_APPLICATION_UID) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700955 return false;
956 }
957
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800958 if (uid >= Process.FIRST_APPLICATION_UID) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700959 int N = mUserIds.size();
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800960 final int index = uid - Process.FIRST_APPLICATION_UID;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700961 while (index >= N) {
962 mUserIds.add(null);
963 N++;
964 }
965 if (mUserIds.get(index) != null) {
966 PackageManagerService.reportSettingsProblem(Log.ERROR,
967 "Adding duplicate user id: " + uid
968 + " name=" + name);
969 return false;
970 }
971 mUserIds.set(index, obj);
972 } else {
973 if (mOtherUserIds.get(uid) != null) {
974 PackageManagerService.reportSettingsProblem(Log.ERROR,
975 "Adding duplicate shared id: " + uid
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -0800976 + " name=" + name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700977 return false;
978 }
979 mOtherUserIds.put(uid, obj);
980 }
981 return true;
982 }
983
Kenny Root447106f2011-03-23 11:00:15 -0700984 public Object getUserIdLPr(int uid) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800985 if (uid >= Process.FIRST_APPLICATION_UID) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700986 final int N = mUserIds.size();
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800987 final int index = uid - Process.FIRST_APPLICATION_UID;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700988 return index < N ? mUserIds.get(index) : null;
989 } else {
990 return mOtherUserIds.get(uid);
991 }
992 }
993
Kenny Root447106f2011-03-23 11:00:15 -0700994 private void removeUserIdLPw(int uid) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800995 if (uid >= Process.FIRST_APPLICATION_UID) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700996 final int N = mUserIds.size();
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800997 final int index = uid - Process.FIRST_APPLICATION_UID;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700998 if (index < N) mUserIds.set(index, null);
999 } else {
1000 mOtherUserIds.remove(uid);
1001 }
Geremy Condra12c18382013-03-06 16:49:06 -08001002 setFirstAvailableUid(uid+1);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001003 }
1004
Kenny Root447106f2011-03-23 11:00:15 -07001005 private void replaceUserIdLPw(int uid, Object obj) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08001006 if (uid >= Process.FIRST_APPLICATION_UID) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001007 final int N = mUserIds.size();
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08001008 final int index = uid - Process.FIRST_APPLICATION_UID;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001009 if (index < N) mUserIds.set(index, obj);
1010 } else {
1011 mOtherUserIds.put(uid, obj);
1012 }
1013 }
1014
Dianne Hackborn63092712012-10-07 14:45:35 -07001015 PreferredIntentResolver editPreferredActivitiesLPw(int userId) {
1016 PreferredIntentResolver pir = mPreferredActivities.get(userId);
1017 if (pir == null) {
1018 pir = new PreferredIntentResolver();
1019 mPreferredActivities.put(userId, pir);
1020 }
1021 return pir;
1022 }
1023
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001024 PersistentPreferredIntentResolver editPersistentPreferredActivitiesLPw(int userId) {
1025 PersistentPreferredIntentResolver ppir = mPersistentPreferredActivities.get(userId);
1026 if (ppir == null) {
1027 ppir = new PersistentPreferredIntentResolver();
1028 mPersistentPreferredActivities.put(userId, ppir);
1029 }
1030 return ppir;
1031 }
1032
Nicolas Prevot81948992014-05-16 18:25:26 +01001033 CrossProfileIntentResolver editCrossProfileIntentResolverLPw(int userId) {
1034 CrossProfileIntentResolver cpir = mCrossProfileIntentResolvers.get(userId);
1035 if (cpir == null) {
1036 cpir = new CrossProfileIntentResolver();
1037 mCrossProfileIntentResolvers.put(userId, cpir);
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001038 }
Nicolas Prevot81948992014-05-16 18:25:26 +01001039 return cpir;
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001040 }
1041
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001042 /**
1043 * The following functions suppose that you have a lock for managing access to the
1044 * mIntentFiltersVerifications map.
1045 */
1046
1047 /* package protected */
1048 IntentFilterVerificationInfo getIntentFilterVerificationLPr(String packageName) {
1049 PackageSetting ps = mPackages.get(packageName);
1050 if (ps == null) {
Christopher Tate72c10a22015-06-12 18:31:24 -07001051 if (DEBUG_DOMAIN_VERIFICATION) {
1052 Slog.w(PackageManagerService.TAG, "No package known: " + packageName);
1053 }
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001054 return null;
1055 }
1056 return ps.getIntentFilterVerificationInfo();
1057 }
1058
1059 /* package protected */
Fabrice Di Meglio7d014ce2015-04-08 16:17:46 -07001060 IntentFilterVerificationInfo createIntentFilterVerificationIfNeededLPw(String packageName,
Fabrice Di Meglio07885952015-04-06 19:41:28 -07001061 ArrayList<String> domains) {
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001062 PackageSetting ps = mPackages.get(packageName);
1063 if (ps == null) {
Christopher Tate72c10a22015-06-12 18:31:24 -07001064 if (DEBUG_DOMAIN_VERIFICATION) {
1065 Slog.w(PackageManagerService.TAG, "No package known: " + packageName);
1066 }
Fabrice Di Meglio7d014ce2015-04-08 16:17:46 -07001067 return null;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001068 }
Fabrice Di Meglio7d014ce2015-04-08 16:17:46 -07001069 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
1070 if (ivi == null) {
1071 ivi = new IntentFilterVerificationInfo(packageName, domains);
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001072 ps.setIntentFilterVerificationInfo(ivi);
Christopher Tate72c10a22015-06-12 18:31:24 -07001073 if (DEBUG_DOMAIN_VERIFICATION) {
1074 Slog.d(PackageManagerService.TAG,
1075 "Creating new IntentFilterVerificationInfo for pkg: " + packageName);
1076 }
Fabrice Di Meglio1de3f0d2015-04-29 19:42:41 -07001077 } else {
1078 ivi.setDomains(domains);
Christopher Tate72c10a22015-06-12 18:31:24 -07001079 if (DEBUG_DOMAIN_VERIFICATION) {
1080 Slog.d(PackageManagerService.TAG,
1081 "Setting domains to existing IntentFilterVerificationInfo for pkg: " +
1082 packageName + " and with domains: " + ivi.getDomainsString());
1083 }
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001084 }
Fabrice Di Meglio7d014ce2015-04-08 16:17:46 -07001085 return ivi;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001086 }
1087
1088 int getIntentFilterVerificationStatusLPr(String packageName, int userId) {
1089 PackageSetting ps = mPackages.get(packageName);
1090 if (ps == null) {
Christopher Tate72c10a22015-06-12 18:31:24 -07001091 if (DEBUG_DOMAIN_VERIFICATION) {
1092 Slog.w(PackageManagerService.TAG, "No package known: " + packageName);
1093 }
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001094 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1095 }
Christopher Tated85a6642015-07-17 15:39:08 -07001096 return (int)(ps.getDomainVerificationStatusForUser(userId) >> 32);
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001097 }
1098
Christopher Tatef0d6cb32015-07-10 17:44:53 -07001099 boolean updateIntentFilterVerificationStatusLPw(String packageName, final int status, int userId) {
Fabrice Di Meglio07885952015-04-06 19:41:28 -07001100 // Update the status for the current package
1101 PackageSetting current = mPackages.get(packageName);
1102 if (current == null) {
Christopher Tate72c10a22015-06-12 18:31:24 -07001103 if (DEBUG_DOMAIN_VERIFICATION) {
1104 Slog.w(PackageManagerService.TAG, "No package known: " + packageName);
1105 }
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001106 return false;
1107 }
Christopher Tate050aee22015-07-01 16:50:43 -07001108
Christopher Tatef0d6cb32015-07-10 17:44:53 -07001109 final int alwaysGeneration;
1110 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
1111 alwaysGeneration = mNextAppLinkGeneration.get(userId) + 1;
1112 mNextAppLinkGeneration.put(userId, alwaysGeneration);
1113 } else {
1114 alwaysGeneration = 0;
1115 }
1116
1117 current.setDomainVerificationStatusForUser(status, alwaysGeneration, userId);
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001118 return true;
1119 }
1120
1121 /**
Fabrice Di Meglio07885952015-04-06 19:41:28 -07001122 * Used for Settings App and PackageManagerService dump. Should be read only.
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001123 */
1124 List<IntentFilterVerificationInfo> getIntentFilterVerificationsLPr(
1125 String packageName) {
1126 if (packageName == null) {
1127 return Collections.<IntentFilterVerificationInfo>emptyList();
1128 }
1129 ArrayList<IntentFilterVerificationInfo> result = new ArrayList<>();
1130 for (PackageSetting ps : mPackages.values()) {
1131 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
1132 if (ivi == null || TextUtils.isEmpty(ivi.getPackageName()) ||
1133 !ivi.getPackageName().equalsIgnoreCase(packageName)) {
1134 continue;
1135 }
1136 result.add(ivi);
1137 }
1138 return result;
1139 }
1140
Fabrice Di Meglio1f09b8c2015-05-06 18:51:21 -07001141 boolean removeIntentFilterVerificationLPw(String packageName, int userId) {
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001142 PackageSetting ps = mPackages.get(packageName);
1143 if (ps == null) {
Christopher Tate72c10a22015-06-12 18:31:24 -07001144 if (DEBUG_DOMAIN_VERIFICATION) {
1145 Slog.w(PackageManagerService.TAG, "No package known: " + packageName);
1146 }
Fabrice Di Meglio1f09b8c2015-05-06 18:51:21 -07001147 return false;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001148 }
1149 ps.clearDomainVerificationStatusForUser(userId);
Fabrice Di Meglio1f09b8c2015-05-06 18:51:21 -07001150 return true;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001151 }
1152
Fabrice Di Meglio1f09b8c2015-05-06 18:51:21 -07001153 boolean removeIntentFilterVerificationLPw(String packageName, int[] userIds) {
1154 boolean result = false;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001155 for (int userId : userIds) {
Fabrice Di Meglio1f09b8c2015-05-06 18:51:21 -07001156 result |= removeIntentFilterVerificationLPw(packageName, userId);
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001157 }
Fabrice Di Meglio1f09b8c2015-05-06 18:51:21 -07001158 return result;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001159 }
1160
Christopher Tatedb3fe812015-06-24 16:15:48 -07001161 boolean setDefaultBrowserPackageNameLPw(String packageName, int userId) {
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001162 if (userId == UserHandle.USER_ALL) {
1163 return false;
1164 }
1165 mDefaultBrowserApp.put(userId, packageName);
1166 writePackageRestrictionsLPr(userId);
1167 return true;
1168 }
1169
1170 String getDefaultBrowserPackageNameLPw(int userId) {
1171 return (userId == UserHandle.USER_ALL) ? null : mDefaultBrowserApp.get(userId);
1172 }
1173
Amith Yamasani483f3b02012-03-13 16:08:00 -07001174 private File getUserPackagesStateFile(int userId) {
Svetoslavc6d1c342015-02-26 14:44:43 -08001175 // TODO: Implement a cleaner solution when adding tests.
1176 // This instead of Environment.getUserSystemDirectory(userId) to support testing.
1177 File userDir = new File(new File(mSystemDir, "users"), Integer.toString(userId));
1178 return new File(userDir, "package-restrictions.xml");
1179 }
1180
1181 private File getUserRuntimePermissionsFile(int userId) {
1182 // TODO: Implement a cleaner solution when adding tests.
1183 // This instead of Environment.getUserSystemDirectory(userId) to support testing.
1184 File userDir = new File(new File(mSystemDir, "users"), Integer.toString(userId));
1185 return new File(userDir, RUNTIME_PERMISSIONS_FILE_NAME);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001186 }
1187
1188 private File getUserPackagesStateBackupFile(int userId) {
Amith Yamasani61f57372012-08-31 12:12:28 -07001189 return new File(Environment.getUserSystemDirectory(userId),
1190 "package-restrictions-backup.xml");
Amith Yamasani483f3b02012-03-13 16:08:00 -07001191 }
1192
1193 void writeAllUsersPackageRestrictionsLPr() {
1194 List<UserInfo> users = getAllUsers();
1195 if (users == null) return;
1196
1197 for (UserInfo user : users) {
1198 writePackageRestrictionsLPr(user.id);
1199 }
1200 }
1201
Svetoslavc6d1c342015-02-26 14:44:43 -08001202 void writeAllRuntimePermissionsLPr() {
1203 for (int userId : UserManagerService.getInstance().getUserIds()) {
1204 mRuntimePermissionsPersistence.writePermissionsForUserAsyncLPr(userId);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001205 }
1206 }
1207
Svet Ganovba3ba812015-06-26 10:54:06 -07001208 boolean areDefaultRuntimePermissionsGrantedLPr(int userId) {
1209 return mRuntimePermissionsPersistence
1210 .areDefaultRuntimPermissionsGrantedLPr(userId);
1211 }
1212
1213 void onDefaultRuntimePermissionsGrantedLPr(int userId) {
1214 mRuntimePermissionsPersistence
1215 .onDefaultRuntimePermissionsGrantedLPr(userId);
1216 }
1217
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07001218 public VersionInfo findOrCreateVersion(String volumeUuid) {
1219 VersionInfo ver = mVersion.get(volumeUuid);
1220 if (ver == null) {
1221 ver = new VersionInfo();
1222 ver.forceCurrent();
1223 mVersion.put(volumeUuid, ver);
1224 }
1225 return ver;
Kenny Rootc1c0d3c2014-04-24 13:36:40 -07001226 }
1227
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07001228 public VersionInfo getInternalVersion() {
1229 return mVersion.get(StorageManager.UUID_PRIVATE_INTERNAL);
Kenny Rootc1c0d3c2014-04-24 13:36:40 -07001230 }
1231
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07001232 public VersionInfo getExternalVersion() {
1233 return mVersion.get(StorageManager.UUID_PRIMARY_PHYSICAL);
Kenny Rootc1c0d3c2014-04-24 13:36:40 -07001234 }
1235
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07001236 public void onVolumeForgotten(String fsUuid) {
1237 mVersion.remove(fsUuid);
Kenny Rootc1c0d3c2014-04-24 13:36:40 -07001238 }
1239
Christopher Tatee012a232015-04-01 17:18:50 -07001240 /**
1241 * Applies the preferred activity state described by the given XML. This code
1242 * also supports the restore-from-backup code path.
1243 *
1244 * @see PreferredActivityBackupHelper
1245 */
1246 void readPreferredActivitiesLPw(XmlPullParser parser, int userId)
Dianne Hackborn63092712012-10-07 14:45:35 -07001247 throws XmlPullParserException, IOException {
1248 int outerDepth = parser.getDepth();
1249 int type;
1250 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1251 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1252 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1253 continue;
1254 }
1255
1256 String tagName = parser.getName();
1257 if (tagName.equals(TAG_ITEM)) {
1258 PreferredActivity pa = new PreferredActivity(parser);
1259 if (pa.mPref.getParseError() == null) {
1260 editPreferredActivitiesLPw(userId).addFilter(pa);
1261 } else {
1262 PackageManagerService.reportSettingsProblem(Log.WARN,
1263 "Error in package manager settings: <preferred-activity> "
1264 + pa.mPref.getParseError() + " at "
1265 + parser.getPositionDescription());
1266 }
1267 } else {
1268 PackageManagerService.reportSettingsProblem(Log.WARN,
1269 "Unknown element under <preferred-activities>: " + parser.getName());
1270 XmlUtils.skipCurrentTag(parser);
1271 }
1272 }
1273 }
1274
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001275 private void readPersistentPreferredActivitiesLPw(XmlPullParser parser, int userId)
1276 throws XmlPullParserException, IOException {
1277 int outerDepth = parser.getDepth();
1278 int type;
1279 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1280 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1281 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1282 continue;
1283 }
1284 String tagName = parser.getName();
1285 if (tagName.equals(TAG_ITEM)) {
1286 PersistentPreferredActivity ppa = new PersistentPreferredActivity(parser);
1287 editPersistentPreferredActivitiesLPw(userId).addFilter(ppa);
1288 } else {
1289 PackageManagerService.reportSettingsProblem(Log.WARN,
Sander Alewijnseaf597622014-03-20 18:44:57 +00001290 "Unknown element under <" + TAG_PERSISTENT_PREFERRED_ACTIVITIES + ">: "
1291 + parser.getName());
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001292 XmlUtils.skipCurrentTag(parser);
1293 }
1294 }
1295 }
1296
Nicolas Prevot81948992014-05-16 18:25:26 +01001297 private void readCrossProfileIntentFiltersLPw(XmlPullParser parser, int userId)
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001298 throws XmlPullParserException, IOException {
1299 int outerDepth = parser.getDepth();
1300 int type;
1301 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1302 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1303 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1304 continue;
1305 }
Christopher Tate6038d152015-06-17 13:07:46 -07001306 final String tagName = parser.getName();
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001307 if (tagName.equals(TAG_ITEM)) {
Nicolas Prevot81948992014-05-16 18:25:26 +01001308 CrossProfileIntentFilter cpif = new CrossProfileIntentFilter(parser);
1309 editCrossProfileIntentResolverLPw(userId).addFilter(cpif);
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001310 } else {
Nicolas Prevot81948992014-05-16 18:25:26 +01001311 String msg = "Unknown element under " + TAG_CROSS_PROFILE_INTENT_FILTERS + ": " +
Christopher Tate6038d152015-06-17 13:07:46 -07001312 tagName;
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001313 PackageManagerService.reportSettingsProblem(Log.WARN, msg);
1314 XmlUtils.skipCurrentTag(parser);
1315 }
1316 }
1317 }
1318
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001319 private void readDomainVerificationLPw(XmlPullParser parser, PackageSettingBase packageSetting)
1320 throws XmlPullParserException, IOException {
1321 IntentFilterVerificationInfo ivi = new IntentFilterVerificationInfo(parser);
1322 packageSetting.setIntentFilterVerificationInfo(ivi);
1323 Log.d(TAG, "Read domain verification for package:" + ivi.getPackageName());
1324 }
1325
Christopher Tate6038d152015-06-17 13:07:46 -07001326 private void readRestoredIntentFilterVerifications(XmlPullParser parser)
1327 throws XmlPullParserException, IOException {
1328 int outerDepth = parser.getDepth();
1329 int type;
1330 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1331 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1332 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1333 continue;
1334 }
1335 final String tagName = parser.getName();
1336 if (tagName.equals(TAG_DOMAIN_VERIFICATION)) {
1337 IntentFilterVerificationInfo ivi = new IntentFilterVerificationInfo(parser);
1338 if (DEBUG_DOMAIN_VERIFICATION) {
1339 Slog.i(TAG, "Restored IVI for " + ivi.getPackageName()
1340 + " status=" + ivi.getStatusString());
1341 }
1342 mRestoredIntentFilterVerifications.put(ivi.getPackageName(), ivi);
1343 } else {
1344 Slog.w(TAG, "Unknown element: " + tagName);
1345 XmlUtils.skipCurrentTag(parser);
1346 }
1347 }
1348 }
1349
1350 void readDefaultAppsLPw(XmlPullParser parser, int userId)
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001351 throws XmlPullParserException, IOException {
1352 int outerDepth = parser.getDepth();
1353 int type;
1354 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1355 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1356 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1357 continue;
1358 }
1359 String tagName = parser.getName();
1360 if (tagName.equals(TAG_DEFAULT_BROWSER)) {
1361 String packageName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
1362 mDefaultBrowserApp.put(userId, packageName);
1363 } else {
1364 String msg = "Unknown element under " + TAG_DEFAULT_APPS + ": " +
1365 parser.getName();
1366 PackageManagerService.reportSettingsProblem(Log.WARN, msg);
1367 XmlUtils.skipCurrentTag(parser);
1368 }
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001369 }
1370 }
1371
Amith Yamasani483f3b02012-03-13 16:08:00 -07001372 void readPackageRestrictionsLPr(int userId) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001373 if (DEBUG_MU) {
1374 Log.i(TAG, "Reading package restrictions for user=" + userId);
1375 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07001376 FileInputStream str = null;
1377 File userPackagesStateFile = getUserPackagesStateFile(userId);
1378 File backupFile = getUserPackagesStateBackupFile(userId);
1379 if (backupFile.exists()) {
1380 try {
1381 str = new FileInputStream(backupFile);
1382 mReadMessages.append("Reading from backup stopped packages file\n");
1383 PackageManagerService.reportSettingsProblem(Log.INFO,
1384 "Need to read from backup stopped packages file");
1385 if (userPackagesStateFile.exists()) {
1386 // If both the backup and normal file exist, we
1387 // ignore the normal one since it might have been
1388 // corrupted.
1389 Slog.w(PackageManagerService.TAG, "Cleaning up stopped packages file "
1390 + userPackagesStateFile);
1391 userPackagesStateFile.delete();
1392 }
1393 } catch (java.io.IOException e) {
1394 // We'll try for the normal settings file.
1395 }
1396 }
1397
1398 try {
1399 if (str == null) {
1400 if (!userPackagesStateFile.exists()) {
1401 mReadMessages.append("No stopped packages file found\n");
1402 PackageManagerService.reportSettingsProblem(Log.INFO,
1403 "No stopped packages file; "
1404 + "assuming all started");
1405 // At first boot, make sure no packages are stopped.
1406 // We usually want to have third party apps initialize
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001407 // in the stopped state, but not at first boot. Also
1408 // consider all applications to be installed.
Amith Yamasani483f3b02012-03-13 16:08:00 -07001409 for (PackageSetting pkg : mPackages.values()) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001410 pkg.setUserState(userId, COMPONENT_ENABLED_STATE_DEFAULT,
1411 true, // installed
1412 false, // stopped
1413 false, // notLaunched
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001414 false, // hidden
Kenny Guyc13053b2014-05-29 14:17:17 +01001415 null, null, null,
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001416 false, // blockUninstall
Christopher Tatef0d6cb32015-07-10 17:44:53 -07001417 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001418 }
1419 return;
1420 }
1421 str = new FileInputStream(userPackagesStateFile);
1422 }
1423 final XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001424 parser.setInput(str, StandardCharsets.UTF_8.name());
Amith Yamasani483f3b02012-03-13 16:08:00 -07001425
1426 int type;
1427 while ((type=parser.next()) != XmlPullParser.START_TAG
1428 && type != XmlPullParser.END_DOCUMENT) {
1429 ;
1430 }
1431
1432 if (type != XmlPullParser.START_TAG) {
1433 mReadMessages.append("No start tag found in package restrictions file\n");
1434 PackageManagerService.reportSettingsProblem(Log.WARN,
1435 "No start tag found in package manager stopped packages");
1436 return;
1437 }
1438
Christopher Tatef0d6cb32015-07-10 17:44:53 -07001439 int maxAppLinkGeneration = 0;
1440
Amith Yamasani483f3b02012-03-13 16:08:00 -07001441 int outerDepth = parser.getDepth();
1442 PackageSetting ps = null;
1443 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1444 && (type != XmlPullParser.END_TAG
1445 || parser.getDepth() > outerDepth)) {
1446 if (type == XmlPullParser.END_TAG
1447 || type == XmlPullParser.TEXT) {
1448 continue;
1449 }
1450
1451 String tagName = parser.getName();
1452 if (tagName.equals(TAG_PACKAGE)) {
1453 String name = parser.getAttributeValue(null, ATTR_NAME);
1454 ps = mPackages.get(name);
1455 if (ps == null) {
1456 Slog.w(PackageManagerService.TAG, "No package known for stopped package: "
1457 + name);
1458 XmlUtils.skipCurrentTag(parser);
1459 continue;
1460 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001461 final String enabledStr = parser.getAttributeValue(null, ATTR_ENABLED);
1462 final int enabled = enabledStr == null
1463 ? COMPONENT_ENABLED_STATE_DEFAULT : Integer.parseInt(enabledStr);
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07001464 final String enabledCaller = parser.getAttributeValue(null,
1465 ATTR_ENABLED_CALLER);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001466 final String installedStr = parser.getAttributeValue(null, ATTR_INSTALLED);
1467 final boolean installed = installedStr == null
1468 ? true : Boolean.parseBoolean(installedStr);
1469 final String stoppedStr = parser.getAttributeValue(null, ATTR_STOPPED);
1470 final boolean stopped = stoppedStr == null
1471 ? false : Boolean.parseBoolean(stoppedStr);
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001472 // For backwards compatibility with the previous name of "blocked", which
1473 // now means hidden, read the old attribute as well.
Amith Yamasani655d0e22013-06-12 14:19:10 -07001474 final String blockedStr = parser.getAttributeValue(null, ATTR_BLOCKED);
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001475 boolean hidden = blockedStr == null
Amith Yamasani655d0e22013-06-12 14:19:10 -07001476 ? false : Boolean.parseBoolean(blockedStr);
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001477 final String hiddenStr = parser.getAttributeValue(null, ATTR_HIDDEN);
1478 hidden = hiddenStr == null
1479 ? hidden : Boolean.parseBoolean(hiddenStr);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001480 final String notLaunchedStr = parser.getAttributeValue(null, ATTR_NOT_LAUNCHED);
1481 final boolean notLaunched = stoppedStr == null
1482 ? false : Boolean.parseBoolean(notLaunchedStr);
Kenny Guyc13053b2014-05-29 14:17:17 +01001483 final String blockUninstallStr = parser.getAttributeValue(null,
1484 ATTR_BLOCK_UNINSTALL);
1485 final boolean blockUninstall = blockUninstallStr == null
1486 ? false : Boolean.parseBoolean(blockUninstallStr);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001487
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001488 final String verifStateStr =
1489 parser.getAttributeValue(null, ATTR_DOMAIN_VERIFICATON_STATE);
1490 final int verifState = (verifStateStr == null) ?
1491 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED :
1492 Integer.parseInt(verifStateStr);
1493
Christopher Tatef0d6cb32015-07-10 17:44:53 -07001494 final String linkGenStr = parser.getAttributeValue(null, ATTR_APP_LINK_GENERATION);
1495 final int linkGeneration = linkGenStr == null ? 0 : Integer.parseInt(linkGenStr);
1496 if (linkGeneration > maxAppLinkGeneration) {
1497 maxAppLinkGeneration = linkGeneration;
1498 }
1499
Jeff Sharkey9f837a92014-10-24 12:07:24 -07001500 ArraySet<String> enabledComponents = null;
1501 ArraySet<String> disabledComponents = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001502
1503 int packageDepth = parser.getDepth();
1504 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1505 && (type != XmlPullParser.END_TAG
1506 || parser.getDepth() > packageDepth)) {
1507 if (type == XmlPullParser.END_TAG
1508 || type == XmlPullParser.TEXT) {
1509 continue;
1510 }
1511 tagName = parser.getName();
1512 if (tagName.equals(TAG_ENABLED_COMPONENTS)) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001513 enabledComponents = readComponentsLPr(parser);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001514 } else if (tagName.equals(TAG_DISABLED_COMPONENTS)) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001515 disabledComponents = readComponentsLPr(parser);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001516 }
1517 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001518
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001519 ps.setUserState(userId, enabled, installed, stopped, notLaunched, hidden,
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001520 enabledCaller, enabledComponents, disabledComponents, blockUninstall,
Christopher Tatef0d6cb32015-07-10 17:44:53 -07001521 verifState, linkGeneration);
Dianne Hackborn63092712012-10-07 14:45:35 -07001522 } else if (tagName.equals("preferred-activities")) {
1523 readPreferredActivitiesLPw(parser, userId);
Sander Alewijnseaf597622014-03-20 18:44:57 +00001524 } else if (tagName.equals(TAG_PERSISTENT_PREFERRED_ACTIVITIES)) {
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001525 readPersistentPreferredActivitiesLPw(parser, userId);
Nicolas Prevot29762c32014-07-29 18:51:32 +01001526 } else if (tagName.equals(TAG_CROSS_PROFILE_INTENT_FILTERS)) {
Nicolas Prevot81948992014-05-16 18:25:26 +01001527 readCrossProfileIntentFiltersLPw(parser, userId);
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001528 } else if (tagName.equals(TAG_DEFAULT_APPS)) {
1529 readDefaultAppsLPw(parser, userId);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001530 } else {
1531 Slog.w(PackageManagerService.TAG, "Unknown element under <stopped-packages>: "
1532 + parser.getName());
1533 XmlUtils.skipCurrentTag(parser);
1534 }
1535 }
1536
1537 str.close();
1538
Christopher Tatef0d6cb32015-07-10 17:44:53 -07001539 mNextAppLinkGeneration.put(userId, maxAppLinkGeneration + 1);
1540
Amith Yamasani483f3b02012-03-13 16:08:00 -07001541 } catch (XmlPullParserException e) {
1542 mReadMessages.append("Error reading: " + e.toString());
1543 PackageManagerService.reportSettingsProblem(Log.ERROR,
1544 "Error reading stopped packages: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07001545 Slog.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages",
1546 e);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001547
1548 } catch (java.io.IOException e) {
1549 mReadMessages.append("Error reading: " + e.toString());
1550 PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07001551 Slog.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages",
1552 e);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001553 }
1554 }
1555
Jeff Sharkey9f837a92014-10-24 12:07:24 -07001556 private ArraySet<String> readComponentsLPr(XmlPullParser parser)
Amith Yamasani483f3b02012-03-13 16:08:00 -07001557 throws IOException, XmlPullParserException {
Jeff Sharkey9f837a92014-10-24 12:07:24 -07001558 ArraySet<String> components = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001559 int type;
1560 int outerDepth = parser.getDepth();
1561 String tagName;
1562 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1563 && (type != XmlPullParser.END_TAG
1564 || parser.getDepth() > outerDepth)) {
1565 if (type == XmlPullParser.END_TAG
1566 || type == XmlPullParser.TEXT) {
1567 continue;
1568 }
1569 tagName = parser.getName();
1570 if (tagName.equals(TAG_ITEM)) {
1571 String componentName = parser.getAttributeValue(null, ATTR_NAME);
1572 if (componentName != null) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001573 if (components == null) {
Jeff Sharkey9f837a92014-10-24 12:07:24 -07001574 components = new ArraySet<String>();
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001575 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07001576 components.add(componentName);
1577 }
1578 }
1579 }
1580 return components;
1581 }
1582
Christopher Tatee012a232015-04-01 17:18:50 -07001583 /**
1584 * Record the state of preferred activity configuration into XML. This is used both
1585 * for recording packages.xml internally and for supporting backup/restore of the
1586 * preferred activity configuration.
1587 */
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08001588 void writePreferredActivitiesLPr(XmlSerializer serializer, int userId, boolean full)
Dianne Hackborn63092712012-10-07 14:45:35 -07001589 throws IllegalArgumentException, IllegalStateException, IOException {
1590 serializer.startTag(null, "preferred-activities");
1591 PreferredIntentResolver pir = mPreferredActivities.get(userId);
1592 if (pir != null) {
1593 for (final PreferredActivity pa : pir.filterSet()) {
1594 serializer.startTag(null, TAG_ITEM);
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08001595 pa.writeToXml(serializer, full);
Dianne Hackborn63092712012-10-07 14:45:35 -07001596 serializer.endTag(null, TAG_ITEM);
1597 }
1598 }
1599 serializer.endTag(null, "preferred-activities");
1600 }
1601
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001602 void writePersistentPreferredActivitiesLPr(XmlSerializer serializer, int userId)
1603 throws IllegalArgumentException, IllegalStateException, IOException {
Sander Alewijnseaf597622014-03-20 18:44:57 +00001604 serializer.startTag(null, TAG_PERSISTENT_PREFERRED_ACTIVITIES);
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001605 PersistentPreferredIntentResolver ppir = mPersistentPreferredActivities.get(userId);
1606 if (ppir != null) {
1607 for (final PersistentPreferredActivity ppa : ppir.filterSet()) {
1608 serializer.startTag(null, TAG_ITEM);
1609 ppa.writeToXml(serializer);
1610 serializer.endTag(null, TAG_ITEM);
1611 }
1612 }
Sander Alewijnseaf597622014-03-20 18:44:57 +00001613 serializer.endTag(null, TAG_PERSISTENT_PREFERRED_ACTIVITIES);
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001614 }
1615
Nicolas Prevot81948992014-05-16 18:25:26 +01001616 void writeCrossProfileIntentFiltersLPr(XmlSerializer serializer, int userId)
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001617 throws IllegalArgumentException, IllegalStateException, IOException {
Nicolas Prevot81948992014-05-16 18:25:26 +01001618 serializer.startTag(null, TAG_CROSS_PROFILE_INTENT_FILTERS);
1619 CrossProfileIntentResolver cpir = mCrossProfileIntentResolvers.get(userId);
1620 if (cpir != null) {
1621 for (final CrossProfileIntentFilter cpif : cpir.filterSet()) {
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001622 serializer.startTag(null, TAG_ITEM);
Nicolas Prevot81948992014-05-16 18:25:26 +01001623 cpif.writeToXml(serializer);
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001624 serializer.endTag(null, TAG_ITEM);
1625 }
1626 }
Nicolas Prevot81948992014-05-16 18:25:26 +01001627 serializer.endTag(null, TAG_CROSS_PROFILE_INTENT_FILTERS);
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001628 }
1629
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001630 void writeDomainVerificationsLPr(XmlSerializer serializer,
1631 IntentFilterVerificationInfo verificationInfo)
1632 throws IllegalArgumentException, IllegalStateException, IOException {
1633 if (verificationInfo != null && verificationInfo.getPackageName() != null) {
1634 serializer.startTag(null, TAG_DOMAIN_VERIFICATION);
1635 verificationInfo.writeToXml(serializer);
Christopher Tate72c10a22015-06-12 18:31:24 -07001636 if (DEBUG_DOMAIN_VERIFICATION) {
1637 Slog.d(TAG, "Wrote domain verification for package: "
1638 + verificationInfo.getPackageName());
1639 }
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001640 serializer.endTag(null, TAG_DOMAIN_VERIFICATION);
1641 }
1642 }
1643
Christopher Tate6038d152015-06-17 13:07:46 -07001644 // Specifically for backup/restore
1645 void writeAllDomainVerificationsLPr(XmlSerializer serializer, int userId)
1646 throws IllegalArgumentException, IllegalStateException, IOException {
1647 serializer.startTag(null, TAG_ALL_INTENT_FILTER_VERIFICATION);
1648 final int N = mPackages.size();
1649 for (int i = 0; i < N; i++) {
1650 PackageSetting ps = mPackages.valueAt(i);
1651 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
1652 if (ivi != null) {
1653 writeDomainVerificationsLPr(serializer, ivi);
1654 }
1655 }
1656 serializer.endTag(null, TAG_ALL_INTENT_FILTER_VERIFICATION);
1657 }
1658
1659 // Specifically for backup/restore
1660 void readAllDomainVerificationsLPr(XmlPullParser parser, int userId)
1661 throws XmlPullParserException, IOException {
1662 mRestoredIntentFilterVerifications.clear();
1663
1664 int outerDepth = parser.getDepth();
1665 int type;
1666 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1667 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1668 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1669 continue;
1670 }
1671
1672 String tagName = parser.getName();
1673 if (tagName.equals(TAG_DOMAIN_VERIFICATION)) {
1674 IntentFilterVerificationInfo ivi = new IntentFilterVerificationInfo(parser);
1675 final String pkgName = ivi.getPackageName();
1676 final PackageSetting ps = mPackages.get(pkgName);
1677 if (ps != null) {
1678 // known/existing package; update in place
1679 ps.setIntentFilterVerificationInfo(ivi);
1680 if (DEBUG_DOMAIN_VERIFICATION) {
1681 Slog.d(TAG, "Restored IVI for existing app " + pkgName
1682 + " status=" + ivi.getStatusString());
1683 }
1684 } else {
1685 mRestoredIntentFilterVerifications.put(pkgName, ivi);
1686 if (DEBUG_DOMAIN_VERIFICATION) {
1687 Slog.d(TAG, "Restored IVI for pending app " + pkgName
1688 + " status=" + ivi.getStatusString());
1689 }
1690 }
1691 } else {
1692 PackageManagerService.reportSettingsProblem(Log.WARN,
1693 "Unknown element under <all-intent-filter-verification>: "
1694 + parser.getName());
1695 XmlUtils.skipCurrentTag(parser);
1696 }
1697 }
1698 }
1699
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001700 void writeDefaultAppsLPr(XmlSerializer serializer, int userId)
1701 throws IllegalArgumentException, IllegalStateException, IOException {
1702 serializer.startTag(null, TAG_DEFAULT_APPS);
1703 String packageName = mDefaultBrowserApp.get(userId);
1704 if (!TextUtils.isEmpty(packageName)) {
1705 serializer.startTag(null, TAG_DEFAULT_BROWSER);
1706 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
1707 serializer.endTag(null, TAG_DEFAULT_BROWSER);
1708 }
1709 serializer.endTag(null, TAG_DEFAULT_APPS);
1710 }
1711
Amith Yamasani483f3b02012-03-13 16:08:00 -07001712 void writePackageRestrictionsLPr(int userId) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001713 if (DEBUG_MU) {
1714 Log.i(TAG, "Writing package restrictions for user=" + userId);
1715 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001716 // Keep the old stopped packages around until we know the new ones have
1717 // been successfully written.
Amith Yamasani483f3b02012-03-13 16:08:00 -07001718 File userPackagesStateFile = getUserPackagesStateFile(userId);
1719 File backupFile = getUserPackagesStateBackupFile(userId);
1720 new File(userPackagesStateFile.getParent()).mkdirs();
1721 if (userPackagesStateFile.exists()) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001722 // Presence of backup settings file indicates that we failed
1723 // to persist packages earlier. So preserve the older
1724 // backup for future reference since the current packages
1725 // might have been corrupted.
Amith Yamasani483f3b02012-03-13 16:08:00 -07001726 if (!backupFile.exists()) {
1727 if (!userPackagesStateFile.renameTo(backupFile)) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07001728 Slog.wtf(PackageManagerService.TAG,
1729 "Unable to backup user packages state file, "
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001730 + "current changes will be lost at reboot");
1731 return;
1732 }
1733 } else {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001734 userPackagesStateFile.delete();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001735 Slog.w(PackageManagerService.TAG, "Preserving older stopped packages backup");
1736 }
1737 }
1738
1739 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001740 final FileOutputStream fstr = new FileOutputStream(userPackagesStateFile);
Kenny Root447106f2011-03-23 11:00:15 -07001741 final BufferedOutputStream str = new BufferedOutputStream(fstr);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001742
Kenny Root447106f2011-03-23 11:00:15 -07001743 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001744 serializer.setOutput(str, StandardCharsets.UTF_8.name());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001745 serializer.startDocument(null, true);
1746 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1747
Amith Yamasani483f3b02012-03-13 16:08:00 -07001748 serializer.startTag(null, TAG_PACKAGE_RESTRICTIONS);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001749
Kenny Root447106f2011-03-23 11:00:15 -07001750 for (final PackageSetting pkg : mPackages.values()) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001751 PackageUserState ustate = pkg.readUserState(userId);
1752 if (ustate.stopped || ustate.notLaunched || !ustate.installed
1753 || ustate.enabled != COMPONENT_ENABLED_STATE_DEFAULT
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001754 || ustate.hidden
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001755 || (ustate.enabledComponents != null
1756 && ustate.enabledComponents.size() > 0)
1757 || (ustate.disabledComponents != null
Kenny Guyc13053b2014-05-29 14:17:17 +01001758 && ustate.disabledComponents.size() > 0)
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001759 || ustate.blockUninstall
1760 || (ustate.domainVerificationStatus !=
1761 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED)) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001762 serializer.startTag(null, TAG_PACKAGE);
1763 serializer.attribute(null, ATTR_NAME, pkg.name);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001764 if (DEBUG_MU) Log.i(TAG, " pkg=" + pkg.name + ", state=" + ustate.enabled);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001765
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001766 if (!ustate.installed) {
1767 serializer.attribute(null, ATTR_INSTALLED, "false");
1768 }
1769 if (ustate.stopped) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001770 serializer.attribute(null, ATTR_STOPPED, "true");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001771 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001772 if (ustate.notLaunched) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001773 serializer.attribute(null, ATTR_NOT_LAUNCHED, "true");
1774 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001775 if (ustate.hidden) {
1776 serializer.attribute(null, ATTR_HIDDEN, "true");
Amith Yamasani655d0e22013-06-12 14:19:10 -07001777 }
Kenny Guyc13053b2014-05-29 14:17:17 +01001778 if (ustate.blockUninstall) {
1779 serializer.attribute(null, ATTR_BLOCK_UNINSTALL, "true");
1780 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001781 if (ustate.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
1782 serializer.attribute(null, ATTR_ENABLED,
1783 Integer.toString(ustate.enabled));
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07001784 if (ustate.lastDisableAppCaller != null) {
1785 serializer.attribute(null, ATTR_ENABLED_CALLER,
1786 ustate.lastDisableAppCaller);
1787 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07001788 }
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001789 if (ustate.domainVerificationStatus !=
1790 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
1791 serializer.attribute(null, ATTR_DOMAIN_VERIFICATON_STATE,
1792 Integer.toString(ustate.domainVerificationStatus));
1793 }
Christopher Tatef0d6cb32015-07-10 17:44:53 -07001794 if (ustate.appLinkGeneration != 0) {
1795 serializer.attribute(null, ATTR_APP_LINK_GENERATION,
1796 Integer.toString(ustate.appLinkGeneration));
1797 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001798 if (ustate.enabledComponents != null
1799 && ustate.enabledComponents.size() > 0) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001800 serializer.startTag(null, TAG_ENABLED_COMPONENTS);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001801 for (final String name : ustate.enabledComponents) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001802 serializer.startTag(null, TAG_ITEM);
1803 serializer.attribute(null, ATTR_NAME, name);
1804 serializer.endTag(null, TAG_ITEM);
1805 }
1806 serializer.endTag(null, TAG_ENABLED_COMPONENTS);
1807 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001808 if (ustate.disabledComponents != null
1809 && ustate.disabledComponents.size() > 0) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001810 serializer.startTag(null, TAG_DISABLED_COMPONENTS);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001811 for (final String name : ustate.disabledComponents) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001812 serializer.startTag(null, TAG_ITEM);
1813 serializer.attribute(null, ATTR_NAME, name);
1814 serializer.endTag(null, TAG_ITEM);
1815 }
1816 serializer.endTag(null, TAG_DISABLED_COMPONENTS);
1817 }
Svetoslavc6d1c342015-02-26 14:44:43 -08001818
Amith Yamasani483f3b02012-03-13 16:08:00 -07001819 serializer.endTag(null, TAG_PACKAGE);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001820 }
1821 }
1822
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08001823 writePreferredActivitiesLPr(serializer, userId, true);
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001824 writePersistentPreferredActivitiesLPr(serializer, userId);
Nicolas Prevot81948992014-05-16 18:25:26 +01001825 writeCrossProfileIntentFiltersLPr(serializer, userId);
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001826 writeDefaultAppsLPr(serializer, userId);
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001827
Amith Yamasani483f3b02012-03-13 16:08:00 -07001828 serializer.endTag(null, TAG_PACKAGE_RESTRICTIONS);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001829
1830 serializer.endDocument();
1831
1832 str.flush();
1833 FileUtils.sync(fstr);
1834 str.close();
1835
1836 // New settings successfully written, old ones are no longer
1837 // needed.
Amith Yamasani483f3b02012-03-13 16:08:00 -07001838 backupFile.delete();
1839 FileUtils.setPermissions(userPackagesStateFile.toString(),
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001840 FileUtils.S_IRUSR|FileUtils.S_IWUSR
Nick Kralevich70522ad2012-01-06 13:58:01 -08001841 |FileUtils.S_IRGRP|FileUtils.S_IWGRP,
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001842 -1, -1);
1843
1844 // Done, all is good!
1845 return;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001846 } catch(java.io.IOException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07001847 Slog.wtf(PackageManagerService.TAG,
Amith Yamasani483f3b02012-03-13 16:08:00 -07001848 "Unable to write package manager user packages state, "
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001849 + " current changes will be lost at reboot", e);
1850 }
1851
1852 // Clean up partially written files
Amith Yamasani483f3b02012-03-13 16:08:00 -07001853 if (userPackagesStateFile.exists()) {
1854 if (!userPackagesStateFile.delete()) {
1855 Log.i(PackageManagerService.TAG, "Failed to clean up mangled file: "
1856 + mStoppedPackagesFilename);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001857 }
1858 }
1859 }
1860
Svetoslavc6d1c342015-02-26 14:44:43 -08001861 void readInstallPermissionsLPr(XmlPullParser parser,
1862 PermissionsState permissionsState) throws IOException, XmlPullParserException {
1863 int outerDepth = parser.getDepth();
1864 int type;
1865 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1866 && (type != XmlPullParser.END_TAG
1867 || parser.getDepth() > outerDepth)) {
1868 if (type == XmlPullParser.END_TAG
1869 || type == XmlPullParser.TEXT) {
1870 continue;
1871 }
1872 String tagName = parser.getName();
1873 if (tagName.equals(TAG_ITEM)) {
1874 String name = parser.getAttributeValue(null, ATTR_NAME);
1875
1876 BasePermission bp = mPermissions.get(name);
1877 if (bp == null) {
1878 Slog.w(PackageManagerService.TAG, "Unknown permission: " + name);
1879 XmlUtils.skipCurrentTag(parser);
1880 continue;
1881 }
1882
Svet Ganov8c7f7002015-05-07 10:48:44 -07001883 String grantedStr = parser.getAttributeValue(null, ATTR_GRANTED);
1884 final boolean granted = grantedStr == null
1885 || Boolean.parseBoolean(grantedStr);
1886
1887 String flagsStr = parser.getAttributeValue(null, ATTR_FLAGS);
1888 final int flags = (flagsStr != null)
1889 ? Integer.parseInt(flagsStr, 16) : 0;
1890
1891 if (granted) {
1892 if (permissionsState.grantInstallPermission(bp) ==
1893 PermissionsState.PERMISSION_OPERATION_FAILURE) {
1894 Slog.w(PackageManagerService.TAG, "Permission already added: " + name);
1895 XmlUtils.skipCurrentTag(parser);
1896 } else {
1897 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
1898 PackageManager.MASK_PERMISSION_FLAGS, flags);
1899 }
1900 } else {
1901 if (permissionsState.revokeInstallPermission(bp) ==
1902 PermissionsState.PERMISSION_OPERATION_FAILURE) {
1903 Slog.w(PackageManagerService.TAG, "Permission already added: " + name);
1904 XmlUtils.skipCurrentTag(parser);
1905 } else {
1906 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
1907 PackageManager.MASK_PERMISSION_FLAGS, flags);
1908 }
Svetoslavc6d1c342015-02-26 14:44:43 -08001909 }
1910 } else {
1911 Slog.w(PackageManagerService.TAG, "Unknown element under <permissions>: "
1912 + parser.getName());
1913 XmlUtils.skipCurrentTag(parser);
1914 }
1915 }
1916 }
1917
Svet Ganov8c7f7002015-05-07 10:48:44 -07001918 void writePermissionsLPr(XmlSerializer serializer, List<PermissionState> permissionStates)
Svetoslavc6d1c342015-02-26 14:44:43 -08001919 throws IOException {
Svet Ganov8c7f7002015-05-07 10:48:44 -07001920 if (permissionStates.isEmpty()) {
Svetoslavc6d1c342015-02-26 14:44:43 -08001921 return;
1922 }
1923
1924 serializer.startTag(null, TAG_PERMISSIONS);
1925
Svet Ganov8c7f7002015-05-07 10:48:44 -07001926 for (PermissionState permissionState : permissionStates) {
Svetoslavc6d1c342015-02-26 14:44:43 -08001927 serializer.startTag(null, TAG_ITEM);
Svet Ganov8c7f7002015-05-07 10:48:44 -07001928 serializer.attribute(null, ATTR_NAME, permissionState.getName());
1929 serializer.attribute(null, ATTR_GRANTED, String.valueOf(permissionState.isGranted()));
1930 serializer.attribute(null, ATTR_FLAGS, Integer.toHexString(permissionState.getFlags()));
Svetoslavc6d1c342015-02-26 14:44:43 -08001931 serializer.endTag(null, TAG_ITEM);
1932 }
1933
1934 serializer.endTag(null, TAG_PERMISSIONS);
1935 }
1936
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001937 // Note: assumed "stopped" field is already cleared in all packages.
Amith Yamasani483f3b02012-03-13 16:08:00 -07001938 // Legacy reader, used to read in the old file format after an upgrade. Not used after that.
Kenny Root447106f2011-03-23 11:00:15 -07001939 void readStoppedLPw() {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001940 FileInputStream str = null;
1941 if (mBackupStoppedPackagesFilename.exists()) {
1942 try {
1943 str = new FileInputStream(mBackupStoppedPackagesFilename);
1944 mReadMessages.append("Reading from backup stopped packages file\n");
Amith Yamasani483f3b02012-03-13 16:08:00 -07001945 PackageManagerService.reportSettingsProblem(Log.INFO,
1946 "Need to read from backup stopped packages file");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001947 if (mSettingsFilename.exists()) {
1948 // If both the backup and normal file exist, we
1949 // ignore the normal one since it might have been
1950 // corrupted.
1951 Slog.w(PackageManagerService.TAG, "Cleaning up stopped packages file "
1952 + mStoppedPackagesFilename);
1953 mStoppedPackagesFilename.delete();
1954 }
1955 } catch (java.io.IOException e) {
1956 // We'll try for the normal settings file.
1957 }
1958 }
1959
1960 try {
1961 if (str == null) {
1962 if (!mStoppedPackagesFilename.exists()) {
1963 mReadMessages.append("No stopped packages file found\n");
Amith Yamasani483f3b02012-03-13 16:08:00 -07001964 PackageManagerService.reportSettingsProblem(Log.INFO,
1965 "No stopped packages file file; assuming all started");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001966 // At first boot, make sure no packages are stopped.
1967 // We usually want to have third party apps initialize
1968 // in the stopped state, but not at first boot.
1969 for (PackageSetting pkg : mPackages.values()) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001970 pkg.setStopped(false, 0);
1971 pkg.setNotLaunched(false, 0);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001972 }
1973 return;
1974 }
1975 str = new FileInputStream(mStoppedPackagesFilename);
1976 }
Kenny Root447106f2011-03-23 11:00:15 -07001977 final XmlPullParser parser = Xml.newPullParser();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001978 parser.setInput(str, null);
1979
1980 int type;
1981 while ((type=parser.next()) != XmlPullParser.START_TAG
1982 && type != XmlPullParser.END_DOCUMENT) {
1983 ;
1984 }
1985
1986 if (type != XmlPullParser.START_TAG) {
1987 mReadMessages.append("No start tag found in stopped packages file\n");
1988 PackageManagerService.reportSettingsProblem(Log.WARN,
1989 "No start tag found in package manager stopped packages");
1990 return;
1991 }
1992
1993 int outerDepth = parser.getDepth();
1994 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1995 && (type != XmlPullParser.END_TAG
1996 || parser.getDepth() > outerDepth)) {
1997 if (type == XmlPullParser.END_TAG
1998 || type == XmlPullParser.TEXT) {
1999 continue;
2000 }
2001
2002 String tagName = parser.getName();
Amith Yamasani483f3b02012-03-13 16:08:00 -07002003 if (tagName.equals(TAG_PACKAGE)) {
2004 String name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002005 PackageSetting ps = mPackages.get(name);
2006 if (ps != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002007 ps.setStopped(true, 0);
2008 if ("1".equals(parser.getAttributeValue(null, ATTR_NOT_LAUNCHED))) {
2009 ps.setNotLaunched(true, 0);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002010 }
2011 } else {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002012 Slog.w(PackageManagerService.TAG,
2013 "No package known for stopped package: " + name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002014 }
2015 XmlUtils.skipCurrentTag(parser);
2016 } else {
2017 Slog.w(PackageManagerService.TAG, "Unknown element under <stopped-packages>: "
2018 + parser.getName());
2019 XmlUtils.skipCurrentTag(parser);
2020 }
2021 }
2022
2023 str.close();
2024
Amith Yamasani483f3b02012-03-13 16:08:00 -07002025 } catch (XmlPullParserException e) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002026 mReadMessages.append("Error reading: " + e.toString());
Amith Yamasani483f3b02012-03-13 16:08:00 -07002027 PackageManagerService.reportSettingsProblem(Log.ERROR,
2028 "Error reading stopped packages: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07002029 Slog.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages",
2030 e);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002031
Amith Yamasani483f3b02012-03-13 16:08:00 -07002032 } catch (java.io.IOException e) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002033 mReadMessages.append("Error reading: " + e.toString());
2034 PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07002035 Slog.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages",
2036 e);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002037
2038 }
2039 }
2040
Kenny Root447106f2011-03-23 11:00:15 -07002041 void writeLPr() {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002042 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
2043
2044 // Keep the old settings around until we know the new ones have
2045 // been successfully written.
2046 if (mSettingsFilename.exists()) {
2047 // Presence of backup settings file indicates that we failed
2048 // to persist settings earlier. So preserve the older
2049 // backup for future reference since the current settings
2050 // might have been corrupted.
2051 if (!mBackupSettingsFilename.exists()) {
2052 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002053 Slog.wtf(PackageManagerService.TAG,
2054 "Unable to backup package manager settings, "
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002055 + " current changes will be lost at reboot");
2056 return;
2057 }
2058 } else {
2059 mSettingsFilename.delete();
2060 Slog.w(PackageManagerService.TAG, "Preserving older settings backup");
2061 }
2062 }
2063
2064 mPastSignatures.clear();
2065
2066 try {
2067 FileOutputStream fstr = new FileOutputStream(mSettingsFilename);
2068 BufferedOutputStream str = new BufferedOutputStream(fstr);
2069
2070 //XmlSerializer serializer = XmlUtils.serializerInstance();
2071 XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002072 serializer.setOutput(str, StandardCharsets.UTF_8.name());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002073 serializer.startDocument(null, true);
2074 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2075
2076 serializer.startTag(null, "packages");
2077
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07002078 for (int i = 0; i < mVersion.size(); i++) {
2079 final String volumeUuid = mVersion.keyAt(i);
2080 final VersionInfo ver = mVersion.valueAt(i);
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07002081
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07002082 serializer.startTag(null, TAG_VERSION);
2083 XmlUtils.writeStringAttribute(serializer, ATTR_VOLUME_UUID, volumeUuid);
2084 XmlUtils.writeIntAttribute(serializer, ATTR_SDK_VERSION, ver.sdkVersion);
2085 XmlUtils.writeIntAttribute(serializer, ATTR_DATABASE_VERSION, ver.databaseVersion);
2086 XmlUtils.writeStringAttribute(serializer, ATTR_FINGERPRINT, ver.fingerprint);
2087 serializer.endTag(null, TAG_VERSION);
2088 }
Kenny Rootc1c0d3c2014-04-24 13:36:40 -07002089
Kenny Root0aaa0d92011-09-12 16:42:55 -07002090 if (mVerifierDeviceIdentity != null) {
2091 serializer.startTag(null, "verifier");
2092 serializer.attribute(null, "device", mVerifierDeviceIdentity.toString());
2093 serializer.endTag(null, "verifier");
2094 }
2095
Jeff Sharkeyf5385772012-05-11 14:04:41 -07002096 if (mReadExternalStorageEnforced != null) {
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07002097 serializer.startTag(null, TAG_READ_EXTERNAL_STORAGE);
2098 serializer.attribute(
Jeff Sharkey5d32e772012-04-12 15:59:23 -07002099 null, ATTR_ENFORCEMENT, mReadExternalStorageEnforced ? "1" : "0");
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07002100 serializer.endTag(null, TAG_READ_EXTERNAL_STORAGE);
2101 }
2102
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002103 serializer.startTag(null, "permission-trees");
2104 for (BasePermission bp : mPermissionTrees.values()) {
Kenny Root447106f2011-03-23 11:00:15 -07002105 writePermissionLPr(serializer, bp);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002106 }
2107 serializer.endTag(null, "permission-trees");
2108
2109 serializer.startTag(null, "permissions");
2110 for (BasePermission bp : mPermissions.values()) {
Kenny Root447106f2011-03-23 11:00:15 -07002111 writePermissionLPr(serializer, bp);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002112 }
2113 serializer.endTag(null, "permissions");
2114
Kenny Root447106f2011-03-23 11:00:15 -07002115 for (final PackageSetting pkg : mPackages.values()) {
2116 writePackageLPr(serializer, pkg);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002117 }
2118
Kenny Root447106f2011-03-23 11:00:15 -07002119 for (final PackageSetting pkg : mDisabledSysPackages.values()) {
2120 writeDisabledSysPackageLPr(serializer, pkg);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002121 }
2122
Kenny Root447106f2011-03-23 11:00:15 -07002123 for (final SharedUserSetting usr : mSharedUsers.values()) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002124 serializer.startTag(null, "shared-user");
Amith Yamasani483f3b02012-03-13 16:08:00 -07002125 serializer.attribute(null, ATTR_NAME, usr.name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002126 serializer.attribute(null, "userId",
2127 Integer.toString(usr.userId));
2128 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
Svet Ganov8c7f7002015-05-07 10:48:44 -07002129 writePermissionsLPr(serializer, usr.getPermissionsState()
2130 .getInstallPermissionStates());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002131 serializer.endTag(null, "shared-user");
2132 }
2133
2134 if (mPackagesToBeCleaned.size() > 0) {
Jeff Sharkey752cd922012-09-23 16:25:12 -07002135 for (PackageCleanItem item : mPackagesToBeCleaned) {
2136 final String userStr = Integer.toString(item.userId);
2137 serializer.startTag(null, "cleaning-package");
2138 serializer.attribute(null, ATTR_NAME, item.packageName);
2139 serializer.attribute(null, ATTR_CODE, item.andCode ? "true" : "false");
2140 serializer.attribute(null, ATTR_USER, userStr);
2141 serializer.endTag(null, "cleaning-package");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002142 }
2143 }
Svetoslavc6d1c342015-02-26 14:44:43 -08002144
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002145 if (mRenamedPackages.size() > 0) {
Andy McFadden2f362292012-01-20 14:43:38 -08002146 for (Map.Entry<String, String> e : mRenamedPackages.entrySet()) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002147 serializer.startTag(null, "renamed-package");
2148 serializer.attribute(null, "new", e.getKey());
2149 serializer.attribute(null, "old", e.getValue());
2150 serializer.endTag(null, "renamed-package");
2151 }
2152 }
Svetoslavc6d1c342015-02-26 14:44:43 -08002153
Christopher Tate6038d152015-06-17 13:07:46 -07002154 final int numIVIs = mRestoredIntentFilterVerifications.size();
2155 if (numIVIs > 0) {
2156 if (DEBUG_DOMAIN_VERIFICATION) {
2157 Slog.i(TAG, "Writing restored-ivi entries to packages.xml");
2158 }
2159 serializer.startTag(null, "restored-ivi");
2160 for (int i = 0; i < numIVIs; i++) {
2161 IntentFilterVerificationInfo ivi = mRestoredIntentFilterVerifications.valueAt(i);
2162 writeDomainVerificationsLPr(serializer, ivi);
2163 }
2164 serializer.endTag(null, "restored-ivi");
2165 } else {
2166 if (DEBUG_DOMAIN_VERIFICATION) {
2167 Slog.i(TAG, " no restored IVI entries to write");
2168 }
2169 }
2170
dcashman55b10782014-04-09 14:20:38 -07002171 mKeySetManagerService.writeKeySetManagerServiceLPr(serializer);
Geremy Condraf1bcca82013-01-07 22:35:24 -08002172
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002173 serializer.endTag(null, "packages");
2174
2175 serializer.endDocument();
2176
2177 str.flush();
2178 FileUtils.sync(fstr);
2179 str.close();
2180
2181 // New settings successfully written, old ones are no longer
2182 // needed.
2183 mBackupSettingsFilename.delete();
2184 FileUtils.setPermissions(mSettingsFilename.toString(),
2185 FileUtils.S_IRUSR|FileUtils.S_IWUSR
Nick Kralevich70522ad2012-01-06 13:58:01 -08002186 |FileUtils.S_IRGRP|FileUtils.S_IWGRP,
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002187 -1, -1);
2188
Jeff Sharkey91edde22015-05-20 12:04:42 -07002189 writePackageListLPr();
Amith Yamasani483f3b02012-03-13 16:08:00 -07002190 writeAllUsersPackageRestrictionsLPr();
Svetoslavc6d1c342015-02-26 14:44:43 -08002191 writeAllRuntimePermissionsLPr();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002192 return;
2193
2194 } catch(XmlPullParserException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002195 Slog.wtf(PackageManagerService.TAG, "Unable to write package manager settings, "
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002196 + "current changes will be lost at reboot", e);
2197 } catch(java.io.IOException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002198 Slog.wtf(PackageManagerService.TAG, "Unable to write package manager settings, "
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002199 + "current changes will be lost at reboot", e);
2200 }
2201 // Clean up partially written files
2202 if (mSettingsFilename.exists()) {
2203 if (!mSettingsFilename.delete()) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002204 Slog.wtf(PackageManagerService.TAG, "Failed to clean up mangled file: "
Amith Yamasani483f3b02012-03-13 16:08:00 -07002205 + mSettingsFilename);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002206 }
2207 }
2208 //Debug.stopMethodTracing();
2209 }
2210
Jeff Sharkey91edde22015-05-20 12:04:42 -07002211 void writePackageListLPr() {
2212 writePackageListLPr(-1);
2213 }
2214
2215 void writePackageListLPr(int creatingUserId) {
2216 // Only derive GIDs for active users (not dying)
2217 final List<UserInfo> users = UserManagerService.getInstance().getUsers(true);
2218 int[] userIds = new int[users.size()];
2219 for (int i = 0; i < userIds.length; i++) {
2220 userIds[i] = users.get(i).id;
2221 }
2222 if (creatingUserId != -1) {
2223 userIds = ArrayUtils.appendInt(userIds, creatingUserId);
2224 }
2225
2226 // Write package list file now, use a JournaledFile.
2227 File tempFile = new File(mPackageListFilename.getAbsolutePath() + ".tmp");
2228 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
2229
2230 final File writeTarget = journal.chooseForWrite();
2231 FileOutputStream fstr = null;
2232 BufferedOutputStream str = null;
2233 try {
2234 fstr = new FileOutputStream(writeTarget);
2235 str = new BufferedOutputStream(fstr);
2236 FileUtils.setPermissions(fstr.getFD(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
2237
2238 StringBuilder sb = new StringBuilder();
2239 for (final PackageSetting pkg : mPackages.values()) {
2240 if (pkg.pkg == null || pkg.pkg.applicationInfo == null) {
2241 Slog.w(TAG, "Skipping " + pkg + " due to missing metadata");
2242 continue;
2243 }
2244
2245 final ApplicationInfo ai = pkg.pkg.applicationInfo;
Oleksiy Vyalov466ecdb2015-06-12 13:27:12 -07002246 final String dataPath = new File(ai.dataDir).getCanonicalPath();
Jeff Sharkey91edde22015-05-20 12:04:42 -07002247 final boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
2248 final int[] gids = pkg.getPermissionsState().computeGids(userIds);
2249
2250 // Avoid any application that has a space in its path.
2251 if (dataPath.indexOf(" ") >= 0)
2252 continue;
2253
2254 // we store on each line the following information for now:
2255 //
2256 // pkgName - package name
2257 // userId - application-specific user id
2258 // debugFlag - 0 or 1 if the package is debuggable.
2259 // dataPath - path to package's data path
2260 // seinfo - seinfo label for the app (assigned at install time)
2261 // gids - supplementary gids this app launches with
2262 //
2263 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
2264 //
2265 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
2266 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
2267 // system/core/logd/LogStatistics.cpp
2268 // system/core/run-as/run-as.c
2269 // system/core/sdcard/sdcard.c
2270 // external/libselinux/src/android.c:package_info_init()
2271 //
2272 sb.setLength(0);
2273 sb.append(ai.packageName);
2274 sb.append(" ");
2275 sb.append((int)ai.uid);
2276 sb.append(isDebug ? " 1 " : " 0 ");
2277 sb.append(dataPath);
2278 sb.append(" ");
2279 sb.append(ai.seinfo);
2280 sb.append(" ");
2281 if (gids != null && gids.length > 0) {
2282 sb.append(gids[0]);
2283 for (int i = 1; i < gids.length; i++) {
2284 sb.append(",");
2285 sb.append(gids[i]);
2286 }
2287 } else {
2288 sb.append("none");
2289 }
2290 sb.append("\n");
2291 str.write(sb.toString().getBytes());
2292 }
2293 str.flush();
2294 FileUtils.sync(fstr);
2295 str.close();
2296 journal.commit();
2297 } catch (Exception e) {
2298 Slog.wtf(TAG, "Failed to write packages.list", e);
2299 IoUtils.closeQuietly(str);
2300 journal.rollback();
2301 }
2302 }
2303
Kenny Root447106f2011-03-23 11:00:15 -07002304 void writeDisabledSysPackageLPr(XmlSerializer serializer, final PackageSetting pkg)
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002305 throws java.io.IOException {
2306 serializer.startTag(null, "updated-package");
Amith Yamasani483f3b02012-03-13 16:08:00 -07002307 serializer.attribute(null, ATTR_NAME, pkg.name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002308 if (pkg.realName != null) {
2309 serializer.attribute(null, "realName", pkg.realName);
2310 }
2311 serializer.attribute(null, "codePath", pkg.codePathString);
2312 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
2313 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
2314 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
2315 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
2316 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
2317 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
2318 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002319 if (pkg.legacyNativeLibraryPathString != null) {
2320 serializer.attribute(null, "nativeLibraryPath", pkg.legacyNativeLibraryPathString);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002321 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002322 if (pkg.primaryCpuAbiString != null) {
2323 serializer.attribute(null, "primaryCpuAbi", pkg.primaryCpuAbiString);
Narayan Kamath9e289d72014-04-10 09:26:59 +00002324 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002325 if (pkg.secondaryCpuAbiString != null) {
2326 serializer.attribute(null, "secondaryCpuAbi", pkg.secondaryCpuAbiString);
2327 }
Narayan Kamath4903f642014-08-11 13:33:45 +01002328 if (pkg.cpuAbiOverrideString != null) {
2329 serializer.attribute(null, "cpuAbiOverride", pkg.cpuAbiOverrideString);
2330 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002331
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002332 if (pkg.sharedUser == null) {
Amith Yamasani13593602012-03-22 16:16:17 -07002333 serializer.attribute(null, "userId", Integer.toString(pkg.appId));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002334 } else {
Amith Yamasani13593602012-03-22 16:16:17 -07002335 serializer.attribute(null, "sharedUserId", Integer.toString(pkg.appId));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002336 }
Svetoslavc6d1c342015-02-26 14:44:43 -08002337
2338 // If this is a shared user, the permissions will be written there.
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002339 if (pkg.sharedUser == null) {
Svet Ganov8c7f7002015-05-07 10:48:44 -07002340 writePermissionsLPr(serializer, pkg.getPermissionsState()
2341 .getInstallPermissionStates());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002342 }
Svetoslavc6d1c342015-02-26 14:44:43 -08002343
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002344 serializer.endTag(null, "updated-package");
2345 }
2346
Kenny Root447106f2011-03-23 11:00:15 -07002347 void writePackageLPr(XmlSerializer serializer, final PackageSetting pkg)
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002348 throws java.io.IOException {
2349 serializer.startTag(null, "package");
Amith Yamasani483f3b02012-03-13 16:08:00 -07002350 serializer.attribute(null, ATTR_NAME, pkg.name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002351 if (pkg.realName != null) {
2352 serializer.attribute(null, "realName", pkg.realName);
2353 }
2354 serializer.attribute(null, "codePath", pkg.codePathString);
2355 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
2356 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
2357 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002358
2359 if (pkg.legacyNativeLibraryPathString != null) {
2360 serializer.attribute(null, "nativeLibraryPath", pkg.legacyNativeLibraryPathString);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002361 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002362 if (pkg.primaryCpuAbiString != null) {
2363 serializer.attribute(null, "primaryCpuAbi", pkg.primaryCpuAbiString);
Narayan Kamath9e289d72014-04-10 09:26:59 +00002364 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002365 if (pkg.secondaryCpuAbiString != null) {
2366 serializer.attribute(null, "secondaryCpuAbi", pkg.secondaryCpuAbiString);
2367 }
Narayan Kamath4903f642014-08-11 13:33:45 +01002368 if (pkg.cpuAbiOverrideString != null) {
2369 serializer.attribute(null, "cpuAbiOverride", pkg.cpuAbiOverrideString);
2370 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002371
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002372 serializer.attribute(null, "publicFlags", Integer.toString(pkg.pkgFlags));
2373 serializer.attribute(null, "privateFlags", Integer.toString(pkg.pkgPrivateFlags));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002374 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
2375 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
2376 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
2377 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
2378 if (pkg.sharedUser == null) {
Amith Yamasani13593602012-03-22 16:16:17 -07002379 serializer.attribute(null, "userId", Integer.toString(pkg.appId));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002380 } else {
Amith Yamasani13593602012-03-22 16:16:17 -07002381 serializer.attribute(null, "sharedUserId", Integer.toString(pkg.appId));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002382 }
2383 if (pkg.uidError) {
2384 serializer.attribute(null, "uidError", "true");
2385 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002386 if (pkg.installStatus == PackageSettingBase.PKG_INSTALL_INCOMPLETE) {
2387 serializer.attribute(null, "installStatus", "false");
2388 }
2389 if (pkg.installerPackageName != null) {
2390 serializer.attribute(null, "installer", pkg.installerPackageName);
2391 }
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07002392 if (pkg.volumeUuid != null) {
2393 serializer.attribute(null, "volumeUuid", pkg.volumeUuid);
2394 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002395 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
Svet Ganov8c7f7002015-05-07 10:48:44 -07002396
2397 writePermissionsLPr(serializer, pkg.getPermissionsState()
2398 .getInstallPermissionStates());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002399
dcashman8c04fac2015-03-23 11:39:42 -07002400 writeSigningKeySetLPr(serializer, pkg.keySetData);
dcashman55b10782014-04-09 14:20:38 -07002401 writeUpgradeKeySetsLPr(serializer, pkg.keySetData);
Geremy Condraf1bcca82013-01-07 22:35:24 -08002402 writeKeySetAliasesLPr(serializer, pkg.keySetData);
Fabrice Di Meglio62271722015-04-10 17:24:02 -07002403 writeDomainVerificationsLPr(serializer, pkg.verificationInfo);
Geremy Condraf1bcca82013-01-07 22:35:24 -08002404
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002405 serializer.endTag(null, "package");
2406 }
2407
dcashman8c04fac2015-03-23 11:39:42 -07002408 void writeSigningKeySetLPr(XmlSerializer serializer,
Geremy Condraf1bcca82013-01-07 22:35:24 -08002409 PackageKeySetData data) throws IOException {
dcashman8c04fac2015-03-23 11:39:42 -07002410 serializer.startTag(null, "proper-signing-keyset");
2411 serializer.attribute(null, "identifier",
2412 Long.toString(data.getProperSigningKeySet()));
2413 serializer.endTag(null, "proper-signing-keyset");
dcashman55b10782014-04-09 14:20:38 -07002414 }
2415
2416 void writeUpgradeKeySetsLPr(XmlSerializer serializer,
2417 PackageKeySetData data) throws IOException {
dcashman8c04fac2015-03-23 11:39:42 -07002418 long properSigning = data.getProperSigningKeySet();
dcashman55b10782014-04-09 14:20:38 -07002419 if (data.isUsingUpgradeKeySets()) {
2420 for (long id : data.getUpgradeKeySets()) {
2421 serializer.startTag(null, "upgrade-keyset");
2422 serializer.attribute(null, "identifier", Long.toString(id));
2423 serializer.endTag(null, "upgrade-keyset");
2424 }
Geremy Condraf1bcca82013-01-07 22:35:24 -08002425 }
2426 }
2427
2428 void writeKeySetAliasesLPr(XmlSerializer serializer,
2429 PackageKeySetData data) throws IOException {
2430 for (Map.Entry<String, Long> e: data.getAliases().entrySet()) {
2431 serializer.startTag(null, "defined-keyset");
2432 serializer.attribute(null, "alias", e.getKey());
2433 serializer.attribute(null, "identifier", Long.toString(e.getValue()));
2434 serializer.endTag(null, "defined-keyset");
2435 }
2436 }
2437
Kenny Root447106f2011-03-23 11:00:15 -07002438 void writePermissionLPr(XmlSerializer serializer, BasePermission bp)
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002439 throws XmlPullParserException, java.io.IOException {
2440 if (bp.type != BasePermission.TYPE_BUILTIN && bp.sourcePackage != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002441 serializer.startTag(null, TAG_ITEM);
2442 serializer.attribute(null, ATTR_NAME, bp.name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002443 serializer.attribute(null, "package", bp.sourcePackage);
2444 if (bp.protectionLevel != PermissionInfo.PROTECTION_NORMAL) {
2445 serializer.attribute(null, "protection", Integer.toString(bp.protectionLevel));
2446 }
2447 if (PackageManagerService.DEBUG_SETTINGS)
2448 Log.v(PackageManagerService.TAG, "Writing perm: name=" + bp.name + " type="
2449 + bp.type);
2450 if (bp.type == BasePermission.TYPE_DYNAMIC) {
Kenny Root447106f2011-03-23 11:00:15 -07002451 final PermissionInfo pi = bp.perm != null ? bp.perm.info : bp.pendingInfo;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002452 if (pi != null) {
2453 serializer.attribute(null, "type", "dynamic");
2454 if (pi.icon != 0) {
2455 serializer.attribute(null, "icon", Integer.toString(pi.icon));
2456 }
2457 if (pi.nonLocalizedLabel != null) {
2458 serializer.attribute(null, "label", pi.nonLocalizedLabel.toString());
2459 }
2460 }
2461 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07002462 serializer.endTag(null, TAG_ITEM);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002463 }
2464 }
2465
Kenny Root447106f2011-03-23 11:00:15 -07002466 ArrayList<PackageSetting> getListOfIncompleteInstallPackagesLPr() {
Jeff Sharkey9f837a92014-10-24 12:07:24 -07002467 final ArraySet<String> kList = new ArraySet<String>(mPackages.keySet());
Kenny Root447106f2011-03-23 11:00:15 -07002468 final Iterator<String> its = kList.iterator();
2469 final ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002470 while (its.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07002471 final String key = its.next();
2472 final PackageSetting ps = mPackages.get(key);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002473 if (ps.getInstallStatus() == PackageSettingBase.PKG_INSTALL_INCOMPLETE) {
2474 ret.add(ps);
2475 }
2476 }
2477 return ret;
2478 }
2479
Jeff Sharkey752cd922012-09-23 16:25:12 -07002480 void addPackageToCleanLPw(PackageCleanItem pkg) {
2481 if (!mPackagesToBeCleaned.contains(pkg)) {
2482 mPackagesToBeCleaned.add(pkg);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002483 }
2484 }
2485
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08002486 boolean readLPw(PackageManagerService service, List<UserInfo> users, int sdkVersion,
2487 boolean onlyCore) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002488 FileInputStream str = null;
2489 if (mBackupSettingsFilename.exists()) {
2490 try {
2491 str = new FileInputStream(mBackupSettingsFilename);
2492 mReadMessages.append("Reading from backup settings file\n");
2493 PackageManagerService.reportSettingsProblem(Log.INFO,
2494 "Need to read from backup settings file");
2495 if (mSettingsFilename.exists()) {
2496 // If both the backup and settings file exist, we
2497 // ignore the settings since it might have been
2498 // corrupted.
2499 Slog.w(PackageManagerService.TAG, "Cleaning up settings file "
2500 + mSettingsFilename);
2501 mSettingsFilename.delete();
2502 }
2503 } catch (java.io.IOException e) {
2504 // We'll try for the normal settings file.
2505 }
2506 }
2507
Kenny Root447106f2011-03-23 11:00:15 -07002508 mPendingPackages.clear();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002509 mPastSignatures.clear();
dcashman8c04fac2015-03-23 11:39:42 -07002510 mKeySetRefs.clear();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002511
2512 try {
2513 if (str == null) {
2514 if (!mSettingsFilename.exists()) {
2515 mReadMessages.append("No settings file found\n");
2516 PackageManagerService.reportSettingsProblem(Log.INFO,
2517 "No settings file; creating initial state");
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07002518 // It's enough to just touch version details to create them
2519 // with default values
2520 findOrCreateVersion(StorageManager.UUID_PRIVATE_INTERNAL);
2521 findOrCreateVersion(StorageManager.UUID_PRIMARY_PHYSICAL);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002522 return false;
2523 }
2524 str = new FileInputStream(mSettingsFilename);
2525 }
2526 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002527 parser.setInput(str, StandardCharsets.UTF_8.name());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002528
2529 int type;
2530 while ((type = parser.next()) != XmlPullParser.START_TAG
2531 && type != XmlPullParser.END_DOCUMENT) {
2532 ;
2533 }
2534
2535 if (type != XmlPullParser.START_TAG) {
2536 mReadMessages.append("No start tag found in settings file\n");
2537 PackageManagerService.reportSettingsProblem(Log.WARN,
2538 "No start tag found in package manager settings");
Dianne Hackborn8d051722014-10-01 14:59:58 -07002539 Slog.wtf(PackageManagerService.TAG,
Dianne Hackborn58f42a52011-10-10 13:46:34 -07002540 "No start tag found in package manager settings");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002541 return false;
2542 }
2543
2544 int outerDepth = parser.getDepth();
2545 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2546 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2547 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2548 continue;
2549 }
2550
2551 String tagName = parser.getName();
2552 if (tagName.equals("package")) {
Kenny Root447106f2011-03-23 11:00:15 -07002553 readPackageLPw(parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002554 } else if (tagName.equals("permissions")) {
Kenny Root447106f2011-03-23 11:00:15 -07002555 readPermissionsLPw(mPermissions, parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002556 } else if (tagName.equals("permission-trees")) {
Kenny Root447106f2011-03-23 11:00:15 -07002557 readPermissionsLPw(mPermissionTrees, parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002558 } else if (tagName.equals("shared-user")) {
Kenny Root447106f2011-03-23 11:00:15 -07002559 readSharedUserLPw(parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002560 } else if (tagName.equals("preferred-packages")) {
2561 // no longer used.
2562 } else if (tagName.equals("preferred-activities")) {
Dianne Hackborn63092712012-10-07 14:45:35 -07002563 // Upgrading from old single-user implementation;
2564 // these are the preferred activities for user 0.
2565 readPreferredActivitiesLPw(parser, 0);
Sander Alewijnseaf597622014-03-20 18:44:57 +00002566 } else if (tagName.equals(TAG_PERSISTENT_PREFERRED_ACTIVITIES)) {
Sander Alewijnsef475ca32014-02-17 15:13:58 +00002567 // TODO: check whether this is okay! as it is very
2568 // similar to how preferred-activities are treated
2569 readPersistentPreferredActivitiesLPw(parser, 0);
Nicolas Prevot29762c32014-07-29 18:51:32 +01002570 } else if (tagName.equals(TAG_CROSS_PROFILE_INTENT_FILTERS)) {
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00002571 // TODO: check whether this is okay! as it is very
2572 // similar to how preferred-activities are treated
Nicolas Prevot81948992014-05-16 18:25:26 +01002573 readCrossProfileIntentFiltersLPw(parser, 0);
Fabrice Di Meglio62271722015-04-10 17:24:02 -07002574 } else if (tagName.equals(TAG_DEFAULT_BROWSER)) {
2575 readDefaultAppsLPw(parser, 0);
2576 } else if (tagName.equals("updated-package")) {
Kenny Root447106f2011-03-23 11:00:15 -07002577 readDisabledSysPackageLPw(parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002578 } else if (tagName.equals("cleaning-package")) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002579 String name = parser.getAttributeValue(null, ATTR_NAME);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002580 String userStr = parser.getAttributeValue(null, ATTR_USER);
2581 String codeStr = parser.getAttributeValue(null, ATTR_CODE);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002582 if (name != null) {
Jeff Sharkey752cd922012-09-23 16:25:12 -07002583 int userId = 0;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002584 boolean andCode = true;
2585 try {
2586 if (userStr != null) {
Jeff Sharkey752cd922012-09-23 16:25:12 -07002587 userId = Integer.parseInt(userStr);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002588 }
2589 } catch (NumberFormatException e) {
2590 }
2591 if (codeStr != null) {
2592 andCode = Boolean.parseBoolean(codeStr);
2593 }
Jeff Sharkey752cd922012-09-23 16:25:12 -07002594 addPackageToCleanLPw(new PackageCleanItem(userId, name, andCode));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002595 }
2596 } else if (tagName.equals("renamed-package")) {
2597 String nname = parser.getAttributeValue(null, "new");
2598 String oname = parser.getAttributeValue(null, "old");
2599 if (nname != null && oname != null) {
2600 mRenamedPackages.put(nname, oname);
2601 }
Christopher Tate6038d152015-06-17 13:07:46 -07002602 } else if (tagName.equals("restored-ivi")) {
2603 readRestoredIntentFilterVerifications(parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002604 } else if (tagName.equals("last-platform-version")) {
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07002605 // Upgrade from older XML schema
2606 final VersionInfo internal = findOrCreateVersion(
2607 StorageManager.UUID_PRIVATE_INTERNAL);
2608 final VersionInfo external = findOrCreateVersion(
2609 StorageManager.UUID_PRIMARY_PHYSICAL);
Svet Ganovadc1cf42015-06-15 16:36:24 -07002610
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07002611 internal.sdkVersion = XmlUtils.readIntAttribute(parser, "internal", 0);
2612 external.sdkVersion = XmlUtils.readIntAttribute(parser, "external", 0);
2613 internal.fingerprint = external.fingerprint =
2614 XmlUtils.readStringAttribute(parser, "fingerprint");
2615
Kenny Rootc1c0d3c2014-04-24 13:36:40 -07002616 } else if (tagName.equals("database-version")) {
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07002617 // Upgrade from older XML schema
2618 final VersionInfo internal = findOrCreateVersion(
2619 StorageManager.UUID_PRIVATE_INTERNAL);
2620 final VersionInfo external = findOrCreateVersion(
2621 StorageManager.UUID_PRIMARY_PHYSICAL);
2622
2623 internal.databaseVersion = XmlUtils.readIntAttribute(parser, "internal", 0);
2624 external.databaseVersion = XmlUtils.readIntAttribute(parser, "external", 0);
2625
Kenny Root0aaa0d92011-09-12 16:42:55 -07002626 } else if (tagName.equals("verifier")) {
2627 final String deviceIdentity = parser.getAttributeValue(null, "device");
2628 try {
2629 mVerifierDeviceIdentity = VerifierDeviceIdentity.parse(deviceIdentity);
2630 } catch (IllegalArgumentException e) {
2631 Slog.w(PackageManagerService.TAG, "Discard invalid verifier device id: "
2632 + e.getMessage());
2633 }
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07002634 } else if (TAG_READ_EXTERNAL_STORAGE.equals(tagName)) {
2635 final String enforcement = parser.getAttributeValue(null, ATTR_ENFORCEMENT);
Jeff Sharkey5d32e772012-04-12 15:59:23 -07002636 mReadExternalStorageEnforced = "1".equals(enforcement);
Geremy Condraf1bcca82013-01-07 22:35:24 -08002637 } else if (tagName.equals("keyset-settings")) {
dcashman8c04fac2015-03-23 11:39:42 -07002638 mKeySetManagerService.readKeySetsLPw(parser, mKeySetRefs);
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07002639 } else if (TAG_VERSION.equals(tagName)) {
2640 final String volumeUuid = XmlUtils.readStringAttribute(parser,
2641 ATTR_VOLUME_UUID);
2642 final VersionInfo ver = findOrCreateVersion(volumeUuid);
2643 ver.sdkVersion = XmlUtils.readIntAttribute(parser, ATTR_SDK_VERSION);
2644 ver.databaseVersion = XmlUtils.readIntAttribute(parser, ATTR_SDK_VERSION);
2645 ver.fingerprint = XmlUtils.readStringAttribute(parser, ATTR_FINGERPRINT);
2646
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002647 } else {
2648 Slog.w(PackageManagerService.TAG, "Unknown element under <packages>: "
2649 + parser.getName());
2650 XmlUtils.skipCurrentTag(parser);
2651 }
2652 }
2653
2654 str.close();
2655
2656 } catch (XmlPullParserException e) {
2657 mReadMessages.append("Error reading: " + e.toString());
2658 PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07002659 Slog.wtf(PackageManagerService.TAG, "Error reading package manager settings", e);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002660
2661 } catch (java.io.IOException e) {
2662 mReadMessages.append("Error reading: " + e.toString());
2663 PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07002664 Slog.wtf(PackageManagerService.TAG, "Error reading package manager settings", e);
Amith Yamasani258848d2012-08-10 17:06:33 -07002665 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002666
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07002667 // If the build is setup to drop runtime permissions
2668 // on update drop the files before loading them.
2669 if (PackageManagerService.CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE) {
2670 final VersionInfo internal = getInternalVersion();
2671 if (!Build.FINGERPRINT.equals(internal.fingerprint)) {
2672 if (users == null) {
2673 mRuntimePermissionsPersistence.deleteUserRuntimePermissionsFile(
2674 UserHandle.USER_OWNER);
2675 } else {
2676 for (UserInfo user : users) {
2677 mRuntimePermissionsPersistence.deleteUserRuntimePermissionsFile(
2678 user.id);
2679 }
2680 }
2681 }
2682 }
2683
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002684 final int N = mPendingPackages.size();
dcashman8c04fac2015-03-23 11:39:42 -07002685
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002686 for (int i = 0; i < N; i++) {
2687 final PendingPackage pp = mPendingPackages.get(i);
Kenny Root447106f2011-03-23 11:00:15 -07002688 Object idObj = getUserIdLPr(pp.sharedId);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002689 if (idObj != null && idObj instanceof SharedUserSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002690 PackageSetting p = getPackageLPw(pp.name, null, pp.realName,
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002691 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
Narayan Kamathff110bd2014-07-04 18:30:45 +01002692 pp.legacyNativeLibraryPathString, pp.primaryCpuAbiString,
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002693 pp.secondaryCpuAbiString, pp.versionCode, pp.pkgFlags, pp.pkgPrivateFlags,
2694 null, true /* add */, false /* allowInstall */);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002695 if (p == null) {
2696 PackageManagerService.reportSettingsProblem(Log.WARN,
2697 "Unable to create application package for " + pp.name);
2698 continue;
2699 }
2700 p.copyFrom(pp);
2701 } else if (idObj != null) {
2702 String msg = "Bad package setting: package " + pp.name + " has shared uid "
2703 + pp.sharedId + " that is not a shared uid\n";
2704 mReadMessages.append(msg);
2705 PackageManagerService.reportSettingsProblem(Log.ERROR, msg);
2706 } else {
2707 String msg = "Bad package setting: package " + pp.name + " has shared uid "
2708 + pp.sharedId + " that is not defined\n";
2709 mReadMessages.append(msg);
2710 PackageManagerService.reportSettingsProblem(Log.ERROR, msg);
2711 }
2712 }
2713 mPendingPackages.clear();
2714
Amith Yamasanif031f232012-10-26 15:35:21 -07002715 if (mBackupStoppedPackagesFilename.exists()
2716 || mStoppedPackagesFilename.exists()) {
2717 // Read old file
2718 readStoppedLPw();
2719 mBackupStoppedPackagesFilename.delete();
2720 mStoppedPackagesFilename.delete();
2721 // Migrate to new file format
2722 writePackageRestrictionsLPr(0);
2723 } else {
2724 if (users == null) {
2725 readPackageRestrictionsLPr(0);
2726 } else {
2727 for (UserInfo user : users) {
2728 readPackageRestrictionsLPr(user.id);
2729 }
2730 }
2731 }
2732
Svet Ganovadc1cf42015-06-15 16:36:24 -07002733 if (users == null) {
2734 mRuntimePermissionsPersistence.readStateForUserSyncLPr(UserHandle.USER_OWNER);
2735 } else {
2736 for (UserInfo user : users) {
2737 mRuntimePermissionsPersistence.readStateForUserSyncLPr(user.id);
2738 }
2739 }
2740
Kenny Root1d1b4892011-04-08 14:25:24 -07002741 /*
2742 * Make sure all the updated system packages have their shared users
2743 * associated with them.
2744 */
2745 final Iterator<PackageSetting> disabledIt = mDisabledSysPackages.values().iterator();
2746 while (disabledIt.hasNext()) {
2747 final PackageSetting disabledPs = disabledIt.next();
Amith Yamasani13593602012-03-22 16:16:17 -07002748 final Object id = getUserIdLPr(disabledPs.appId);
Kenny Root1d1b4892011-04-08 14:25:24 -07002749 if (id != null && id instanceof SharedUserSetting) {
2750 disabledPs.sharedUser = (SharedUserSetting) id;
2751 }
2752 }
2753
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002754 mReadMessages.append("Read completed successfully: " + mPackages.size() + " packages, "
2755 + mSharedUsers.size() + " shared uids\n");
2756
2757 return true;
2758 }
2759
Christopher Tatedb3fe812015-06-24 16:15:48 -07002760 void applyDefaultPreferredAppsLPw(PackageManagerService service, int userId) {
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002761 // First pull data from any pre-installed apps.
2762 for (PackageSetting ps : mPackages.values()) {
2763 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0 && ps.pkg != null
2764 && ps.pkg.preferredActivityFilters != null) {
2765 ArrayList<PackageParser.ActivityIntentInfo> intents
2766 = ps.pkg.preferredActivityFilters;
2767 for (int i=0; i<intents.size(); i++) {
2768 PackageParser.ActivityIntentInfo aii = intents.get(i);
2769 applyDefaultPreferredActivityLPw(service, aii, new ComponentName(
2770 ps.name, aii.activity.className), userId);
2771 }
2772 }
2773 }
2774
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07002775 // Read preferred apps from .../etc/preferred-apps directory.
2776 File preferredDir = new File(Environment.getRootDirectory(), "etc/preferred-apps");
2777 if (!preferredDir.exists() || !preferredDir.isDirectory()) {
2778 return;
2779 }
2780 if (!preferredDir.canRead()) {
2781 Slog.w(TAG, "Directory " + preferredDir + " cannot be read");
2782 return;
2783 }
2784
2785 // Iterate over the files in the directory and scan .xml files
2786 for (File f : preferredDir.listFiles()) {
2787 if (!f.getPath().endsWith(".xml")) {
2788 Slog.i(TAG, "Non-xml file " + f + " in " + preferredDir + " directory, ignoring");
2789 continue;
2790 }
2791 if (!f.canRead()) {
2792 Slog.w(TAG, "Preferred apps file " + f + " cannot be read");
2793 continue;
2794 }
2795
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08002796 if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Reading default preferred " + f);
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07002797 FileInputStream str = null;
2798 try {
2799 str = new FileInputStream(f);
2800 XmlPullParser parser = Xml.newPullParser();
2801 parser.setInput(str, null);
2802
2803 int type;
2804 while ((type = parser.next()) != XmlPullParser.START_TAG
2805 && type != XmlPullParser.END_DOCUMENT) {
2806 ;
2807 }
2808
2809 if (type != XmlPullParser.START_TAG) {
2810 Slog.w(TAG, "Preferred apps file " + f + " does not have start tag");
2811 continue;
2812 }
2813 if (!"preferred-activities".equals(parser.getName())) {
2814 Slog.w(TAG, "Preferred apps file " + f
2815 + " does not start with 'preferred-activities'");
2816 continue;
2817 }
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08002818 readDefaultPreferredActivitiesLPw(service, parser, userId);
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07002819 } catch (XmlPullParserException e) {
2820 Slog.w(TAG, "Error reading apps file " + f, e);
2821 } catch (IOException e) {
2822 Slog.w(TAG, "Error reading apps file " + f, e);
2823 } finally {
2824 if (str != null) {
2825 try {
2826 str.close();
2827 } catch (IOException e) {
2828 }
2829 }
2830 }
2831 }
2832 }
2833
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002834 private void applyDefaultPreferredActivityLPw(PackageManagerService service,
2835 IntentFilter tmpPa, ComponentName cn, int userId) {
2836 // The initial preferences only specify the target activity
2837 // component and intent-filter, not the set of matches. So we
2838 // now need to query for the matches to build the correct
2839 // preferred activity entry.
2840 if (PackageManagerService.DEBUG_PREFERRED) {
2841 Log.d(TAG, "Processing preferred:");
2842 tmpPa.dump(new LogPrinter(Log.DEBUG, TAG), " ");
2843 }
2844 Intent intent = new Intent();
2845 int flags = 0;
2846 intent.setAction(tmpPa.getAction(0));
2847 for (int i=0; i<tmpPa.countCategories(); i++) {
2848 String cat = tmpPa.getCategory(i);
2849 if (cat.equals(Intent.CATEGORY_DEFAULT)) {
2850 flags |= PackageManager.MATCH_DEFAULT_ONLY;
2851 } else {
2852 intent.addCategory(cat);
2853 }
2854 }
2855
2856 boolean doNonData = true;
Christopher Tate2298ef22013-11-04 17:02:10 -08002857 boolean hasSchemes = false;
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002858
2859 for (int ischeme=0; ischeme<tmpPa.countDataSchemes(); ischeme++) {
2860 boolean doScheme = true;
2861 String scheme = tmpPa.getDataScheme(ischeme);
Christopher Tate2298ef22013-11-04 17:02:10 -08002862 if (scheme != null && !scheme.isEmpty()) {
2863 hasSchemes = true;
2864 }
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002865 for (int issp=0; issp<tmpPa.countDataSchemeSpecificParts(); issp++) {
2866 Uri.Builder builder = new Uri.Builder();
2867 builder.scheme(scheme);
2868 PatternMatcher ssp = tmpPa.getDataSchemeSpecificPart(issp);
2869 builder.opaquePart(ssp.getPath());
2870 Intent finalIntent = new Intent(intent);
2871 finalIntent.setData(builder.build());
2872 applyDefaultPreferredActivityLPw(service, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002873 scheme, ssp, null, null, userId);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002874 doScheme = false;
2875 }
2876 for (int iauth=0; iauth<tmpPa.countDataAuthorities(); iauth++) {
2877 boolean doAuth = true;
2878 IntentFilter.AuthorityEntry auth = tmpPa.getDataAuthority(iauth);
2879 for (int ipath=0; ipath<tmpPa.countDataPaths(); ipath++) {
2880 Uri.Builder builder = new Uri.Builder();
2881 builder.scheme(scheme);
2882 if (auth.getHost() != null) {
2883 builder.authority(auth.getHost());
2884 }
2885 PatternMatcher path = tmpPa.getDataPath(ipath);
2886 builder.path(path.getPath());
2887 Intent finalIntent = new Intent(intent);
2888 finalIntent.setData(builder.build());
2889 applyDefaultPreferredActivityLPw(service, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002890 scheme, null, auth, path, userId);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002891 doAuth = doScheme = false;
2892 }
2893 if (doAuth) {
2894 Uri.Builder builder = new Uri.Builder();
2895 builder.scheme(scheme);
2896 if (auth.getHost() != null) {
2897 builder.authority(auth.getHost());
2898 }
2899 Intent finalIntent = new Intent(intent);
2900 finalIntent.setData(builder.build());
2901 applyDefaultPreferredActivityLPw(service, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002902 scheme, null, auth, null, userId);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002903 doScheme = false;
2904 }
2905 }
2906 if (doScheme) {
2907 Uri.Builder builder = new Uri.Builder();
2908 builder.scheme(scheme);
2909 Intent finalIntent = new Intent(intent);
2910 finalIntent.setData(builder.build());
2911 applyDefaultPreferredActivityLPw(service, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002912 scheme, null, null, null, userId);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002913 }
2914 doNonData = false;
2915 }
2916
2917 for (int idata=0; idata<tmpPa.countDataTypes(); idata++) {
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002918 String mimeType = tmpPa.getDataType(idata);
Christopher Tate2298ef22013-11-04 17:02:10 -08002919 if (hasSchemes) {
2920 Uri.Builder builder = new Uri.Builder();
2921 for (int ischeme=0; ischeme<tmpPa.countDataSchemes(); ischeme++) {
2922 String scheme = tmpPa.getDataScheme(ischeme);
2923 if (scheme != null && !scheme.isEmpty()) {
2924 Intent finalIntent = new Intent(intent);
2925 builder.scheme(scheme);
2926 finalIntent.setDataAndType(builder.build(), mimeType);
2927 applyDefaultPreferredActivityLPw(service, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002928 scheme, null, null, null, userId);
Christopher Tate2298ef22013-11-04 17:02:10 -08002929 }
2930 }
2931 } else {
2932 Intent finalIntent = new Intent(intent);
2933 finalIntent.setType(mimeType);
2934 applyDefaultPreferredActivityLPw(service, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002935 null, null, null, null, userId);
Christopher Tate2298ef22013-11-04 17:02:10 -08002936 }
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002937 doNonData = false;
2938 }
2939
2940 if (doNonData) {
2941 applyDefaultPreferredActivityLPw(service, intent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002942 null, null, null, null, userId);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002943 }
2944 }
2945
2946 private void applyDefaultPreferredActivityLPw(PackageManagerService service,
2947 Intent intent, int flags, ComponentName cn, String scheme, PatternMatcher ssp,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002948 IntentFilter.AuthorityEntry auth, PatternMatcher path, int userId) {
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002949 List<ResolveInfo> ri = service.mActivities.queryIntent(intent,
2950 intent.getType(), flags, 0);
2951 if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Queried " + intent
2952 + " results: " + ri);
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002953 int systemMatch = 0;
2954 int thirdPartyMatch = 0;
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002955 if (ri != null && ri.size() > 1) {
2956 boolean haveAct = false;
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002957 ComponentName haveNonSys = null;
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002958 ComponentName[] set = new ComponentName[ri.size()];
2959 for (int i=0; i<ri.size(); i++) {
2960 ActivityInfo ai = ri.get(i).activityInfo;
2961 set[i] = new ComponentName(ai.packageName, ai.name);
2962 if ((ai.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002963 if (ri.get(i).match >= thirdPartyMatch) {
2964 // Keep track of the best match we find of all third
2965 // party apps, for use later to determine if we actually
2966 // want to set a preferred app for this intent.
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002967 if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Result "
2968 + ai.packageName + "/" + ai.name + ": non-system!");
2969 haveNonSys = set[i];
2970 break;
2971 }
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002972 } else if (cn.getPackageName().equals(ai.packageName)
2973 && cn.getClassName().equals(ai.name)) {
2974 if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Result "
2975 + ai.packageName + "/" + ai.name + ": default!");
2976 haveAct = true;
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002977 systemMatch = ri.get(i).match;
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002978 } else {
2979 if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Result "
2980 + ai.packageName + "/" + ai.name + ": skipped");
2981 }
2982 }
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002983 if (haveNonSys != null && thirdPartyMatch < systemMatch) {
2984 // If we have a matching third party app, but its match is not as
2985 // good as the built-in system app, then we don't want to actually
2986 // consider it a match because presumably the built-in app is still
2987 // the thing we want users to see by default.
2988 haveNonSys = null;
2989 }
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002990 if (haveAct && haveNonSys == null) {
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002991 IntentFilter filter = new IntentFilter();
2992 if (intent.getAction() != null) {
2993 filter.addAction(intent.getAction());
2994 }
Erin Dahlgren707a59d2013-10-24 15:13:39 -07002995 if (intent.getCategories() != null) {
2996 for (String cat : intent.getCategories()) {
2997 filter.addCategory(cat);
2998 }
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002999 }
3000 if ((flags&PackageManager.MATCH_DEFAULT_ONLY) != 0) {
3001 filter.addCategory(Intent.CATEGORY_DEFAULT);
3002 }
3003 if (scheme != null) {
3004 filter.addDataScheme(scheme);
3005 }
3006 if (ssp != null) {
3007 filter.addDataSchemeSpecificPart(ssp.getPath(), ssp.getType());
3008 }
3009 if (auth != null) {
3010 filter.addDataAuthority(auth);
3011 }
3012 if (path != null) {
3013 filter.addDataPath(path);
3014 }
Erin Dahlgren707a59d2013-10-24 15:13:39 -07003015 if (intent.getType() != null) {
3016 try {
3017 filter.addDataType(intent.getType());
3018 } catch (IntentFilter.MalformedMimeTypeException ex) {
3019 Slog.w(TAG, "Malformed mimetype " + intent.getType() + " for " + cn);
3020 }
3021 }
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07003022 PreferredActivity pa = new PreferredActivity(filter, systemMatch, set, cn, true);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003023 editPreferredActivitiesLPw(userId).addFilter(pa);
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003024 } else if (haveNonSys == null) {
3025 StringBuilder sb = new StringBuilder();
3026 sb.append("No component ");
3027 sb.append(cn.flattenToShortString());
3028 sb.append(" found setting preferred ");
3029 sb.append(intent);
3030 sb.append("; possible matches are ");
3031 for (int i=0; i<set.length; i++) {
3032 if (i > 0) sb.append(", ");
3033 sb.append(set[i].flattenToShortString());
3034 }
3035 Slog.w(TAG, sb.toString());
3036 } else {
3037 Slog.i(TAG, "Not setting preferred " + intent + "; found third party match "
3038 + haveNonSys.flattenToShortString());
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003039 }
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003040 } else {
3041 Slog.w(TAG, "No potential matches found for " + intent + " while setting preferred "
3042 + cn.flattenToShortString());
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003043 }
3044 }
3045
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08003046 private void readDefaultPreferredActivitiesLPw(PackageManagerService service,
3047 XmlPullParser parser, int userId)
3048 throws XmlPullParserException, IOException {
3049 int outerDepth = parser.getDepth();
3050 int type;
3051 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3052 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3053 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3054 continue;
3055 }
3056
3057 String tagName = parser.getName();
3058 if (tagName.equals(TAG_ITEM)) {
3059 PreferredActivity tmpPa = new PreferredActivity(parser);
3060 if (tmpPa.mPref.getParseError() == null) {
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003061 applyDefaultPreferredActivityLPw(service, tmpPa, tmpPa.mPref.mComponent,
3062 userId);
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08003063 } else {
3064 PackageManagerService.reportSettingsProblem(Log.WARN,
3065 "Error in package manager settings: <preferred-activity> "
3066 + tmpPa.mPref.getParseError() + " at "
3067 + parser.getPositionDescription());
3068 }
3069 } else {
3070 PackageManagerService.reportSettingsProblem(Log.WARN,
3071 "Unknown element under <preferred-activities>: " + parser.getName());
3072 XmlUtils.skipCurrentTag(parser);
3073 }
3074 }
3075 }
3076
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003077 private int readInt(XmlPullParser parser, String ns, String name, int defValue) {
3078 String v = parser.getAttributeValue(ns, name);
3079 try {
3080 if (v == null) {
3081 return defValue;
3082 }
3083 return Integer.parseInt(v);
3084 } catch (NumberFormatException e) {
3085 PackageManagerService.reportSettingsProblem(Log.WARN,
3086 "Error in package manager settings: attribute " + name
3087 + " has bad integer value " + v + " at "
3088 + parser.getPositionDescription());
3089 }
3090 return defValue;
3091 }
3092
Jeff Sharkey9f837a92014-10-24 12:07:24 -07003093 private void readPermissionsLPw(ArrayMap<String, BasePermission> out, XmlPullParser parser)
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003094 throws IOException, XmlPullParserException {
3095 int outerDepth = parser.getDepth();
3096 int type;
3097 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3098 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3099 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3100 continue;
3101 }
3102
Kenny Root447106f2011-03-23 11:00:15 -07003103 final String tagName = parser.getName();
Amith Yamasani483f3b02012-03-13 16:08:00 -07003104 if (tagName.equals(TAG_ITEM)) {
3105 final String name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Root447106f2011-03-23 11:00:15 -07003106 final String sourcePackage = parser.getAttributeValue(null, "package");
3107 final String ptype = parser.getAttributeValue(null, "type");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003108 if (name != null && sourcePackage != null) {
Kenny Root447106f2011-03-23 11:00:15 -07003109 final boolean dynamic = "dynamic".equals(ptype);
Svetoslavc6d1c342015-02-26 14:44:43 -08003110 final BasePermission bp = new BasePermission(name.intern(), sourcePackage,
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003111 dynamic ? BasePermission.TYPE_DYNAMIC : BasePermission.TYPE_NORMAL);
3112 bp.protectionLevel = readInt(parser, null, "protection",
3113 PermissionInfo.PROTECTION_NORMAL);
Dianne Hackborne639da72012-02-21 15:11:13 -08003114 bp.protectionLevel = PermissionInfo.fixProtectionLevel(bp.protectionLevel);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003115 if (dynamic) {
3116 PermissionInfo pi = new PermissionInfo();
3117 pi.packageName = sourcePackage.intern();
3118 pi.name = name.intern();
3119 pi.icon = readInt(parser, null, "icon", 0);
3120 pi.nonLocalizedLabel = parser.getAttributeValue(null, "label");
3121 pi.protectionLevel = bp.protectionLevel;
3122 bp.pendingInfo = pi;
3123 }
3124 out.put(bp.name, bp);
3125 } else {
3126 PackageManagerService.reportSettingsProblem(Log.WARN,
3127 "Error in package manager settings: permissions has" + " no name at "
3128 + parser.getPositionDescription());
3129 }
3130 } else {
3131 PackageManagerService.reportSettingsProblem(Log.WARN,
3132 "Unknown element reading permissions: " + parser.getName() + " at "
3133 + parser.getPositionDescription());
3134 }
3135 XmlUtils.skipCurrentTag(parser);
3136 }
3137 }
3138
Kenny Root447106f2011-03-23 11:00:15 -07003139 private void readDisabledSysPackageLPw(XmlPullParser parser) throws XmlPullParserException,
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003140 IOException {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003141 String name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003142 String realName = parser.getAttributeValue(null, "realName");
3143 String codePathStr = parser.getAttributeValue(null, "codePath");
3144 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Narayan Kamathff110bd2014-07-04 18:30:45 +01003145
3146 String legacyCpuAbiStr = parser.getAttributeValue(null, "requiredCpuAbi");
3147 String legacyNativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
3148
3149 String primaryCpuAbiStr = parser.getAttributeValue(null, "primaryCpuAbi");
3150 String secondaryCpuAbiStr = parser.getAttributeValue(null, "secondaryCpuAbi");
Narayan Kamath4903f642014-08-11 13:33:45 +01003151 String cpuAbiOverrideStr = parser.getAttributeValue(null, "cpuAbiOverride");
Narayan Kamathff110bd2014-07-04 18:30:45 +01003152
3153 if (primaryCpuAbiStr == null && legacyCpuAbiStr != null) {
3154 primaryCpuAbiStr = legacyCpuAbiStr;
3155 }
Narayan Kamath9e289d72014-04-10 09:26:59 +00003156
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003157 if (resourcePathStr == null) {
3158 resourcePathStr = codePathStr;
3159 }
3160 String version = parser.getAttributeValue(null, "version");
3161 int versionCode = 0;
3162 if (version != null) {
3163 try {
3164 versionCode = Integer.parseInt(version);
3165 } catch (NumberFormatException e) {
3166 }
3167 }
3168
3169 int pkgFlags = 0;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003170 int pkgPrivateFlags = 0;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003171 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Christopher Tate628946a2013-10-18 18:11:05 -07003172 final File codePathFile = new File(codePathStr);
3173 if (PackageManagerService.locationIsPrivileged(codePathFile)) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003174 pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
Christopher Tate628946a2013-10-18 18:11:05 -07003175 }
3176 PackageSetting ps = new PackageSetting(name, realName, codePathFile,
Narayan Kamathff110bd2014-07-04 18:30:45 +01003177 new File(resourcePathStr), legacyNativeLibraryPathStr, primaryCpuAbiStr,
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003178 secondaryCpuAbiStr, cpuAbiOverrideStr, versionCode, pkgFlags, pkgPrivateFlags);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003179 String timeStampStr = parser.getAttributeValue(null, "ft");
3180 if (timeStampStr != null) {
3181 try {
3182 long timeStamp = Long.parseLong(timeStampStr, 16);
3183 ps.setTimeStamp(timeStamp);
3184 } catch (NumberFormatException e) {
3185 }
3186 } else {
3187 timeStampStr = parser.getAttributeValue(null, "ts");
3188 if (timeStampStr != null) {
3189 try {
3190 long timeStamp = Long.parseLong(timeStampStr);
3191 ps.setTimeStamp(timeStamp);
3192 } catch (NumberFormatException e) {
3193 }
3194 }
3195 }
3196 timeStampStr = parser.getAttributeValue(null, "it");
3197 if (timeStampStr != null) {
3198 try {
3199 ps.firstInstallTime = Long.parseLong(timeStampStr, 16);
3200 } catch (NumberFormatException e) {
3201 }
3202 }
3203 timeStampStr = parser.getAttributeValue(null, "ut");
3204 if (timeStampStr != null) {
3205 try {
3206 ps.lastUpdateTime = Long.parseLong(timeStampStr, 16);
3207 } catch (NumberFormatException e) {
3208 }
3209 }
3210 String idStr = parser.getAttributeValue(null, "userId");
Amith Yamasani13593602012-03-22 16:16:17 -07003211 ps.appId = idStr != null ? Integer.parseInt(idStr) : 0;
3212 if (ps.appId <= 0) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003213 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
Amith Yamasani13593602012-03-22 16:16:17 -07003214 ps.appId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003215 }
Svetoslavc6d1c342015-02-26 14:44:43 -08003216
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003217 int outerDepth = parser.getDepth();
3218 int type;
3219 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3220 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3221 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3222 continue;
3223 }
3224
Svetoslavc6d1c342015-02-26 14:44:43 -08003225 if (parser.getName().equals(TAG_PERMISSIONS)) {
3226 readInstallPermissionsLPr(parser, ps.getPermissionsState());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003227 } else {
3228 PackageManagerService.reportSettingsProblem(Log.WARN,
3229 "Unknown element under <updated-package>: " + parser.getName());
3230 XmlUtils.skipCurrentTag(parser);
3231 }
3232 }
Christopher Tate628946a2013-10-18 18:11:05 -07003233
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003234 mDisabledSysPackages.put(name, ps);
3235 }
3236
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003237 private static int PRE_M_APP_INFO_FLAG_HIDDEN = 1<<27;
3238 private static int PRE_M_APP_INFO_FLAG_CANT_SAVE_STATE = 1<<28;
3239 private static int PRE_M_APP_INFO_FLAG_FORWARD_LOCK = 1<<29;
3240 private static int PRE_M_APP_INFO_FLAG_PRIVILEGED = 1<<30;
3241
Kenny Root447106f2011-03-23 11:00:15 -07003242 private void readPackageLPw(XmlPullParser parser) throws XmlPullParserException, IOException {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003243 String name = null;
3244 String realName = null;
3245 String idStr = null;
3246 String sharedIdStr = null;
3247 String codePathStr = null;
3248 String resourcePathStr = null;
Narayan Kamathff110bd2014-07-04 18:30:45 +01003249 String legacyCpuAbiString = null;
3250 String legacyNativeLibraryPathStr = null;
3251 String primaryCpuAbiString = null;
3252 String secondaryCpuAbiString = null;
Narayan Kamath4903f642014-08-11 13:33:45 +01003253 String cpuAbiOverrideString = null;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003254 String systemStr = null;
3255 String installerPackageName = null;
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07003256 String volumeUuid = null;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003257 String uidError = null;
3258 int pkgFlags = 0;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003259 int pkgPrivateFlags = 0;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003260 long timeStamp = 0;
3261 long firstInstallTime = 0;
3262 long lastUpdateTime = 0;
3263 PackageSettingBase packageSetting = null;
3264 String version = null;
3265 int versionCode = 0;
3266 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003267 name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003268 realName = parser.getAttributeValue(null, "realName");
3269 idStr = parser.getAttributeValue(null, "userId");
3270 uidError = parser.getAttributeValue(null, "uidError");
3271 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
3272 codePathStr = parser.getAttributeValue(null, "codePath");
3273 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Narayan Kamath9e289d72014-04-10 09:26:59 +00003274
Narayan Kamathff110bd2014-07-04 18:30:45 +01003275 legacyCpuAbiString = parser.getAttributeValue(null, "requiredCpuAbi");
3276
3277 legacyNativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
3278 primaryCpuAbiString = parser.getAttributeValue(null, "primaryCpuAbi");
3279 secondaryCpuAbiString = parser.getAttributeValue(null, "secondaryCpuAbi");
Narayan Kamath4903f642014-08-11 13:33:45 +01003280 cpuAbiOverrideString = parser.getAttributeValue(null, "cpuAbiOverride");
Narayan Kamathff110bd2014-07-04 18:30:45 +01003281
3282 if (primaryCpuAbiString == null && legacyCpuAbiString != null) {
3283 primaryCpuAbiString = legacyCpuAbiString;
3284 }
Svetoslavc6d1c342015-02-26 14:44:43 -08003285
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003286 version = parser.getAttributeValue(null, "version");
3287 if (version != null) {
3288 try {
3289 versionCode = Integer.parseInt(version);
3290 } catch (NumberFormatException e) {
3291 }
3292 }
3293 installerPackageName = parser.getAttributeValue(null, "installer");
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07003294 volumeUuid = parser.getAttributeValue(null, "volumeUuid");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003295
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003296 systemStr = parser.getAttributeValue(null, "publicFlags");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003297 if (systemStr != null) {
3298 try {
3299 pkgFlags = Integer.parseInt(systemStr);
3300 } catch (NumberFormatException e) {
3301 }
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003302 systemStr = parser.getAttributeValue(null, "privateFlags");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003303 if (systemStr != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003304 try {
3305 pkgPrivateFlags = Integer.parseInt(systemStr);
3306 } catch (NumberFormatException e) {
3307 }
3308 }
3309 } else {
3310 // Pre-M -- both public and private flags were stored in one "flags" field.
3311 systemStr = parser.getAttributeValue(null, "flags");
3312 if (systemStr != null) {
3313 try {
3314 pkgFlags = Integer.parseInt(systemStr);
3315 } catch (NumberFormatException e) {
3316 }
3317 if ((pkgFlags & PRE_M_APP_INFO_FLAG_HIDDEN) != 0) {
3318 pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_HIDDEN;
3319 }
3320 if ((pkgFlags & PRE_M_APP_INFO_FLAG_CANT_SAVE_STATE) != 0) {
3321 pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE;
3322 }
3323 if ((pkgFlags & PRE_M_APP_INFO_FLAG_FORWARD_LOCK) != 0) {
3324 pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_FORWARD_LOCK;
3325 }
3326 if ((pkgFlags & PRE_M_APP_INFO_FLAG_PRIVILEGED) != 0) {
3327 pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
3328 }
3329 pkgFlags &= ~(PRE_M_APP_INFO_FLAG_HIDDEN
3330 | PRE_M_APP_INFO_FLAG_CANT_SAVE_STATE
3331 | PRE_M_APP_INFO_FLAG_FORWARD_LOCK
3332 | PRE_M_APP_INFO_FLAG_PRIVILEGED);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003333 } else {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003334 // For backward compatibility
3335 systemStr = parser.getAttributeValue(null, "system");
3336 if (systemStr != null) {
3337 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM
3338 : 0;
3339 } else {
3340 // Old settings that don't specify system... just treat
3341 // them as system, good enough.
3342 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
3343 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003344 }
3345 }
3346 String timeStampStr = parser.getAttributeValue(null, "ft");
3347 if (timeStampStr != null) {
3348 try {
3349 timeStamp = Long.parseLong(timeStampStr, 16);
3350 } catch (NumberFormatException e) {
3351 }
3352 } else {
3353 timeStampStr = parser.getAttributeValue(null, "ts");
3354 if (timeStampStr != null) {
3355 try {
3356 timeStamp = Long.parseLong(timeStampStr);
3357 } catch (NumberFormatException e) {
3358 }
3359 }
3360 }
3361 timeStampStr = parser.getAttributeValue(null, "it");
3362 if (timeStampStr != null) {
3363 try {
3364 firstInstallTime = Long.parseLong(timeStampStr, 16);
3365 } catch (NumberFormatException e) {
3366 }
3367 }
3368 timeStampStr = parser.getAttributeValue(null, "ut");
3369 if (timeStampStr != null) {
3370 try {
3371 lastUpdateTime = Long.parseLong(timeStampStr, 16);
3372 } catch (NumberFormatException e) {
3373 }
3374 }
3375 if (PackageManagerService.DEBUG_SETTINGS)
3376 Log.v(PackageManagerService.TAG, "Reading package: " + name + " userId=" + idStr
3377 + " sharedUserId=" + sharedIdStr);
3378 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
3379 if (resourcePathStr == null) {
3380 resourcePathStr = codePathStr;
3381 }
3382 if (realName != null) {
3383 realName = realName.intern();
3384 }
3385 if (name == null) {
3386 PackageManagerService.reportSettingsProblem(Log.WARN,
3387 "Error in package manager settings: <package> has no name at "
3388 + parser.getPositionDescription());
3389 } else if (codePathStr == null) {
3390 PackageManagerService.reportSettingsProblem(Log.WARN,
3391 "Error in package manager settings: <package> has no codePath at "
3392 + parser.getPositionDescription());
3393 } else if (userId > 0) {
Kenny Root447106f2011-03-23 11:00:15 -07003394 packageSetting = addPackageLPw(name.intern(), realName, new File(codePathStr),
Narayan Kamathff110bd2014-07-04 18:30:45 +01003395 new File(resourcePathStr), legacyNativeLibraryPathStr, primaryCpuAbiString,
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003396 secondaryCpuAbiString, cpuAbiOverrideString, userId, versionCode, pkgFlags,
3397 pkgPrivateFlags);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003398 if (PackageManagerService.DEBUG_SETTINGS)
3399 Log.i(PackageManagerService.TAG, "Reading package " + name + ": userId="
3400 + userId + " pkg=" + packageSetting);
3401 if (packageSetting == null) {
3402 PackageManagerService.reportSettingsProblem(Log.ERROR, "Failure adding uid "
3403 + userId + " while parsing settings at "
3404 + parser.getPositionDescription());
3405 } else {
3406 packageSetting.setTimeStamp(timeStamp);
3407 packageSetting.firstInstallTime = firstInstallTime;
3408 packageSetting.lastUpdateTime = lastUpdateTime;
3409 }
3410 } else if (sharedIdStr != null) {
3411 userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
3412 if (userId > 0) {
3413 packageSetting = new PendingPackage(name.intern(), realName, new File(
Narayan Kamathff110bd2014-07-04 18:30:45 +01003414 codePathStr), new File(resourcePathStr), legacyNativeLibraryPathStr,
Narayan Kamath4903f642014-08-11 13:33:45 +01003415 primaryCpuAbiString, secondaryCpuAbiString, cpuAbiOverrideString,
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003416 userId, versionCode, pkgFlags, pkgPrivateFlags);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003417 packageSetting.setTimeStamp(timeStamp);
3418 packageSetting.firstInstallTime = firstInstallTime;
3419 packageSetting.lastUpdateTime = lastUpdateTime;
3420 mPendingPackages.add((PendingPackage) packageSetting);
3421 if (PackageManagerService.DEBUG_SETTINGS)
3422 Log.i(PackageManagerService.TAG, "Reading package " + name
3423 + ": sharedUserId=" + userId + " pkg=" + packageSetting);
3424 } else {
3425 PackageManagerService.reportSettingsProblem(Log.WARN,
3426 "Error in package manager settings: package " + name
3427 + " has bad sharedId " + sharedIdStr + " at "
3428 + parser.getPositionDescription());
3429 }
3430 } else {
3431 PackageManagerService.reportSettingsProblem(Log.WARN,
3432 "Error in package manager settings: package " + name + " has bad userId "
3433 + idStr + " at " + parser.getPositionDescription());
3434 }
3435 } catch (NumberFormatException e) {
3436 PackageManagerService.reportSettingsProblem(Log.WARN,
3437 "Error in package manager settings: package " + name + " has bad userId "
3438 + idStr + " at " + parser.getPositionDescription());
3439 }
3440 if (packageSetting != null) {
3441 packageSetting.uidError = "true".equals(uidError);
3442 packageSetting.installerPackageName = installerPackageName;
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07003443 packageSetting.volumeUuid = volumeUuid;
Narayan Kamathff110bd2014-07-04 18:30:45 +01003444 packageSetting.legacyNativeLibraryPathString = legacyNativeLibraryPathStr;
3445 packageSetting.primaryCpuAbiString = primaryCpuAbiString;
3446 packageSetting.secondaryCpuAbiString = secondaryCpuAbiString;
Amith Yamasani483f3b02012-03-13 16:08:00 -07003447 // Handle legacy string here for single-user mode
3448 final String enabledStr = parser.getAttributeValue(null, ATTR_ENABLED);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003449 if (enabledStr != null) {
Dianne Hackbornb8f40002011-07-19 15:17:43 -07003450 try {
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07003451 packageSetting.setEnabled(Integer.parseInt(enabledStr), 0 /* userId */, null);
Dianne Hackbornb8f40002011-07-19 15:17:43 -07003452 } catch (NumberFormatException e) {
3453 if (enabledStr.equalsIgnoreCase("true")) {
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07003454 packageSetting.setEnabled(COMPONENT_ENABLED_STATE_ENABLED, 0, null);
Dianne Hackbornb8f40002011-07-19 15:17:43 -07003455 } else if (enabledStr.equalsIgnoreCase("false")) {
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07003456 packageSetting.setEnabled(COMPONENT_ENABLED_STATE_DISABLED, 0, null);
Dianne Hackbornb8f40002011-07-19 15:17:43 -07003457 } else if (enabledStr.equalsIgnoreCase("default")) {
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07003458 packageSetting.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 0, null);
Dianne Hackbornb8f40002011-07-19 15:17:43 -07003459 } else {
3460 PackageManagerService.reportSettingsProblem(Log.WARN,
3461 "Error in package manager settings: package " + name
3462 + " has bad enabled value: " + idStr + " at "
3463 + parser.getPositionDescription());
3464 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003465 }
3466 } else {
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07003467 packageSetting.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 0, null);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003468 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003469
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003470 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
3471 if (installStatusStr != null) {
3472 if (installStatusStr.equalsIgnoreCase("false")) {
3473 packageSetting.installStatus = PackageSettingBase.PKG_INSTALL_INCOMPLETE;
3474 } else {
3475 packageSetting.installStatus = PackageSettingBase.PKG_INSTALL_COMPLETE;
3476 }
3477 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003478 int outerDepth = parser.getDepth();
3479 int type;
3480 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3481 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3482 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3483 continue;
3484 }
3485
3486 String tagName = parser.getName();
Amith Yamasani483f3b02012-03-13 16:08:00 -07003487 // Legacy
3488 if (tagName.equals(TAG_DISABLED_COMPONENTS)) {
3489 readDisabledComponentsLPw(packageSetting, parser, 0);
3490 } else if (tagName.equals(TAG_ENABLED_COMPONENTS)) {
3491 readEnabledComponentsLPw(packageSetting, parser, 0);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003492 } else if (tagName.equals("sigs")) {
3493 packageSetting.signatures.readXml(parser, mPastSignatures);
Svetoslavc6d1c342015-02-26 14:44:43 -08003494 } else if (tagName.equals(TAG_PERMISSIONS)) {
3495 readInstallPermissionsLPr(parser,
3496 packageSetting.getPermissionsState());
Svetoslavcf959f62015-03-26 20:53:34 -07003497 packageSetting.installPermissionsFixed = true;
dcashman3a0dbfb2014-07-07 13:53:36 -07003498 } else if (tagName.equals("proper-signing-keyset")) {
3499 long id = Long.parseLong(parser.getAttributeValue(null, "identifier"));
dcashman8c04fac2015-03-23 11:39:42 -07003500 Integer refCt = mKeySetRefs.get(id);
3501 if (refCt != null) {
3502 mKeySetRefs.put(id, refCt + 1);
3503 } else {
3504 mKeySetRefs.put(id, 1);
3505 }
dcashman3a0dbfb2014-07-07 13:53:36 -07003506 packageSetting.keySetData.setProperSigningKeySet(id);
Geremy Condraf1bcca82013-01-07 22:35:24 -08003507 } else if (tagName.equals("signing-keyset")) {
dcashman8c04fac2015-03-23 11:39:42 -07003508 // from v1 of keysetmanagerservice - no longer used
dcashman55b10782014-04-09 14:20:38 -07003509 } else if (tagName.equals("upgrade-keyset")) {
3510 long id = Long.parseLong(parser.getAttributeValue(null, "identifier"));
3511 packageSetting.keySetData.addUpgradeKeySetById(id);
Geremy Condraf1bcca82013-01-07 22:35:24 -08003512 } else if (tagName.equals("defined-keyset")) {
3513 long id = Long.parseLong(parser.getAttributeValue(null, "identifier"));
3514 String alias = parser.getAttributeValue(null, "alias");
dcashman8c04fac2015-03-23 11:39:42 -07003515 Integer refCt = mKeySetRefs.get(id);
3516 if (refCt != null) {
3517 mKeySetRefs.put(id, refCt + 1);
3518 } else {
3519 mKeySetRefs.put(id, 1);
3520 }
Geremy Condraf1bcca82013-01-07 22:35:24 -08003521 packageSetting.keySetData.addDefinedKeySet(id, alias);
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08003522 } else if (tagName.equals(TAG_DOMAIN_VERIFICATION)) {
3523 readDomainVerificationLPw(parser, packageSetting);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003524 } else {
3525 PackageManagerService.reportSettingsProblem(Log.WARN,
3526 "Unknown element under <package>: " + parser.getName());
3527 XmlUtils.skipCurrentTag(parser);
3528 }
3529 }
3530 } else {
3531 XmlUtils.skipCurrentTag(parser);
3532 }
3533 }
3534
Amith Yamasani483f3b02012-03-13 16:08:00 -07003535 private void readDisabledComponentsLPw(PackageSettingBase packageSetting, XmlPullParser parser,
3536 int userId) throws IOException, XmlPullParserException {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003537 int outerDepth = parser.getDepth();
3538 int type;
3539 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3540 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3541 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3542 continue;
3543 }
3544
3545 String tagName = parser.getName();
Amith Yamasani483f3b02012-03-13 16:08:00 -07003546 if (tagName.equals(TAG_ITEM)) {
3547 String name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003548 if (name != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003549 packageSetting.addDisabledComponent(name.intern(), userId);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003550 } else {
3551 PackageManagerService.reportSettingsProblem(Log.WARN,
3552 "Error in package manager settings: <disabled-components> has"
3553 + " no name at " + parser.getPositionDescription());
3554 }
3555 } else {
3556 PackageManagerService.reportSettingsProblem(Log.WARN,
3557 "Unknown element under <disabled-components>: " + parser.getName());
3558 }
3559 XmlUtils.skipCurrentTag(parser);
3560 }
3561 }
3562
Amith Yamasani483f3b02012-03-13 16:08:00 -07003563 private void readEnabledComponentsLPw(PackageSettingBase packageSetting, XmlPullParser parser,
3564 int userId) throws IOException, XmlPullParserException {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003565 int outerDepth = parser.getDepth();
3566 int type;
3567 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3568 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3569 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3570 continue;
3571 }
3572
3573 String tagName = parser.getName();
Amith Yamasani483f3b02012-03-13 16:08:00 -07003574 if (tagName.equals(TAG_ITEM)) {
3575 String name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003576 if (name != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003577 packageSetting.addEnabledComponent(name.intern(), userId);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003578 } else {
3579 PackageManagerService.reportSettingsProblem(Log.WARN,
3580 "Error in package manager settings: <enabled-components> has"
3581 + " no name at " + parser.getPositionDescription());
3582 }
3583 } else {
3584 PackageManagerService.reportSettingsProblem(Log.WARN,
3585 "Unknown element under <enabled-components>: " + parser.getName());
3586 }
3587 XmlUtils.skipCurrentTag(parser);
3588 }
3589 }
3590
Amith Yamasani483f3b02012-03-13 16:08:00 -07003591 private void readSharedUserLPw(XmlPullParser parser) throws XmlPullParserException,IOException {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003592 String name = null;
3593 String idStr = null;
3594 int pkgFlags = 0;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003595 int pkgPrivateFlags = 0;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003596 SharedUserSetting su = null;
3597 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003598 name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003599 idStr = parser.getAttributeValue(null, "userId");
3600 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
3601 if ("true".equals(parser.getAttributeValue(null, "system"))) {
3602 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
3603 }
3604 if (name == null) {
3605 PackageManagerService.reportSettingsProblem(Log.WARN,
3606 "Error in package manager settings: <shared-user> has no name at "
3607 + parser.getPositionDescription());
3608 } else if (userId == 0) {
3609 PackageManagerService.reportSettingsProblem(Log.WARN,
3610 "Error in package manager settings: shared-user " + name
3611 + " has bad userId " + idStr + " at "
3612 + parser.getPositionDescription());
3613 } else {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003614 if ((su = addSharedUserLPw(name.intern(), userId, pkgFlags, pkgPrivateFlags))
3615 == null) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003616 PackageManagerService
3617 .reportSettingsProblem(Log.ERROR, "Occurred while parsing settings at "
3618 + parser.getPositionDescription());
3619 }
3620 }
3621 } catch (NumberFormatException e) {
3622 PackageManagerService.reportSettingsProblem(Log.WARN,
3623 "Error in package manager settings: package " + name + " has bad userId "
3624 + idStr + " at " + parser.getPositionDescription());
3625 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003626
3627 if (su != null) {
3628 int outerDepth = parser.getDepth();
3629 int type;
3630 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3631 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3632 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3633 continue;
3634 }
3635
3636 String tagName = parser.getName();
3637 if (tagName.equals("sigs")) {
3638 su.signatures.readXml(parser, mPastSignatures);
3639 } else if (tagName.equals("perms")) {
Svetoslavc6d1c342015-02-26 14:44:43 -08003640 readInstallPermissionsLPr(parser, su.getPermissionsState());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003641 } else {
3642 PackageManagerService.reportSettingsProblem(Log.WARN,
3643 "Unknown element under <shared-user>: " + parser.getName());
3644 XmlUtils.skipCurrentTag(parser);
3645 }
3646 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003647 } else {
3648 XmlUtils.skipCurrentTag(parser);
3649 }
3650 }
3651
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003652 void createNewUserLILPw(PackageManagerService service, Installer installer, int userHandle) {
Dianne Hackborn63092712012-10-07 14:45:35 -07003653 for (PackageSetting ps : mPackages.values()) {
Amith Yamasani41cd5772014-07-10 15:26:00 -07003654 if (ps.pkg == null || ps.pkg.applicationInfo == null) {
3655 continue;
3656 }
Dianne Hackborn63092712012-10-07 14:45:35 -07003657 // Only system apps are initially installed.
3658 ps.setInstalled((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0, userHandle);
3659 // Need to create a data directory for all apps under this user.
Jeff Sharkey529f91f2015-04-18 20:23:13 -07003660 installer.createUserData(ps.volumeUuid, ps.name,
Robert Craig8643dc62013-07-29 09:06:51 -04003661 UserHandle.getUid(userHandle, ps.appId), userHandle,
3662 ps.pkg.applicationInfo.seinfo);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003663 }
Christopher Tatedb3fe812015-06-24 16:15:48 -07003664 applyDefaultPreferredAppsLPw(service, userHandle);
Dianne Hackborn63092712012-10-07 14:45:35 -07003665 writePackageRestrictionsLPr(userHandle);
Jeff Sharkey91edde22015-05-20 12:04:42 -07003666 writePackageListLPr(userHandle);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003667 }
3668
Alexandra Gherghina539a7ef2014-07-07 12:27:54 +01003669 void removeUserLPw(int userId) {
Dianne Hackborn63092712012-10-07 14:45:35 -07003670 Set<Entry<String, PackageSetting>> entries = mPackages.entrySet();
3671 for (Entry<String, PackageSetting> entry : entries) {
3672 entry.getValue().removeUser(userId);
3673 }
3674 mPreferredActivities.remove(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07003675 File file = getUserPackagesStateFile(userId);
3676 file.delete();
3677 file = getUserPackagesStateBackupFile(userId);
3678 file.delete();
Nicolas Prevote7024042014-07-08 15:47:17 +01003679 removeCrossProfileIntentFiltersLPw(userId);
Svetoslavc6d1c342015-02-26 14:44:43 -08003680
3681 mRuntimePermissionsPersistence.onUserRemoved(userId);
Jeff Sharkey91edde22015-05-20 12:04:42 -07003682
3683 writePackageListLPr();
Nicolas Prevota0f48852014-05-27 11:21:11 +01003684 }
3685
Nicolas Prevote7024042014-07-08 15:47:17 +01003686 void removeCrossProfileIntentFiltersLPw(int userId) {
3687 synchronized (mCrossProfileIntentResolvers) {
3688 // userId is the source user
3689 if (mCrossProfileIntentResolvers.get(userId) != null) {
3690 mCrossProfileIntentResolvers.remove(userId);
3691 writePackageRestrictionsLPr(userId);
Nicolas Prevota0f48852014-05-27 11:21:11 +01003692 }
Nicolas Prevote7024042014-07-08 15:47:17 +01003693 // userId is the target user
3694 int count = mCrossProfileIntentResolvers.size();
3695 for (int i = 0; i < count; i++) {
3696 int sourceUserId = mCrossProfileIntentResolvers.keyAt(i);
3697 CrossProfileIntentResolver cpir = mCrossProfileIntentResolvers.get(sourceUserId);
3698 boolean needsWriting = false;
Jeff Sharkey9f837a92014-10-24 12:07:24 -07003699 ArraySet<CrossProfileIntentFilter> cpifs =
3700 new ArraySet<CrossProfileIntentFilter>(cpir.filterSet());
Nicolas Prevote7024042014-07-08 15:47:17 +01003701 for (CrossProfileIntentFilter cpif : cpifs) {
3702 if (cpif.getTargetUserId() == userId) {
3703 needsWriting = true;
3704 cpir.removeFilter(cpif);
3705 }
3706 }
3707 if (needsWriting) {
3708 writePackageRestrictionsLPr(sourceUserId);
3709 }
Nicolas Prevota0f48852014-05-27 11:21:11 +01003710 }
3711 }
Amith Yamasani13593602012-03-22 16:16:17 -07003712 }
3713
Geremy Condra12c18382013-03-06 16:49:06 -08003714 // This should be called (at least) whenever an application is removed
3715 private void setFirstAvailableUid(int uid) {
3716 if (uid > mFirstAvailableUid) {
3717 mFirstAvailableUid = uid;
3718 }
3719 }
3720
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003721 // Returns -1 if we could not find an available UserId to assign
Kenny Root447106f2011-03-23 11:00:15 -07003722 private int newUserIdLPw(Object obj) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003723 // Let's be stupidly inefficient for now...
3724 final int N = mUserIds.size();
Geremy Condra12c18382013-03-06 16:49:06 -08003725 for (int i = mFirstAvailableUid; i < N; i++) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003726 if (mUserIds.get(i) == null) {
3727 mUserIds.set(i, obj);
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003728 return Process.FIRST_APPLICATION_UID + i;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003729 }
3730 }
3731
3732 // None left?
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003733 if (N > (Process.LAST_APPLICATION_UID-Process.FIRST_APPLICATION_UID)) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003734 return -1;
3735 }
3736
3737 mUserIds.add(obj);
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003738 return Process.FIRST_APPLICATION_UID + N;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003739 }
3740
Kenny Root0aaa0d92011-09-12 16:42:55 -07003741 public VerifierDeviceIdentity getVerifierDeviceIdentityLPw() {
3742 if (mVerifierDeviceIdentity == null) {
3743 mVerifierDeviceIdentity = VerifierDeviceIdentity.generate();
3744
3745 writeLPr();
3746 }
3747
3748 return mVerifierDeviceIdentity;
3749 }
3750
Kenny Root447106f2011-03-23 11:00:15 -07003751 public PackageSetting getDisabledSystemPkgLPr(String name) {
3752 PackageSetting ps = mDisabledSysPackages.get(name);
3753 return ps;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003754 }
3755
Jeff Sharkey9f837a92014-10-24 12:07:24 -07003756 private String compToString(ArraySet<String> cmp) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003757 return cmp != null ? Arrays.toString(cmp.toArray()) : "[]";
3758 }
3759
Amith Yamasani483f3b02012-03-13 16:08:00 -07003760 boolean isEnabledLPr(ComponentInfo componentInfo, int flags, int userId) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003761 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
3762 return true;
3763 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003764 final String pkgName = componentInfo.packageName;
3765 final PackageSetting packageSettings = mPackages.get(pkgName);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003766 if (PackageManagerService.DEBUG_SETTINGS) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003767 Log.v(PackageManagerService.TAG, "isEnabledLock - packageName = "
3768 + componentInfo.packageName + " componentName = " + componentInfo.name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003769 Log.v(PackageManagerService.TAG, "enabledComponents: "
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003770 + compToString(packageSettings.getEnabledComponents(userId)));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003771 Log.v(PackageManagerService.TAG, "disabledComponents: "
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003772 + compToString(packageSettings.getDisabledComponents(userId)));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003773 }
3774 if (packageSettings == null) {
3775 return false;
3776 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003777 PackageUserState ustate = packageSettings.readUserState(userId);
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08003778 if ((flags&PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS) != 0) {
3779 if (ustate.enabled == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
3780 return true;
3781 }
3782 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003783 if (ustate.enabled == COMPONENT_ENABLED_STATE_DISABLED
3784 || ustate.enabled == COMPONENT_ENABLED_STATE_DISABLED_USER
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08003785 || ustate.enabled == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003786 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003787 && ustate.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003788 return false;
3789 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003790 if (ustate.enabledComponents != null
3791 && ustate.enabledComponents.contains(componentInfo.name)) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003792 return true;
3793 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003794 if (ustate.disabledComponents != null
3795 && ustate.disabledComponents.contains(componentInfo.name)) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003796 return false;
3797 }
3798 return componentInfo.enabled;
3799 }
Kenny Root447106f2011-03-23 11:00:15 -07003800
3801 String getInstallerPackageNameLPr(String packageName) {
3802 final PackageSetting pkg = mPackages.get(packageName);
3803 if (pkg == null) {
3804 throw new IllegalArgumentException("Unknown package: " + packageName);
3805 }
3806 return pkg.installerPackageName;
3807 }
3808
Amith Yamasani483f3b02012-03-13 16:08:00 -07003809 int getApplicationEnabledSettingLPr(String packageName, int userId) {
Kenny Root447106f2011-03-23 11:00:15 -07003810 final PackageSetting pkg = mPackages.get(packageName);
3811 if (pkg == null) {
3812 throw new IllegalArgumentException("Unknown package: " + packageName);
3813 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003814 return pkg.getEnabled(userId);
Kenny Root447106f2011-03-23 11:00:15 -07003815 }
3816
Amith Yamasani483f3b02012-03-13 16:08:00 -07003817 int getComponentEnabledSettingLPr(ComponentName componentName, int userId) {
Kenny Root447106f2011-03-23 11:00:15 -07003818 final String packageName = componentName.getPackageName();
3819 final PackageSetting pkg = mPackages.get(packageName);
3820 if (pkg == null) {
3821 throw new IllegalArgumentException("Unknown component: " + componentName);
3822 }
3823 final String classNameStr = componentName.getClassName();
Amith Yamasani483f3b02012-03-13 16:08:00 -07003824 return pkg.getCurrentEnabledStateLPr(classNameStr, userId);
Kenny Root447106f2011-03-23 11:00:15 -07003825 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003826
Jeff Sharkeybd0e9e42015-04-30 16:04:50 -07003827 boolean setPackageStoppedStateLPw(PackageManagerService yucky, String packageName,
3828 boolean stopped, boolean allowedByPermission, int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003829 int appId = UserHandle.getAppId(uid);
Kenny Root447106f2011-03-23 11:00:15 -07003830 final PackageSetting pkgSetting = mPackages.get(packageName);
3831 if (pkgSetting == null) {
3832 throw new IllegalArgumentException("Unknown package: " + packageName);
3833 }
Amith Yamasani13593602012-03-22 16:16:17 -07003834 if (!allowedByPermission && (appId != pkgSetting.appId)) {
Kenny Root447106f2011-03-23 11:00:15 -07003835 throw new SecurityException(
3836 "Permission Denial: attempt to change stopped state from pid="
3837 + Binder.getCallingPid()
Amith Yamasani13593602012-03-22 16:16:17 -07003838 + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
Kenny Root447106f2011-03-23 11:00:15 -07003839 }
3840 if (DEBUG_STOPPED) {
3841 if (stopped) {
3842 RuntimeException e = new RuntimeException("here");
3843 e.fillInStackTrace();
3844 Slog.i(TAG, "Stopping package " + packageName, e);
3845 }
3846 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003847 if (pkgSetting.getStopped(userId) != stopped) {
3848 pkgSetting.setStopped(stopped, userId);
3849 // pkgSetting.pkg.mSetStopped = stopped;
3850 if (pkgSetting.getNotLaunched(userId)) {
Kenny Root447106f2011-03-23 11:00:15 -07003851 if (pkgSetting.installerPackageName != null) {
Jeff Sharkeybd0e9e42015-04-30 16:04:50 -07003852 yucky.sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH,
Kenny Root447106f2011-03-23 11:00:15 -07003853 pkgSetting.name, null,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003854 pkgSetting.installerPackageName, null, new int[] {userId});
Kenny Root447106f2011-03-23 11:00:15 -07003855 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003856 pkgSetting.setNotLaunched(false, userId);
Kenny Root447106f2011-03-23 11:00:15 -07003857 }
3858 return true;
3859 }
3860 return false;
3861 }
3862
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08003863 List<UserInfo> getAllUsers() {
Amith Yamasani7ea3e7d2012-04-20 15:19:35 -07003864 long id = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07003865 try {
Amith Yamasani920ace02012-09-20 22:15:37 -07003866 return UserManagerService.getInstance().getUsers(false);
Amith Yamasani483f3b02012-03-13 16:08:00 -07003867 } catch (NullPointerException npe) {
3868 // packagemanager not yet initialized
Amith Yamasani7ea3e7d2012-04-20 15:19:35 -07003869 } finally {
3870 Binder.restoreCallingIdentity(id);
Amith Yamasani483f3b02012-03-13 16:08:00 -07003871 }
3872 return null;
3873 }
3874
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07003875 /**
3876 * Return all {@link PackageSetting} that are actively installed on the
3877 * given {@link VolumeInfo#fsUuid}.
3878 */
3879 List<PackageSetting> getVolumePackagesLPr(String volumeUuid) {
3880 Preconditions.checkNotNull(volumeUuid);
3881 ArrayList<PackageSetting> res = new ArrayList<>();
3882 for (int i = 0; i < mPackages.size(); i++) {
3883 final PackageSetting setting = mPackages.valueAt(i);
3884 if (Objects.equals(volumeUuid, setting.volumeUuid)) {
3885 res.add(setting);
3886 }
3887 }
3888 return res;
3889 }
3890
Svetoslavc6d1c342015-02-26 14:44:43 -08003891 static void printFlags(PrintWriter pw, int val, Object[] spec) {
Joe Onorato20963df2012-01-04 18:13:24 -08003892 pw.print("[ ");
3893 for (int i=0; i<spec.length; i+=2) {
3894 int mask = (Integer)spec[i];
3895 if ((val & mask) != 0) {
3896 pw.print(spec[i+1]);
3897 pw.print(" ");
3898 }
3899 }
3900 pw.print("]");
3901 }
3902
3903 static final Object[] FLAG_DUMP_SPEC = new Object[] {
3904 ApplicationInfo.FLAG_SYSTEM, "SYSTEM",
3905 ApplicationInfo.FLAG_DEBUGGABLE, "DEBUGGABLE",
3906 ApplicationInfo.FLAG_HAS_CODE, "HAS_CODE",
3907 ApplicationInfo.FLAG_PERSISTENT, "PERSISTENT",
3908 ApplicationInfo.FLAG_FACTORY_TEST, "FACTORY_TEST",
3909 ApplicationInfo.FLAG_ALLOW_TASK_REPARENTING, "ALLOW_TASK_REPARENTING",
3910 ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA, "ALLOW_CLEAR_USER_DATA",
3911 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, "UPDATED_SYSTEM_APP",
3912 ApplicationInfo.FLAG_TEST_ONLY, "TEST_ONLY",
3913 ApplicationInfo.FLAG_VM_SAFE_MODE, "VM_SAFE_MODE",
3914 ApplicationInfo.FLAG_ALLOW_BACKUP, "ALLOW_BACKUP",
3915 ApplicationInfo.FLAG_KILL_AFTER_RESTORE, "KILL_AFTER_RESTORE",
3916 ApplicationInfo.FLAG_RESTORE_ANY_VERSION, "RESTORE_ANY_VERSION",
3917 ApplicationInfo.FLAG_EXTERNAL_STORAGE, "EXTERNAL_STORAGE",
3918 ApplicationInfo.FLAG_LARGE_HEAP, "LARGE_HEAP",
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003919 };
3920
3921 static final Object[] PRIVATE_FLAG_DUMP_SPEC = new Object[] {
3922 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED, "PRIVILEGED",
3923 ApplicationInfo.PRIVATE_FLAG_FORWARD_LOCK, "FORWARD_LOCK",
3924 ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE, "CANT_SAVE_STATE",
Joe Onorato20963df2012-01-04 18:13:24 -08003925 };
3926
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07003927 void dumpVersionLPr(IndentingPrintWriter pw) {
3928 pw.increaseIndent();
3929 for (int i= 0; i < mVersion.size(); i++) {
3930 final String volumeUuid = mVersion.keyAt(i);
3931 final VersionInfo ver = mVersion.valueAt(i);
3932 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
3933 pw.println("Internal:");
3934 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
3935 pw.println("External:");
3936 } else {
3937 pw.println("UUID " + volumeUuid + ":");
3938 }
3939 pw.increaseIndent();
3940 pw.printPair("sdkVersion", ver.sdkVersion);
3941 pw.printPair("databaseVersion", ver.databaseVersion);
3942 pw.println();
3943 pw.printPair("fingerprint", ver.fingerprint);
3944 pw.println();
3945 pw.decreaseIndent();
3946 }
3947 pw.decreaseIndent();
3948 }
3949
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07003950 void dumpPackageLPr(PrintWriter pw, String prefix, String checkinTag,
3951 ArraySet<String> permissionNames, PackageSetting ps, SimpleDateFormat sdf,
3952 Date date, List<UserInfo> users) {
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08003953 if (checkinTag != null) {
3954 pw.print(checkinTag);
3955 pw.print(",");
3956 pw.print(ps.realName != null ? ps.realName : ps.name);
3957 pw.print(",");
3958 pw.print(ps.appId);
3959 pw.print(",");
3960 pw.print(ps.versionCode);
3961 pw.print(",");
3962 pw.print(ps.firstInstallTime);
3963 pw.print(",");
3964 pw.print(ps.lastUpdateTime);
3965 pw.print(",");
3966 pw.print(ps.installerPackageName != null ? ps.installerPackageName : "?");
3967 pw.println();
Jeff Sharkeyc4d05fc2014-12-01 16:24:01 -08003968 if (ps.pkg != null) {
3969 pw.print(checkinTag); pw.print("-"); pw.print("splt,");
3970 pw.print("base,");
3971 pw.println(ps.pkg.baseRevisionCode);
3972 if (ps.pkg.splitNames != null) {
3973 for (int i = 0; i < ps.pkg.splitNames.length; i++) {
3974 pw.print(checkinTag); pw.print("-"); pw.print("splt,");
3975 pw.print(ps.pkg.splitNames[i]); pw.print(",");
3976 pw.println(ps.pkg.splitRevisionCodes[i]);
3977 }
3978 }
3979 }
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08003980 for (UserInfo user : users) {
3981 pw.print(checkinTag);
3982 pw.print("-");
3983 pw.print("usr");
3984 pw.print(",");
3985 pw.print(user.id);
3986 pw.print(",");
3987 pw.print(ps.getInstalled(user.id) ? "I" : "i");
Amith Yamasanie5bcff62014-07-19 15:44:09 -07003988 pw.print(ps.getHidden(user.id) ? "B" : "b");
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08003989 pw.print(ps.getStopped(user.id) ? "S" : "s");
3990 pw.print(ps.getNotLaunched(user.id) ? "l" : "L");
3991 pw.print(",");
3992 pw.print(ps.getEnabled(user.id));
3993 String lastDisabledAppCaller = ps.getLastDisabledAppCaller(user.id);
3994 pw.print(",");
3995 pw.print(lastDisabledAppCaller != null ? lastDisabledAppCaller : "?");
3996 pw.println();
3997 }
3998 return;
3999 }
4000
Dianne Hackbornc895be72013-03-11 17:48:43 -07004001 pw.print(prefix); pw.print("Package [");
4002 pw.print(ps.realName != null ? ps.realName : ps.name);
4003 pw.print("] (");
4004 pw.print(Integer.toHexString(System.identityHashCode(ps)));
4005 pw.println("):");
4006
Jeff Sharkeye31b8202015-04-29 21:44:57 -07004007 if (ps.frozen) {
4008 pw.print(prefix); pw.println(" FROZEN!");
4009 }
4010
Dianne Hackbornc895be72013-03-11 17:48:43 -07004011 if (ps.realName != null) {
4012 pw.print(prefix); pw.print(" compat name=");
4013 pw.println(ps.name);
4014 }
4015
Svetoslavc6d1c342015-02-26 14:44:43 -08004016 pw.print(prefix); pw.print(" userId="); pw.println(ps.appId);
4017
Dianne Hackbornc895be72013-03-11 17:48:43 -07004018 if (ps.sharedUser != null) {
4019 pw.print(prefix); pw.print(" sharedUser="); pw.println(ps.sharedUser);
4020 }
4021 pw.print(prefix); pw.print(" pkg="); pw.println(ps.pkg);
4022 pw.print(prefix); pw.print(" codePath="); pw.println(ps.codePathString);
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004023 if (permissionNames == null) {
4024 pw.print(prefix); pw.print(" resourcePath="); pw.println(ps.resourcePathString);
4025 pw.print(prefix); pw.print(" legacyNativeLibraryDir=");
4026 pw.println(ps.legacyNativeLibraryPathString);
4027 pw.print(prefix); pw.print(" primaryCpuAbi="); pw.println(ps.primaryCpuAbiString);
4028 pw.print(prefix); pw.print(" secondaryCpuAbi="); pw.println(ps.secondaryCpuAbiString);
4029 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004030 pw.print(prefix); pw.print(" versionCode="); pw.print(ps.versionCode);
4031 if (ps.pkg != null) {
4032 pw.print(" targetSdk="); pw.print(ps.pkg.applicationInfo.targetSdkVersion);
4033 }
4034 pw.println();
4035 if (ps.pkg != null) {
4036 pw.print(prefix); pw.print(" versionName="); pw.println(ps.pkg.mVersionName);
Jeff Sharkeyc4d05fc2014-12-01 16:24:01 -08004037 pw.print(prefix); pw.print(" splits="); dumpSplitNames(pw, ps.pkg); pw.println();
Dianne Hackbornc895be72013-03-11 17:48:43 -07004038 pw.print(prefix); pw.print(" applicationInfo=");
4039 pw.println(ps.pkg.applicationInfo.toString());
4040 pw.print(prefix); pw.print(" flags="); printFlags(pw, ps.pkg.applicationInfo.flags,
4041 FLAG_DUMP_SPEC); pw.println();
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004042 if (ps.pkg.applicationInfo.privateFlags != 0) {
4043 pw.print(prefix); pw.print(" privateFlags="); printFlags(pw,
4044 ps.pkg.applicationInfo.privateFlags, PRIVATE_FLAG_DUMP_SPEC); pw.println();
4045 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004046 pw.print(prefix); pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Dianne Hackbornc895be72013-03-11 17:48:43 -07004047 pw.print(prefix); pw.print(" supportsScreens=[");
4048 boolean first = true;
4049 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
4050 if (!first)
4051 pw.print(", ");
4052 first = false;
4053 pw.print("small");
4054 }
4055 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
4056 if (!first)
4057 pw.print(", ");
4058 first = false;
4059 pw.print("medium");
4060 }
4061 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
4062 if (!first)
4063 pw.print(", ");
4064 first = false;
4065 pw.print("large");
4066 }
4067 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
4068 if (!first)
4069 pw.print(", ");
4070 first = false;
4071 pw.print("xlarge");
4072 }
4073 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
4074 if (!first)
4075 pw.print(", ");
4076 first = false;
4077 pw.print("resizeable");
4078 }
4079 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
4080 if (!first)
4081 pw.print(", ");
4082 first = false;
4083 pw.print("anyDensity");
4084 }
4085 pw.println("]");
4086 if (ps.pkg.libraryNames != null && ps.pkg.libraryNames.size() > 0) {
4087 pw.print(prefix); pw.println(" libraries:");
4088 for (int i=0; i<ps.pkg.libraryNames.size(); i++) {
4089 pw.print(prefix); pw.print(" "); pw.println(ps.pkg.libraryNames.get(i));
4090 }
4091 }
4092 if (ps.pkg.usesLibraries != null && ps.pkg.usesLibraries.size() > 0) {
4093 pw.print(prefix); pw.println(" usesLibraries:");
4094 for (int i=0; i<ps.pkg.usesLibraries.size(); i++) {
4095 pw.print(prefix); pw.print(" "); pw.println(ps.pkg.usesLibraries.get(i));
4096 }
4097 }
4098 if (ps.pkg.usesOptionalLibraries != null
4099 && ps.pkg.usesOptionalLibraries.size() > 0) {
4100 pw.print(prefix); pw.println(" usesOptionalLibraries:");
4101 for (int i=0; i<ps.pkg.usesOptionalLibraries.size(); i++) {
4102 pw.print(prefix); pw.print(" ");
4103 pw.println(ps.pkg.usesOptionalLibraries.get(i));
4104 }
4105 }
4106 if (ps.pkg.usesLibraryFiles != null
4107 && ps.pkg.usesLibraryFiles.length > 0) {
4108 pw.print(prefix); pw.println(" usesLibraryFiles:");
4109 for (int i=0; i<ps.pkg.usesLibraryFiles.length; i++) {
4110 pw.print(prefix); pw.print(" "); pw.println(ps.pkg.usesLibraryFiles[i]);
4111 }
4112 }
4113 }
4114 pw.print(prefix); pw.print(" timeStamp=");
4115 date.setTime(ps.timeStamp);
4116 pw.println(sdf.format(date));
4117 pw.print(prefix); pw.print(" firstInstallTime=");
4118 date.setTime(ps.firstInstallTime);
4119 pw.println(sdf.format(date));
4120 pw.print(prefix); pw.print(" lastUpdateTime=");
4121 date.setTime(ps.lastUpdateTime);
4122 pw.println(sdf.format(date));
4123 if (ps.installerPackageName != null) {
4124 pw.print(prefix); pw.print(" installerPackageName=");
4125 pw.println(ps.installerPackageName);
4126 }
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07004127 if (ps.volumeUuid != null) {
4128 pw.print(prefix); pw.print(" volumeUuid=");
4129 pw.println(ps.volumeUuid);
4130 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004131 pw.print(prefix); pw.print(" signatures="); pw.println(ps.signatures);
Svetoslavcf959f62015-03-26 20:53:34 -07004132 pw.print(prefix); pw.print(" installPermissionsFixed=");
4133 pw.print(ps.installPermissionsFixed);
Dianne Hackbornc895be72013-03-11 17:48:43 -07004134 pw.print(" installStatus="); pw.println(ps.installStatus);
4135 pw.print(prefix); pw.print(" pkgFlags="); printFlags(pw, ps.pkgFlags, FLAG_DUMP_SPEC);
4136 pw.println();
Svetoslavc6d1c342015-02-26 14:44:43 -08004137
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004138 if (ps.pkg != null && ps.pkg.permissions != null && ps.pkg.permissions.size() > 0) {
4139 final ArrayList<PackageParser.Permission> perms = ps.pkg.permissions;
4140 pw.print(prefix); pw.println(" declared permissions:");
4141 for (int i=0; i<perms.size(); i++) {
4142 PackageParser.Permission perm = perms.get(i);
4143 if (permissionNames != null
4144 && !permissionNames.contains(perm.info.name)) {
4145 continue;
4146 }
4147 pw.print(prefix); pw.print(" "); pw.print(perm.info.name);
4148 pw.print(": prot=");
4149 pw.print(PermissionInfo.protectionToString(perm.info.protectionLevel));
4150 if ((perm.info.flags&PermissionInfo.FLAG_COSTS_MONEY) != 0) {
4151 pw.print(", COSTS_MONEY");
4152 }
Svet Ganov3e0be742015-08-07 23:06:00 -07004153 if ((perm.info.flags&PermissionInfo.FLAG_HIDDEN) != 0) {
Svet Ganov52153f42015-08-11 08:59:12 -07004154 pw.print(", HIDDEN");
Svet Ganov3e0be742015-08-07 23:06:00 -07004155 }
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004156 if ((perm.info.flags&PermissionInfo.FLAG_INSTALLED) != 0) {
4157 pw.print(", INSTALLED");
4158 }
4159 pw.println();
4160 }
4161 }
4162
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004163 if (ps.sharedUser == null || permissionNames != null) {
Svetoslavc6d1c342015-02-26 14:44:43 -08004164 PermissionsState permissionsState = ps.getPermissionsState();
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004165 dumpInstallPermissionsLPr(pw, prefix + " ", permissionNames, permissionsState);
Svetoslavc6d1c342015-02-26 14:44:43 -08004166 }
4167
Dianne Hackbornc895be72013-03-11 17:48:43 -07004168 for (UserInfo user : users) {
4169 pw.print(prefix); pw.print(" User "); pw.print(user.id); pw.print(": ");
4170 pw.print(" installed=");
4171 pw.print(ps.getInstalled(user.id));
Amith Yamasanie5bcff62014-07-19 15:44:09 -07004172 pw.print(" hidden=");
4173 pw.print(ps.getHidden(user.id));
Dianne Hackbornc895be72013-03-11 17:48:43 -07004174 pw.print(" stopped=");
4175 pw.print(ps.getStopped(user.id));
4176 pw.print(" notLaunched=");
4177 pw.print(ps.getNotLaunched(user.id));
4178 pw.print(" enabled=");
4179 pw.println(ps.getEnabled(user.id));
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07004180 String lastDisabledAppCaller = ps.getLastDisabledAppCaller(user.id);
4181 if (lastDisabledAppCaller != null) {
4182 pw.print(prefix); pw.print(" lastDisabledCaller: ");
4183 pw.println(lastDisabledAppCaller);
4184 }
Svetoslavc6d1c342015-02-26 14:44:43 -08004185
4186 if (ps.sharedUser == null) {
4187 PermissionsState permissionsState = ps.getPermissionsState();
4188 dumpGidsLPr(pw, prefix + " ", permissionsState.computeGids(user.id));
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004189 dumpRuntimePermissionsLPr(pw, prefix + " ", permissionNames, permissionsState
Svet Ganov8c7f7002015-05-07 10:48:44 -07004190 .getRuntimePermissionStates(user.id));
Svetoslavc6d1c342015-02-26 14:44:43 -08004191 }
4192
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004193 if (permissionNames == null) {
4194 ArraySet<String> cmp = ps.getDisabledComponents(user.id);
4195 if (cmp != null && cmp.size() > 0) {
4196 pw.print(prefix); pw.println(" disabledComponents:");
4197 for (String s : cmp) {
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004198 pw.print(prefix); pw.print(" "); pw.println(s);
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004199 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004200 }
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004201 cmp = ps.getEnabledComponents(user.id);
4202 if (cmp != null && cmp.size() > 0) {
4203 pw.print(prefix); pw.println(" enabledComponents:");
4204 for (String s : cmp) {
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004205 pw.print(prefix); pw.print(" "); pw.println(s);
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004206 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004207 }
4208 }
4209 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004210 }
4211
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004212 void dumpPackagesLPr(PrintWriter pw, String packageName, ArraySet<String> permissionNames,
4213 DumpState dumpState, boolean checkin) {
Kenny Root447106f2011-03-23 11:00:15 -07004214 final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
4215 final Date date = new Date();
4216 boolean printedSomething = false;
Amith Yamasani7ea3e7d2012-04-20 15:19:35 -07004217 List<UserInfo> users = getAllUsers();
Kenny Root447106f2011-03-23 11:00:15 -07004218 for (final PackageSetting ps : mPackages.values()) {
4219 if (packageName != null && !packageName.equals(ps.realName)
4220 && !packageName.equals(ps.name)) {
4221 continue;
4222 }
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004223 if (permissionNames != null
4224 && !ps.getPermissionsState().hasRequestedPermission(permissionNames)) {
4225 continue;
4226 }
Kenny Root447106f2011-03-23 11:00:15 -07004227
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004228 if (!checkin && packageName != null) {
Kenny Root447106f2011-03-23 11:00:15 -07004229 dumpState.setSharedUser(ps.sharedUser);
4230 }
4231
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004232 if (!checkin && !printedSomething) {
Kenny Root447106f2011-03-23 11:00:15 -07004233 if (dumpState.onTitlePrinted())
Dianne Hackborncbfd23e2013-06-11 14:26:53 -07004234 pw.println();
Kenny Root447106f2011-03-23 11:00:15 -07004235 pw.println("Packages:");
4236 printedSomething = true;
4237 }
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004238 dumpPackageLPr(pw, " ", checkin ? "pkg" : null, permissionNames, ps, sdf, date, users);
Kenny Root447106f2011-03-23 11:00:15 -07004239 }
4240
4241 printedSomething = false;
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004242 if (!checkin && mRenamedPackages.size() > 0 && permissionNames == null) {
Andy McFadden2f362292012-01-20 14:43:38 -08004243 for (final Map.Entry<String, String> e : mRenamedPackages.entrySet()) {
Kenny Root447106f2011-03-23 11:00:15 -07004244 if (packageName != null && !packageName.equals(e.getKey())
4245 && !packageName.equals(e.getValue())) {
4246 continue;
4247 }
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004248 if (!checkin) {
4249 if (!printedSomething) {
4250 if (dumpState.onTitlePrinted())
4251 pw.println();
4252 pw.println("Renamed packages:");
4253 printedSomething = true;
4254 }
4255 pw.print(" ");
4256 } else {
4257 pw.print("ren,");
Kenny Root447106f2011-03-23 11:00:15 -07004258 }
Kenny Root447106f2011-03-23 11:00:15 -07004259 pw.print(e.getKey());
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004260 pw.print(checkin ? " -> " : ",");
Kenny Root447106f2011-03-23 11:00:15 -07004261 pw.println(e.getValue());
4262 }
4263 }
4264
4265 printedSomething = false;
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004266 if (mDisabledSysPackages.size() > 0 && permissionNames == null) {
Kenny Root447106f2011-03-23 11:00:15 -07004267 for (final PackageSetting ps : mDisabledSysPackages.values()) {
4268 if (packageName != null && !packageName.equals(ps.realName)
4269 && !packageName.equals(ps.name)) {
4270 continue;
4271 }
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004272 if (!checkin && !printedSomething) {
Kenny Root447106f2011-03-23 11:00:15 -07004273 if (dumpState.onTitlePrinted())
Dianne Hackborncbfd23e2013-06-11 14:26:53 -07004274 pw.println();
Kenny Root447106f2011-03-23 11:00:15 -07004275 pw.println("Hidden system packages:");
4276 printedSomething = true;
4277 }
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004278 dumpPackageLPr(pw, " ", checkin ? "dis" : null, permissionNames, ps, sdf, date,
4279 users);
Kenny Root447106f2011-03-23 11:00:15 -07004280 }
4281 }
4282 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07004283
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004284 void dumpPermissionsLPr(PrintWriter pw, String packageName, ArraySet<String> permissionNames,
4285 DumpState dumpState) {
Kenny Root447106f2011-03-23 11:00:15 -07004286 boolean printedSomething = false;
4287 for (BasePermission p : mPermissions.values()) {
4288 if (packageName != null && !packageName.equals(p.sourcePackage)) {
4289 continue;
4290 }
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004291 if (permissionNames != null && !permissionNames.contains(p.name)) {
4292 continue;
4293 }
Kenny Root447106f2011-03-23 11:00:15 -07004294 if (!printedSomething) {
4295 if (dumpState.onTitlePrinted())
Dianne Hackborncbfd23e2013-06-11 14:26:53 -07004296 pw.println();
Kenny Root447106f2011-03-23 11:00:15 -07004297 pw.println("Permissions:");
4298 printedSomething = true;
4299 }
4300 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
4301 pw.print(Integer.toHexString(System.identityHashCode(p)));
4302 pw.println("):");
4303 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
4304 pw.print(" uid="); pw.print(p.uid);
Jeff Sharkey00f39042015-03-23 16:51:22 -07004305 pw.print(" gids="); pw.print(Arrays.toString(
4306 p.computeGids(UserHandle.USER_OWNER)));
Kenny Root447106f2011-03-23 11:00:15 -07004307 pw.print(" type="); pw.print(p.type);
Dianne Hackborne639da72012-02-21 15:11:13 -08004308 pw.print(" prot=");
4309 pw.println(PermissionInfo.protectionToString(p.protectionLevel));
Kenny Root447106f2011-03-23 11:00:15 -07004310 if (p.perm != null) {
4311 pw.print(" perm="); pw.println(p.perm);
Svet Ganov3e0be742015-08-07 23:06:00 -07004312 if ((p.perm.info.flags & PermissionInfo.FLAG_INSTALLED) == 0
4313 || (p.perm.info.flags & PermissionInfo.FLAG_HIDDEN) != 0) {
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004314 pw.print(" flags=0x"); pw.println(Integer.toHexString(p.perm.info.flags));
4315 }
4316 }
4317 if (p.packageSetting != null) {
4318 pw.print(" packageSetting="); pw.println(p.packageSetting);
Kenny Root447106f2011-03-23 11:00:15 -07004319 }
Jeff Sharkey1c27576a2012-04-11 19:07:08 -07004320 if (READ_EXTERNAL_STORAGE.equals(p.name)) {
Jeff Sharkey5d32e772012-04-12 15:59:23 -07004321 pw.print(" enforced=");
4322 pw.println(mReadExternalStorageEnforced);
Jeff Sharkey1c27576a2012-04-11 19:07:08 -07004323 }
Kenny Root447106f2011-03-23 11:00:15 -07004324 }
4325 }
Jeff Sharkey1c27576a2012-04-11 19:07:08 -07004326
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004327 void dumpSharedUsersLPr(PrintWriter pw, String packageName, ArraySet<String> permissionNames,
4328 DumpState dumpState, boolean checkin) {
Kenny Root447106f2011-03-23 11:00:15 -07004329 boolean printedSomething = false;
4330 for (SharedUserSetting su : mSharedUsers.values()) {
4331 if (packageName != null && su != dumpState.getSharedUser()) {
4332 continue;
4333 }
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004334 if (permissionNames != null
4335 && !su.getPermissionsState().hasRequestedPermission(permissionNames)) {
4336 continue;
4337 }
Dianne Hackbornd052a942014-11-21 15:23:13 -08004338 if (!checkin) {
4339 if (!printedSomething) {
4340 if (dumpState.onTitlePrinted())
4341 pw.println();
4342 pw.println("Shared users:");
4343 printedSomething = true;
4344 }
4345 pw.print(" SharedUser [");
4346 pw.print(su.name);
4347 pw.print("] (");
4348 pw.print(Integer.toHexString(System.identityHashCode(su)));
4349 pw.println("):");
Svetoslavc6d1c342015-02-26 14:44:43 -08004350
4351 String prefix = " ";
4352 pw.print(prefix); pw.print("userId="); pw.println(su.userId);
4353
4354 PermissionsState permissionsState = su.getPermissionsState();
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004355 dumpInstallPermissionsLPr(pw, prefix, permissionNames, permissionsState);
Svetoslavc6d1c342015-02-26 14:44:43 -08004356
4357 for (int userId : UserManagerService.getInstance().getUserIds()) {
4358 final int[] gids = permissionsState.computeGids(userId);
Svet Ganov8c7f7002015-05-07 10:48:44 -07004359 List<PermissionState> permissions = permissionsState
4360 .getRuntimePermissionStates(userId);
Svetoslavc6d1c342015-02-26 14:44:43 -08004361 if (!ArrayUtils.isEmpty(gids) || !permissions.isEmpty()) {
4362 pw.print(prefix); pw.print("User "); pw.print(userId); pw.println(": ");
4363 dumpGidsLPr(pw, prefix + " ", gids);
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004364 dumpRuntimePermissionsLPr(pw, prefix + " ", permissionNames, permissions);
Svetoslavc6d1c342015-02-26 14:44:43 -08004365 }
Dianne Hackbornd052a942014-11-21 15:23:13 -08004366 }
4367 } else {
4368 pw.print("suid,"); pw.print(su.userId); pw.print(","); pw.println(su.name);
Kenny Root447106f2011-03-23 11:00:15 -07004369 }
4370 }
4371 }
4372
4373 void dumpReadMessagesLPr(PrintWriter pw, DumpState dumpState) {
4374 pw.println("Settings parse messages:");
4375 pw.print(mReadMessages.toString());
4376 }
Jeff Sharkeyc4d05fc2014-12-01 16:24:01 -08004377
4378 private static void dumpSplitNames(PrintWriter pw, PackageParser.Package pkg) {
4379 if (pkg == null) {
4380 pw.print("unknown");
4381 } else {
4382 // [base:10, config.mdpi, config.xhdpi:12]
4383 pw.print("[");
4384 pw.print("base");
4385 if (pkg.baseRevisionCode != 0) {
4386 pw.print(":"); pw.print(pkg.baseRevisionCode);
4387 }
4388 if (pkg.splitNames != null) {
4389 for (int i = 0; i < pkg.splitNames.length; i++) {
4390 pw.print(", ");
4391 pw.print(pkg.splitNames[i]);
4392 if (pkg.splitRevisionCodes[i] != 0) {
4393 pw.print(":"); pw.print(pkg.splitRevisionCodes[i]);
4394 }
4395 }
4396 }
4397 pw.print("]");
4398 }
4399 }
Svetoslavc6d1c342015-02-26 14:44:43 -08004400
4401 void dumpGidsLPr(PrintWriter pw, String prefix, int[] gids) {
4402 if (!ArrayUtils.isEmpty(gids)) {
Fabrice Di Meglio62271722015-04-10 17:24:02 -07004403 pw.print(prefix);
4404 pw.print("gids="); pw.println(
Svetoslavc6d1c342015-02-26 14:44:43 -08004405 PackageManagerService.arrayToString(gids));
4406 }
4407 }
4408
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004409 void dumpRuntimePermissionsLPr(PrintWriter pw, String prefix, ArraySet<String> permissionNames,
Svet Ganov8c7f7002015-05-07 10:48:44 -07004410 List<PermissionState> permissionStates) {
4411 if (!permissionStates.isEmpty()) {
Svetoslavc6d1c342015-02-26 14:44:43 -08004412 pw.print(prefix); pw.println("runtime permissions:");
Svet Ganov8c7f7002015-05-07 10:48:44 -07004413 for (PermissionState permissionState : permissionStates) {
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004414 if (permissionNames != null
4415 && !permissionNames.contains(permissionState.getName())) {
4416 continue;
4417 }
Svet Ganov8c7f7002015-05-07 10:48:44 -07004418 pw.print(prefix); pw.print(" "); pw.print(permissionState.getName());
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004419 pw.print(": granted="); pw.print(permissionState.isGranted());
4420 pw.println(permissionFlagsToString(", flags=",
4421 permissionState.getFlags()));
Svetoslavc6d1c342015-02-26 14:44:43 -08004422 }
4423 }
4424 }
4425
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004426 private static String permissionFlagsToString(String prefix, int flags) {
4427 StringBuilder flagsString = null;
Svet Ganov77ab6a82015-07-03 12:03:02 -07004428 while (flags != 0) {
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004429 if (flagsString == null) {
4430 flagsString = new StringBuilder();
4431 flagsString.append(prefix);
4432 flagsString.append("[ ");
4433 }
Svet Ganov77ab6a82015-07-03 12:03:02 -07004434 final int flag = 1 << Integer.numberOfTrailingZeros(flags);
4435 flags &= ~flag;
4436 flagsString.append(PackageManager.permissionFlagToString(flag));
4437 flagsString.append(' ');
4438 }
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004439 if (flagsString != null) {
4440 flagsString.append(']');
4441 return flagsString.toString();
4442 } else {
4443 return "";
4444 }
Svet Ganov77ab6a82015-07-03 12:03:02 -07004445 }
4446
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004447 void dumpInstallPermissionsLPr(PrintWriter pw, String prefix, ArraySet<String> permissionNames,
Svetoslavc6d1c342015-02-26 14:44:43 -08004448 PermissionsState permissionsState) {
Svet Ganov8c7f7002015-05-07 10:48:44 -07004449 List<PermissionState> permissionStates = permissionsState.getInstallPermissionStates();
4450 if (!permissionStates.isEmpty()) {
Svetoslavc6d1c342015-02-26 14:44:43 -08004451 pw.print(prefix); pw.println("install permissions:");
Svet Ganov8c7f7002015-05-07 10:48:44 -07004452 for (PermissionState permissionState : permissionStates) {
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004453 if (permissionNames != null
4454 && !permissionNames.contains(permissionState.getName())) {
4455 continue;
4456 }
Svet Ganov8c7f7002015-05-07 10:48:44 -07004457 pw.print(prefix); pw.print(" "); pw.print(permissionState.getName());
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004458 pw.print(": granted="); pw.print(permissionState.isGranted());
4459 pw.println(permissionFlagsToString(", flags=",
Svet Ganov8c7f7002015-05-07 10:48:44 -07004460 permissionState.getFlags()));
Svetoslavc6d1c342015-02-26 14:44:43 -08004461 }
4462 }
4463 }
4464
4465 public void writeRuntimePermissionsForUserLPr(int userId, boolean sync) {
4466 if (sync) {
4467 mRuntimePermissionsPersistence.writePermissionsForUserSyncLPr(userId);
4468 } else {
4469 mRuntimePermissionsPersistence.writePermissionsForUserAsyncLPr(userId);
4470 }
4471 }
4472
4473 private final class RuntimePermissionPersistence {
4474 private static final long WRITE_PERMISSIONS_DELAY_MILLIS = 200;
4475
4476 private static final long MAX_WRITE_PERMISSIONS_DELAY_MILLIS = 2000;
4477
4478 private final Handler mHandler = new MyHandler();
4479
4480 private final Object mLock;
4481
4482 @GuardedBy("mLock")
Svet Ganovba3ba812015-06-26 10:54:06 -07004483 private final SparseBooleanArray mWriteScheduled = new SparseBooleanArray();
Svetoslavc6d1c342015-02-26 14:44:43 -08004484
4485 @GuardedBy("mLock")
Svet Ganovba3ba812015-06-26 10:54:06 -07004486 // The mapping keys are user ids.
4487 private final SparseLongArray mLastNotWrittenMutationTimesMillis = new SparseLongArray();
4488
4489 @GuardedBy("mLock")
4490 // The mapping keys are user ids.
4491 private final SparseArray<String> mFingerprints = new SparseArray<>();
4492
4493 @GuardedBy("mLock")
4494 // The mapping keys are user ids.
4495 private final SparseBooleanArray mDefaultPermissionsGranted = new SparseBooleanArray();
Svetoslavc6d1c342015-02-26 14:44:43 -08004496
4497 public RuntimePermissionPersistence(Object lock) {
4498 mLock = lock;
4499 }
4500
Svet Ganovba3ba812015-06-26 10:54:06 -07004501 public boolean areDefaultRuntimPermissionsGrantedLPr(int userId) {
4502 return mDefaultPermissionsGranted.get(userId);
4503 }
4504
4505 public void onDefaultRuntimePermissionsGrantedLPr(int userId) {
4506 mFingerprints.put(userId, Build.FINGERPRINT);
4507 writePermissionsForUserAsyncLPr(userId);
4508 }
4509
Svetoslavc6d1c342015-02-26 14:44:43 -08004510 public void writePermissionsForUserSyncLPr(int userId) {
4511 mHandler.removeMessages(userId);
4512 writePermissionsSync(userId);
4513 }
4514
4515 public void writePermissionsForUserAsyncLPr(int userId) {
4516 final long currentTimeMillis = SystemClock.uptimeMillis();
4517
4518 if (mWriteScheduled.get(userId)) {
4519 mHandler.removeMessages(userId);
4520
4521 // If enough time passed, write without holding off anymore.
4522 final long lastNotWrittenMutationTimeMillis = mLastNotWrittenMutationTimesMillis
4523 .get(userId);
4524 final long timeSinceLastNotWrittenMutationMillis = currentTimeMillis
4525 - lastNotWrittenMutationTimeMillis;
4526 if (timeSinceLastNotWrittenMutationMillis >= MAX_WRITE_PERMISSIONS_DELAY_MILLIS) {
4527 mHandler.obtainMessage(userId).sendToTarget();
4528 return;
4529 }
4530
4531 // Hold off a bit more as settings are frequently changing.
4532 final long maxDelayMillis = Math.max(lastNotWrittenMutationTimeMillis
4533 + MAX_WRITE_PERMISSIONS_DELAY_MILLIS - currentTimeMillis, 0);
4534 final long writeDelayMillis = Math.min(WRITE_PERMISSIONS_DELAY_MILLIS,
4535 maxDelayMillis);
4536
4537 Message message = mHandler.obtainMessage(userId);
4538 mHandler.sendMessageDelayed(message, writeDelayMillis);
4539 } else {
4540 mLastNotWrittenMutationTimesMillis.put(userId, currentTimeMillis);
4541 Message message = mHandler.obtainMessage(userId);
4542 mHandler.sendMessageDelayed(message, WRITE_PERMISSIONS_DELAY_MILLIS);
4543 mWriteScheduled.put(userId, true);
4544 }
4545 }
4546
4547 private void writePermissionsSync(int userId) {
4548 AtomicFile destination = new AtomicFile(getUserRuntimePermissionsFile(userId));
4549
Svet Ganov8c7f7002015-05-07 10:48:44 -07004550 ArrayMap<String, List<PermissionState>> permissionsForPackage = new ArrayMap<>();
4551 ArrayMap<String, List<PermissionState>> permissionsForSharedUser = new ArrayMap<>();
Svetoslavc6d1c342015-02-26 14:44:43 -08004552
4553 synchronized (mLock) {
4554 mWriteScheduled.delete(userId);
4555
4556 final int packageCount = mPackages.size();
4557 for (int i = 0; i < packageCount; i++) {
4558 String packageName = mPackages.keyAt(i);
4559 PackageSetting packageSetting = mPackages.valueAt(i);
4560 if (packageSetting.sharedUser == null) {
4561 PermissionsState permissionsState = packageSetting.getPermissionsState();
Svet Ganov8c7f7002015-05-07 10:48:44 -07004562 List<PermissionState> permissionsStates = permissionsState
4563 .getRuntimePermissionStates(userId);
4564 if (!permissionsStates.isEmpty()) {
4565 permissionsForPackage.put(packageName, permissionsStates);
Svetoslavc6d1c342015-02-26 14:44:43 -08004566 }
4567 }
4568 }
4569
4570 final int sharedUserCount = mSharedUsers.size();
4571 for (int i = 0; i < sharedUserCount; i++) {
4572 String sharedUserName = mSharedUsers.keyAt(i);
4573 SharedUserSetting sharedUser = mSharedUsers.valueAt(i);
4574 PermissionsState permissionsState = sharedUser.getPermissionsState();
Svet Ganov8c7f7002015-05-07 10:48:44 -07004575 List<PermissionState> permissionsStates = permissionsState
4576 .getRuntimePermissionStates(userId);
4577 if (!permissionsStates.isEmpty()) {
4578 permissionsForSharedUser.put(sharedUserName, permissionsStates);
Svetoslavc6d1c342015-02-26 14:44:43 -08004579 }
4580 }
4581 }
4582
4583 FileOutputStream out = null;
4584 try {
4585 out = destination.startWrite();
4586
4587 XmlSerializer serializer = Xml.newSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01004588 serializer.setOutput(out, StandardCharsets.UTF_8.name());
Svetoslavc6d1c342015-02-26 14:44:43 -08004589 serializer.setFeature(
4590 "http://xmlpull.org/v1/doc/features.html#indent-output", true);
4591 serializer.startDocument(null, true);
4592 serializer.startTag(null, TAG_RUNTIME_PERMISSIONS);
4593
Svet Ganovba3ba812015-06-26 10:54:06 -07004594 String fingerprint = mFingerprints.get(userId);
Svetoslavcdfd2302015-06-25 19:07:31 -07004595 if (fingerprint != null) {
4596 serializer.attribute(null, ATTR_FINGERPRINT, fingerprint);
4597 }
Svet Ganovba3ba812015-06-26 10:54:06 -07004598
Svetoslavc6d1c342015-02-26 14:44:43 -08004599 final int packageCount = permissionsForPackage.size();
4600 for (int i = 0; i < packageCount; i++) {
4601 String packageName = permissionsForPackage.keyAt(i);
Svet Ganov8c7f7002015-05-07 10:48:44 -07004602 List<PermissionState> permissionStates = permissionsForPackage.valueAt(i);
Svetoslavc6d1c342015-02-26 14:44:43 -08004603 serializer.startTag(null, TAG_PACKAGE);
4604 serializer.attribute(null, ATTR_NAME, packageName);
Svet Ganov8c7f7002015-05-07 10:48:44 -07004605 writePermissions(serializer, permissionStates);
Svetoslavc6d1c342015-02-26 14:44:43 -08004606 serializer.endTag(null, TAG_PACKAGE);
4607 }
4608
4609 final int sharedUserCount = permissionsForSharedUser.size();
4610 for (int i = 0; i < sharedUserCount; i++) {
4611 String packageName = permissionsForSharedUser.keyAt(i);
Svet Ganov8c7f7002015-05-07 10:48:44 -07004612 List<PermissionState> permissionStates = permissionsForSharedUser.valueAt(i);
Svetoslavc6d1c342015-02-26 14:44:43 -08004613 serializer.startTag(null, TAG_SHARED_USER);
4614 serializer.attribute(null, ATTR_NAME, packageName);
Svet Ganov8c7f7002015-05-07 10:48:44 -07004615 writePermissions(serializer, permissionStates);
Svetoslavc6d1c342015-02-26 14:44:43 -08004616 serializer.endTag(null, TAG_SHARED_USER);
4617 }
4618
4619 serializer.endTag(null, TAG_RUNTIME_PERMISSIONS);
4620 serializer.endDocument();
4621 destination.finishWrite(out);
Svet Ganovba0821e2015-04-22 13:34:31 -07004622
Svet Ganovba3ba812015-06-26 10:54:06 -07004623 if (Build.FINGERPRINT.equals(fingerprint)) {
4624 mDefaultPermissionsGranted.put(userId, true);
4625 }
4626 // Any error while writing is fatal.
Svet Ganovba0821e2015-04-22 13:34:31 -07004627 } catch (Throwable t) {
Svetoslavc6d1c342015-02-26 14:44:43 -08004628 Slog.wtf(PackageManagerService.TAG,
Svet Ganovba0821e2015-04-22 13:34:31 -07004629 "Failed to write settings, restoring backup", t);
Svetoslavc6d1c342015-02-26 14:44:43 -08004630 destination.failWrite(out);
4631 } finally {
4632 IoUtils.closeQuietly(out);
4633 }
4634 }
4635
4636 private void onUserRemoved(int userId) {
4637 // Make sure we do not
4638 mHandler.removeMessages(userId);
4639
4640 for (SettingBase sb : mPackages.values()) {
Svet Ganov8c7f7002015-05-07 10:48:44 -07004641 revokeRuntimePermissionsAndClearFlags(sb, userId);
Svetoslavc6d1c342015-02-26 14:44:43 -08004642 }
4643
4644 for (SettingBase sb : mSharedUsers.values()) {
Svet Ganov8c7f7002015-05-07 10:48:44 -07004645 revokeRuntimePermissionsAndClearFlags(sb, userId);
Svetoslavc6d1c342015-02-26 14:44:43 -08004646 }
4647 }
4648
Svet Ganov8c7f7002015-05-07 10:48:44 -07004649 private void revokeRuntimePermissionsAndClearFlags(SettingBase sb, int userId) {
Svetoslavc6d1c342015-02-26 14:44:43 -08004650 PermissionsState permissionsState = sb.getPermissionsState();
Svet Ganov8c7f7002015-05-07 10:48:44 -07004651 for (PermissionState permissionState
4652 : permissionsState.getRuntimePermissionStates(userId)) {
4653 BasePermission bp = mPermissions.get(permissionState.getName());
Svetoslavc6d1c342015-02-26 14:44:43 -08004654 if (bp != null) {
4655 permissionsState.revokeRuntimePermission(bp, userId);
Svet Ganov8c7f7002015-05-07 10:48:44 -07004656 permissionsState.updatePermissionFlags(bp, userId,
4657 PackageManager.MASK_PERMISSION_FLAGS, 0);
Svetoslavc6d1c342015-02-26 14:44:43 -08004658 }
4659 }
4660 }
4661
Svet Ganovadc1cf42015-06-15 16:36:24 -07004662 public void deleteUserRuntimePermissionsFile(int userId) {
4663 getUserRuntimePermissionsFile(userId).delete();
4664 }
4665
Svetoslavc6d1c342015-02-26 14:44:43 -08004666 public void readStateForUserSyncLPr(int userId) {
4667 File permissionsFile = getUserRuntimePermissionsFile(userId);
4668 if (!permissionsFile.exists()) {
4669 return;
4670 }
4671
4672 FileInputStream in;
4673 try {
Svetoslav3dcdd372015-05-29 13:00:32 -07004674 in = new AtomicFile(permissionsFile).openRead();
Svetoslavc6d1c342015-02-26 14:44:43 -08004675 } catch (FileNotFoundException fnfe) {
4676 Slog.i(PackageManagerService.TAG, "No permissions state");
4677 return;
4678 }
4679
4680 try {
4681 XmlPullParser parser = Xml.newPullParser();
4682 parser.setInput(in, null);
4683 parseRuntimePermissionsLPr(parser, userId);
Svet Ganovba0821e2015-04-22 13:34:31 -07004684
Svet Ganove723e542015-04-23 11:58:26 -07004685 } catch (XmlPullParserException | IOException e) {
Svetoslavc6d1c342015-02-26 14:44:43 -08004686 throw new IllegalStateException("Failed parsing permissions file: "
Svet Ganove723e542015-04-23 11:58:26 -07004687 + permissionsFile , e);
Svetoslavc6d1c342015-02-26 14:44:43 -08004688 } finally {
4689 IoUtils.closeQuietly(in);
4690 }
4691 }
4692
4693 private void parseRuntimePermissionsLPr(XmlPullParser parser, int userId)
4694 throws IOException, XmlPullParserException {
Svet Ganov12a692a2015-03-28 19:34:15 -07004695 final int outerDepth = parser.getDepth();
4696 int type;
4697 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
4698 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
4699 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
4700 continue;
4701 }
Svetoslavc6d1c342015-02-26 14:44:43 -08004702
Svet Ganov12a692a2015-03-28 19:34:15 -07004703 switch (parser.getName()) {
Svet Ganovba3ba812015-06-26 10:54:06 -07004704 case TAG_RUNTIME_PERMISSIONS: {
4705 String fingerprint = parser.getAttributeValue(null, ATTR_FINGERPRINT);
4706 mFingerprints.put(userId, fingerprint);
4707 final boolean defaultsGranted = Build.FINGERPRINT.equals(fingerprint);
4708 mDefaultPermissionsGranted.put(userId, defaultsGranted);
4709 } break;
4710
Svet Ganov12a692a2015-03-28 19:34:15 -07004711 case TAG_PACKAGE: {
4712 String name = parser.getAttributeValue(null, ATTR_NAME);
4713 PackageSetting ps = mPackages.get(name);
4714 if (ps == null) {
4715 Slog.w(PackageManagerService.TAG, "Unknown package:" + name);
4716 XmlUtils.skipCurrentTag(parser);
4717 continue;
4718 }
4719 parsePermissionsLPr(parser, ps.getPermissionsState(), userId);
4720 } break;
Svetoslavc6d1c342015-02-26 14:44:43 -08004721
Svet Ganov12a692a2015-03-28 19:34:15 -07004722 case TAG_SHARED_USER: {
4723 String name = parser.getAttributeValue(null, ATTR_NAME);
4724 SharedUserSetting sus = mSharedUsers.get(name);
4725 if (sus == null) {
4726 Slog.w(PackageManagerService.TAG, "Unknown shared user:" + name);
4727 XmlUtils.skipCurrentTag(parser);
4728 continue;
4729 }
4730 parsePermissionsLPr(parser, sus.getPermissionsState(), userId);
4731 } break;
Svetoslavc6d1c342015-02-26 14:44:43 -08004732 }
4733 }
Svetoslavc6d1c342015-02-26 14:44:43 -08004734 }
4735
Svet Ganov12a692a2015-03-28 19:34:15 -07004736 private void parsePermissionsLPr(XmlPullParser parser, PermissionsState permissionsState,
Svetoslavc6d1c342015-02-26 14:44:43 -08004737 int userId) throws IOException, XmlPullParserException {
Svet Ganov12a692a2015-03-28 19:34:15 -07004738 final int outerDepth = parser.getDepth();
4739 int type;
4740 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
4741 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
4742 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
4743 continue;
Svetoslavc6d1c342015-02-26 14:44:43 -08004744 }
Svetoslavc6d1c342015-02-26 14:44:43 -08004745
Svet Ganov12a692a2015-03-28 19:34:15 -07004746 switch (parser.getName()) {
4747 case TAG_ITEM: {
4748 String name = parser.getAttributeValue(null, ATTR_NAME);
4749 BasePermission bp = mPermissions.get(name);
4750 if (bp == null) {
4751 Slog.w(PackageManagerService.TAG, "Unknown permission:" + name);
4752 XmlUtils.skipCurrentTag(parser);
4753 continue;
4754 }
Svetoslavc6d1c342015-02-26 14:44:43 -08004755
Svet Ganov8c7f7002015-05-07 10:48:44 -07004756 String grantedStr = parser.getAttributeValue(null, ATTR_GRANTED);
4757 final boolean granted = grantedStr == null
4758 || Boolean.parseBoolean(grantedStr);
4759
4760 String flagsStr = parser.getAttributeValue(null, ATTR_FLAGS);
4761 final int flags = (flagsStr != null)
4762 ? Integer.parseInt(flagsStr, 16) : 0;
4763
4764 if (granted) {
Svet Ganovadc1cf42015-06-15 16:36:24 -07004765 permissionsState.grantRuntimePermission(bp, userId);
4766 permissionsState.updatePermissionFlags(bp, userId,
Svet Ganov8c7f7002015-05-07 10:48:44 -07004767 PackageManager.MASK_PERMISSION_FLAGS, flags);
Svet Ganov8c7f7002015-05-07 10:48:44 -07004768 } else {
Svet Ganovadc1cf42015-06-15 16:36:24 -07004769 permissionsState.updatePermissionFlags(bp, userId,
4770 PackageManager.MASK_PERMISSION_FLAGS, flags);
Svet Ganov12a692a2015-03-28 19:34:15 -07004771 }
Svet Ganov8c7f7002015-05-07 10:48:44 -07004772
Svet Ganov12a692a2015-03-28 19:34:15 -07004773 } break;
Svetoslavc6d1c342015-02-26 14:44:43 -08004774 }
Svetoslavc6d1c342015-02-26 14:44:43 -08004775 }
Svetoslavc6d1c342015-02-26 14:44:43 -08004776 }
4777
Svet Ganov8c7f7002015-05-07 10:48:44 -07004778 private void writePermissions(XmlSerializer serializer,
4779 List<PermissionState> permissionStates) throws IOException {
4780 for (PermissionState permissionState : permissionStates) {
Svetoslavc6d1c342015-02-26 14:44:43 -08004781 serializer.startTag(null, TAG_ITEM);
Svet Ganov8c7f7002015-05-07 10:48:44 -07004782 serializer.attribute(null, ATTR_NAME,permissionState.getName());
4783 serializer.attribute(null, ATTR_GRANTED,
4784 String.valueOf(permissionState.isGranted()));
4785 serializer.attribute(null, ATTR_FLAGS,
4786 Integer.toHexString(permissionState.getFlags()));
Svetoslavc6d1c342015-02-26 14:44:43 -08004787 serializer.endTag(null, TAG_ITEM);
4788 }
4789 }
4790
4791 private final class MyHandler extends Handler {
4792 public MyHandler() {
4793 super(BackgroundThread.getHandler().getLooper());
4794 }
4795
4796 @Override
4797 public void handleMessage(Message message) {
4798 final int userId = message.what;
4799 Runnable callback = (Runnable) message.obj;
4800 writePermissionsSync(userId);
4801 if (callback != null) {
4802 callback.run();
4803 }
4804 }
4805 }
4806 }
Andy McFadden2f362292012-01-20 14:43:38 -08004807}