blob: d2964bbe2e222d2d975a605163e113a25c0ead02 [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;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070030
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080031import android.content.IntentFilter;
32import android.content.pm.ActivityInfo;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -080033import android.content.pm.IntentFilterVerificationInfo;
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080034import android.content.pm.ResolveInfo;
35import android.net.Uri;
Narayan Kamathff110bd2014-07-04 18:30:45 +010036import android.os.Binder;
Jeff Sharkey4ed745d2014-07-15 20:39:15 -070037import android.os.Build;
Narayan Kamathff110bd2014-07-04 18:30:45 +010038import android.os.Environment;
39import android.os.FileUtils;
Svetoslavc6d1c342015-02-26 14:44:43 -080040import android.os.Handler;
41import android.os.Message;
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080042import android.os.PatternMatcher;
Narayan Kamathff110bd2014-07-04 18:30:45 +010043import android.os.Process;
Svetoslavc6d1c342015-02-26 14:44:43 -080044import android.os.SystemClock;
Narayan Kamathff110bd2014-07-04 18:30:45 +010045import android.os.UserHandle;
Amith Yamasani26f9ea32014-09-11 10:56:51 -070046import android.os.UserManager;
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -070047import android.os.storage.VolumeInfo;
Svetoslavc6d1c342015-02-26 14:44:43 -080048import android.util.AtomicFile;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -080049import android.text.TextUtils;
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080050import android.util.LogPrinter;
Svetoslavc6d1c342015-02-26 14:44:43 -080051import android.util.SparseBooleanArray;
52import android.util.SparseLongArray;
Christopher Tatee012a232015-04-01 17:18:50 -070053
Svetoslavc6d1c342015-02-26 14:44:43 -080054import com.android.internal.annotations.GuardedBy;
55import com.android.internal.os.BackgroundThread;
56import com.android.internal.util.ArrayUtils;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070057import com.android.internal.util.FastXmlSerializer;
58import com.android.internal.util.JournaledFile;
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -070059import com.android.internal.util.Preconditions;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070060import com.android.internal.util.XmlUtils;
Christopher Tatee012a232015-04-01 17:18:50 -070061import com.android.server.backup.PreferredActivityBackupHelper;
Kenny Root447106f2011-03-23 11:00:15 -070062import com.android.server.pm.PackageManagerService.DumpState;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070063
Svetoslavc6d1c342015-02-26 14:44:43 -080064import java.io.FileNotFoundException;
Narayan Kamathdf6d6dc2014-04-28 14:18:34 +010065import java.util.Collection;
Alexandra Gherghina6e2ae252014-06-12 16:03:58 +010066
Kenny Rootcf0b38c2011-03-22 14:17:59 -070067import org.xmlpull.v1.XmlPullParser;
68import org.xmlpull.v1.XmlPullParserException;
69import org.xmlpull.v1.XmlSerializer;
70
Kenny Root447106f2011-03-23 11:00:15 -070071import android.content.ComponentName;
72import android.content.Intent;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070073import android.content.pm.ApplicationInfo;
74import android.content.pm.ComponentInfo;
Dianne Hackborn7767eac2012-08-23 18:25:40 -070075import android.content.pm.PackageCleanItem;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070076import android.content.pm.PackageManager;
77import android.content.pm.PackageParser;
78import android.content.pm.PermissionInfo;
79import android.content.pm.Signature;
Amith Yamasani483f3b02012-03-13 16:08:00 -070080import android.content.pm.UserInfo;
Dianne Hackborn7767eac2012-08-23 18:25:40 -070081import android.content.pm.PackageUserState;
Kenny Root0aaa0d92011-09-12 16:42:55 -070082import android.content.pm.VerifierDeviceIdentity;
Jeff Sharkey9f837a92014-10-24 12:07:24 -070083import android.util.ArrayMap;
84import android.util.ArraySet;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070085import android.util.Log;
86import android.util.Slog;
87import android.util.SparseArray;
88import android.util.Xml;
89
90import java.io.BufferedOutputStream;
91import java.io.File;
92import java.io.FileInputStream;
93import java.io.FileOutputStream;
94import java.io.IOException;
95import java.io.PrintWriter;
Kenny Root447106f2011-03-23 11:00:15 -070096import java.text.SimpleDateFormat;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070097import java.util.ArrayList;
98import java.util.Arrays;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -080099import java.util.Collections;
Kenny Root447106f2011-03-23 11:00:15 -0700100import java.util.Date;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700101import java.util.Iterator;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700102import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800103import java.util.Map;
Jeff Sharkey84f12942014-07-10 17:48:11 -0700104import java.util.Objects;
Dianne Hackborn63092712012-10-07 14:45:35 -0700105import java.util.Set;
106import java.util.Map.Entry;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700107
Kenny Root62539e92011-11-10 09:35:38 -0800108import libcore.io.IoUtils;
109
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700110/**
111 * Holds information about dynamic settings.
112 */
113final class Settings {
Kenny Root447106f2011-03-23 11:00:15 -0700114 private static final String TAG = "PackageSettings";
115
Kenny Rootc1c0d3c2014-04-24 13:36:40 -0700116 /**
117 * Current version of the package database. Set it to the latest version in
118 * the {@link DatabaseVersion} class below to ensure the database upgrade
119 * doesn't happen repeatedly.
120 * <p>
121 * Note that care should be taken to make sure all database upgrades are
122 * idempotent.
123 */
Jeff Sharkeyd68b87c2014-11-12 12:18:11 -0800124 private static final int CURRENT_DATABASE_VERSION = DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
Kenny Rootc1c0d3c2014-04-24 13:36:40 -0700125
126 /**
127 * This class contains constants that can be referred to from upgrade code.
128 * Insert constant values here that describe the upgrade reason. The version
129 * code must be monotonically increasing.
130 */
131 public static class DatabaseVersion {
132 /**
133 * The initial version of the database.
134 */
135 public static final int FIRST_VERSION = 1;
Kenny Roota8e65fd2014-04-24 11:44:47 -0700136
137 /**
138 * Migrating the Signature array from the entire certificate chain to
139 * just the signing certificate.
140 */
141 public static final int SIGNATURE_END_ENTITY = 2;
Jeff Sharkeyd68b87c2014-11-12 12:18:11 -0800142
143 /**
144 * There was a window of time in
145 * {@link android.os.Build.VERSION_CODES#LOLLIPOP} where we persisted
146 * certificates after potentially mutating them. To switch back to the
147 * original untouched certificates, we need to force a collection pass.
148 */
149 public static final int SIGNATURE_MALFORMED_RECOVER = 3;
Kenny Rootc1c0d3c2014-04-24 13:36:40 -0700150 }
151
Kenny Root447106f2011-03-23 11:00:15 -0700152 private static final boolean DEBUG_STOPPED = false;
Amith Yamasani258848d2012-08-10 17:06:33 -0700153 private static final boolean DEBUG_MU = false;
Kenny Root447106f2011-03-23 11:00:15 -0700154
Svetoslavc6d1c342015-02-26 14:44:43 -0800155 private static final String RUNTIME_PERMISSIONS_FILE_NAME = "runtime-permissions.xml";
156
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -0700157 private static final String TAG_READ_EXTERNAL_STORAGE = "read-external-storage";
158 private static final String ATTR_ENFORCEMENT = "enforcement";
159
Amith Yamasani483f3b02012-03-13 16:08:00 -0700160 private static final String TAG_ITEM = "item";
161 private static final String TAG_DISABLED_COMPONENTS = "disabled-components";
162 private static final String TAG_ENABLED_COMPONENTS = "enabled-components";
163 private static final String TAG_PACKAGE_RESTRICTIONS = "package-restrictions";
164 private static final String TAG_PACKAGE = "pkg";
Svetoslavc6d1c342015-02-26 14:44:43 -0800165 private static final String TAG_SHARED_USER = "shared-user";
166 private static final String TAG_RUNTIME_PERMISSIONS = "runtime-permissions";
167 private static final String TAG_PERMISSIONS = "perms";
Sander Alewijnseaf597622014-03-20 18:44:57 +0000168 private static final String TAG_PERSISTENT_PREFERRED_ACTIVITIES =
169 "persistent-preferred-activities";
Nicolas Prevot81948992014-05-16 18:25:26 +0100170 static final String TAG_CROSS_PROFILE_INTENT_FILTERS =
171 "crossProfile-intent-filters";
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -0800172 public static final String TAG_DOMAIN_VERIFICATION = "domain-verification";
Fabrice Di Meglio62271722015-04-10 17:24:02 -0700173 public static final String TAG_DEFAULT_APPS= "default-apps";
174 public static final String TAG_DEFAULT_BROWSER= "default-browser";
Amith Yamasani483f3b02012-03-13 16:08:00 -0700175
176 private static final String ATTR_NAME = "name";
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700177 private static final String ATTR_USER = "user";
178 private static final String ATTR_CODE = "code";
Amith Yamasani483f3b02012-03-13 16:08:00 -0700179 private static final String ATTR_NOT_LAUNCHED = "nl";
180 private static final String ATTR_ENABLED = "enabled";
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -0700181 private static final String ATTR_ENABLED_CALLER = "enabledCaller";
Amith Yamasani483f3b02012-03-13 16:08:00 -0700182 private static final String ATTR_STOPPED = "stopped";
Amith Yamasanie5bcff62014-07-19 15:44:09 -0700183 // Legacy, here for reading older versions of the package-restrictions.
Amith Yamasani655d0e22013-06-12 14:19:10 -0700184 private static final String ATTR_BLOCKED = "blocked";
Amith Yamasanie5bcff62014-07-19 15:44:09 -0700185 // New name for the above attribute.
186 private static final String ATTR_HIDDEN = "hidden";
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700187 private static final String ATTR_INSTALLED = "inst";
Kenny Guyc13053b2014-05-29 14:17:17 +0100188 private static final String ATTR_BLOCK_UNINSTALL = "blockUninstall";
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -0800189 private static final String ATTR_DOMAIN_VERIFICATON_STATE = "domainVerificationStatus";
Fabrice Di Meglio62271722015-04-10 17:24:02 -0700190 private static final String ATTR_PACKAGE_NAME= "packageName";
Amith Yamasani483f3b02012-03-13 16:08:00 -0700191
Svetoslavc6d1c342015-02-26 14:44:43 -0800192 private final Object mLock;
Svetoslavc6d1c342015-02-26 14:44:43 -0800193
194 private final RuntimePermissionPersistence mRuntimePermissionsPersistence;
195
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700196 private final File mSettingsFilename;
197 private final File mBackupSettingsFilename;
198 private final File mPackageListFilename;
199 private final File mStoppedPackagesFilename;
200 private final File mBackupStoppedPackagesFilename;
Jeff Sharkey184a0102013-07-10 16:19:52 -0700201
Jeff Sharkey9f837a92014-10-24 12:07:24 -0700202 final ArrayMap<String, PackageSetting> mPackages =
203 new ArrayMap<String, PackageSetting>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700204 // List of replaced system applications
Jeff Sharkey9f837a92014-10-24 12:07:24 -0700205 private final ArrayMap<String, PackageSetting> mDisabledSysPackages =
206 new ArrayMap<String, PackageSetting>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700207
Geremy Condra12c18382013-03-06 16:49:06 -0800208 private static int mFirstAvailableUid = 0;
209
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700210 // These are the last platform API version we were using for
211 // the apps installed on internal and external storage. It is
212 // used to grant newer permissions one time during a system upgrade.
213 int mInternalSdkPlatform;
214 int mExternalSdkPlatform;
Kenny Root0aaa0d92011-09-12 16:42:55 -0700215
Kenny Rootc1c0d3c2014-04-24 13:36:40 -0700216 /**
217 * The current database version for apps on internal storage. This is
218 * used to upgrade the format of the packages.xml database not necessarily
219 * tied to an SDK version.
220 */
221 int mInternalDatabaseVersion;
222 int mExternalDatabaseVersion;
223
Jeff Sharkey4ed745d2014-07-15 20:39:15 -0700224 /**
225 * Last known value of {@link Build#FINGERPRINT}. Used to determine when an
226 * system update has occurred, meaning we need to clear code caches.
227 */
228 String mFingerprint;
229
Jeff Sharkeyf5385772012-05-11 14:04:41 -0700230 Boolean mReadExternalStorageEnforced;
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -0700231
Kenny Root0aaa0d92011-09-12 16:42:55 -0700232 /** Device identity for the purpose of package verification. */
233 private VerifierDeviceIdentity mVerifierDeviceIdentity;
234
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700235 // The user's preferred activities associated with particular intent
236 // filters.
Dianne Hackborn63092712012-10-07 14:45:35 -0700237 final SparseArray<PreferredIntentResolver> mPreferredActivities =
238 new SparseArray<PreferredIntentResolver>();
239
Sander Alewijnsef475ca32014-02-17 15:13:58 +0000240 // The persistent preferred activities of the user's profile/device owner
241 // associated with particular intent filters.
242 final SparseArray<PersistentPreferredIntentResolver> mPersistentPreferredActivities =
243 new SparseArray<PersistentPreferredIntentResolver>();
244
Nicolas Prevot10fa67c2014-03-24 13:44:38 +0000245 // For every user, it is used to find to which other users the intent can be forwarded.
Nicolas Prevot81948992014-05-16 18:25:26 +0100246 final SparseArray<CrossProfileIntentResolver> mCrossProfileIntentResolvers =
247 new SparseArray<CrossProfileIntentResolver>();
Nicolas Prevot10fa67c2014-03-24 13:44:38 +0000248
Jeff Sharkey9f837a92014-10-24 12:07:24 -0700249 final ArrayMap<String, SharedUserSetting> mSharedUsers =
250 new ArrayMap<String, SharedUserSetting>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700251 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
252 private final SparseArray<Object> mOtherUserIds =
253 new SparseArray<Object>();
254
255 // For reading/writing settings file.
256 private final ArrayList<Signature> mPastSignatures =
257 new ArrayList<Signature>();
dcashman8c04fac2015-03-23 11:39:42 -0700258 private final ArrayMap<Long, Integer> mKeySetRefs =
259 new ArrayMap<Long, Integer>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700260
261 // Mapping from permission names to info about them.
Jeff Sharkey9f837a92014-10-24 12:07:24 -0700262 final ArrayMap<String, BasePermission> mPermissions =
263 new ArrayMap<String, BasePermission>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700264
265 // Mapping from permission tree names to info about them.
Jeff Sharkey9f837a92014-10-24 12:07:24 -0700266 final ArrayMap<String, BasePermission> mPermissionTrees =
267 new ArrayMap<String, BasePermission>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700268
269 // Packages that have been uninstalled and still need their external
270 // storage data deleted.
Jeff Sharkey752cd922012-09-23 16:25:12 -0700271 final ArrayList<PackageCleanItem> mPackagesToBeCleaned = new ArrayList<PackageCleanItem>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700272
273 // Packages that have been renamed since they were first installed.
274 // Keys are the new names of the packages, values are the original
275 // names. The packages appear everwhere else under their original
276 // names.
Jeff Sharkey9f837a92014-10-24 12:07:24 -0700277 final ArrayMap<String, String> mRenamedPackages = new ArrayMap<String, String>();
Fabrice Di Meglio62271722015-04-10 17:24:02 -0700278
279 // For every user, it is used to find the package name of the default Browser App.
280 final SparseArray<String> mDefaultBrowserApp = new SparseArray<String>();
281
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700282 final StringBuilder mReadMessages = new StringBuilder();
283
Kenny Root447106f2011-03-23 11:00:15 -0700284 /**
285 * Used to track packages that have a shared user ID that hasn't been read
286 * in yet.
287 * <p>
288 * TODO: make this just a local variable that is passed in during package
289 * scanning to make it less confusing.
290 */
291 private final ArrayList<PendingPackage> mPendingPackages = new ArrayList<PendingPackage>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700292
Amith Yamasani483f3b02012-03-13 16:08:00 -0700293 private final File mSystemDir;
Geremy Condraf1bcca82013-01-07 22:35:24 -0800294
dcashman55b10782014-04-09 14:20:38 -0700295 public final KeySetManagerService mKeySetManagerService = new KeySetManagerService(mPackages);
Geremy Condraf1bcca82013-01-07 22:35:24 -0800296
Svet Ganov12a692a2015-03-28 19:34:15 -0700297 Settings(Object lock) {
298 this(Environment.getDataDirectory(), lock);
Amith Yamasani483f3b02012-03-13 16:08:00 -0700299 }
300
Svet Ganov12a692a2015-03-28 19:34:15 -0700301 Settings(File dataDir, Object lock) {
Svetoslavc6d1c342015-02-26 14:44:43 -0800302 mLock = lock;
303
304 mRuntimePermissionsPersistence = new RuntimePermissionPersistence(mLock);
305
Amith Yamasani483f3b02012-03-13 16:08:00 -0700306 mSystemDir = new File(dataDir, "system");
307 mSystemDir.mkdirs();
308 FileUtils.setPermissions(mSystemDir.toString(),
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700309 FileUtils.S_IRWXU|FileUtils.S_IRWXG
310 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
311 -1, -1);
Amith Yamasani483f3b02012-03-13 16:08:00 -0700312 mSettingsFilename = new File(mSystemDir, "packages.xml");
313 mBackupSettingsFilename = new File(mSystemDir, "packages-backup.xml");
314 mPackageListFilename = new File(mSystemDir, "packages.list");
Jeff Sharkeyaebb65c2014-11-24 15:00:13 -0800315 FileUtils.setPermissions(mPackageListFilename, 0640, SYSTEM_UID, PACKAGE_INFO_GID);
Jeff Sharkey184a0102013-07-10 16:19:52 -0700316
Amith Yamasani483f3b02012-03-13 16:08:00 -0700317 // Deprecated: Needed for migration
318 mStoppedPackagesFilename = new File(mSystemDir, "packages-stopped.xml");
319 mBackupStoppedPackagesFilename = new File(mSystemDir, "packages-stopped-backup.xml");
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700320 }
321
Kenny Root447106f2011-03-23 11:00:15 -0700322 PackageSetting getPackageLPw(PackageParser.Package pkg, PackageSetting origPackage,
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700323 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Narayan Kamath4903f642014-08-11 13:33:45 +0100324 String legacyNativeLibraryPathString, String primaryCpuAbi, String secondaryCpuAbi,
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800325 int pkgFlags, int pkgPrivateFlags, UserHandle user, boolean add) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700326 final String name = pkg.packageName;
Kenny Root447106f2011-03-23 11:00:15 -0700327 PackageSetting p = getPackageLPw(name, origPackage, realName, sharedUser, codePath,
Jeff Sharkey84f12942014-07-10 17:48:11 -0700328 resourcePath, legacyNativeLibraryPathString, primaryCpuAbi, secondaryCpuAbi,
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800329 pkg.mVersionCode, pkgFlags, pkgPrivateFlags, user, add, true /* allowInstall */);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700330 return p;
331 }
332
Kenny Root447106f2011-03-23 11:00:15 -0700333 PackageSetting peekPackageLPr(String name) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700334 return mPackages.get(name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700335 }
336
337 void setInstallStatus(String pkgName, int status) {
338 PackageSetting p = mPackages.get(pkgName);
339 if(p != null) {
340 if(p.getInstallStatus() != status) {
341 p.setInstallStatus(status);
342 }
343 }
344 }
345
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -0700346 void setInstallerPackageName(String pkgName, String installerPkgName) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700347 PackageSetting p = mPackages.get(pkgName);
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -0700348 if (p != null) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700349 p.setInstallerPackageName(installerPkgName);
350 }
351 }
352
Kenny Root447106f2011-03-23 11:00:15 -0700353 SharedUserSetting getSharedUserLPw(String name,
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800354 int pkgFlags, int pkgPrivateFlags, boolean create) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700355 SharedUserSetting s = mSharedUsers.get(name);
356 if (s == null) {
357 if (!create) {
358 return null;
359 }
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800360 s = new SharedUserSetting(name, pkgFlags, pkgPrivateFlags);
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800361 s.userId = newUserIdLPw(s);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700362 Log.i(PackageManagerService.TAG, "New shared user " + name + ": id=" + s.userId);
363 // < 0 means we couldn't assign a userid; fall out and return
364 // s, which is currently null
365 if (s.userId >= 0) {
366 mSharedUsers.put(name, s);
367 }
368 }
369
370 return s;
371 }
372
Narayan Kamathdf6d6dc2014-04-28 14:18:34 +0100373 Collection<SharedUserSetting> getAllSharedUsersLPw() {
374 return mSharedUsers.values();
375 }
376
377
Kenny Root447106f2011-03-23 11:00:15 -0700378 boolean disableSystemPackageLPw(String name) {
379 final PackageSetting p = mPackages.get(name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700380 if(p == null) {
381 Log.w(PackageManagerService.TAG, "Package:"+name+" is not an installed package");
382 return false;
383 }
Kenny Root447106f2011-03-23 11:00:15 -0700384 final PackageSetting dp = mDisabledSysPackages.get(name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700385 // always make sure the system package code and resource paths dont change
386 if (dp == null) {
387 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
388 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
389 }
390 mDisabledSysPackages.put(name, p);
391
392 // a little trick... when we install the new package, we don't
393 // want to modify the existing PackageSetting for the built-in
394 // version. so at this point we need a new PackageSetting that
395 // is okay to muck with.
396 PackageSetting newp = new PackageSetting(p);
Kenny Root447106f2011-03-23 11:00:15 -0700397 replacePackageLPw(name, newp);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700398 return true;
399 }
400 return false;
401 }
402
Kenny Root447106f2011-03-23 11:00:15 -0700403 PackageSetting enableSystemPackageLPw(String name) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700404 PackageSetting p = mDisabledSysPackages.get(name);
405 if(p == null) {
406 Log.w(PackageManagerService.TAG, "Package:"+name+" is not disabled");
407 return null;
408 }
409 // Reset flag in ApplicationInfo object
410 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
411 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
412 }
Kenny Root447106f2011-03-23 11:00:15 -0700413 PackageSetting ret = addPackageLPw(name, p.realName, p.codePath, p.resourcePath,
Narayan Kamathff110bd2014-07-04 18:30:45 +0100414 p.legacyNativeLibraryPathString, p.primaryCpuAbiString,
Narayan Kamath4903f642014-08-11 13:33:45 +0100415 p.secondaryCpuAbiString, p.secondaryCpuAbiString,
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800416 p.appId, p.versionCode, p.pkgFlags, p.pkgPrivateFlags);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700417 mDisabledSysPackages.remove(name);
418 return ret;
419 }
420
Kenny Rootc52d6fd2012-05-07 23:04:52 -0700421 boolean isDisabledSystemPackageLPr(String name) {
422 return mDisabledSysPackages.containsKey(name);
423 }
424
425 void removeDisabledSystemPackageLPw(String name) {
426 mDisabledSysPackages.remove(name);
427 }
428
Kenny Root447106f2011-03-23 11:00:15 -0700429 PackageSetting addPackageLPw(String name, String realName, File codePath, File resourcePath,
Narayan Kamathff110bd2014-07-04 18:30:45 +0100430 String legacyNativeLibraryPathString, String primaryCpuAbiString, String secondaryCpuAbiString,
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800431 String cpuAbiOverrideString, int uid, int vc, int pkgFlags, int pkgPrivateFlags) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700432 PackageSetting p = mPackages.get(name);
433 if (p != null) {
Amith Yamasani13593602012-03-22 16:16:17 -0700434 if (p.appId == uid) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700435 return p;
436 }
437 PackageManagerService.reportSettingsProblem(Log.ERROR,
438 "Adding duplicate package, keeping first: " + name);
439 return null;
440 }
Narayan Kamathff110bd2014-07-04 18:30:45 +0100441 p = new PackageSetting(name, realName, codePath, resourcePath,
Narayan Kamath4903f642014-08-11 13:33:45 +0100442 legacyNativeLibraryPathString, primaryCpuAbiString, secondaryCpuAbiString,
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800443 cpuAbiOverrideString, vc, pkgFlags, pkgPrivateFlags);
Amith Yamasani13593602012-03-22 16:16:17 -0700444 p.appId = uid;
Kenny Root447106f2011-03-23 11:00:15 -0700445 if (addUserIdLPw(uid, p, name)) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700446 mPackages.put(name, p);
447 return p;
448 }
449 return null;
450 }
451
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800452 SharedUserSetting addSharedUserLPw(String name, int uid, int pkgFlags, int pkgPrivateFlags) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700453 SharedUserSetting s = mSharedUsers.get(name);
454 if (s != null) {
455 if (s.userId == uid) {
456 return s;
457 }
458 PackageManagerService.reportSettingsProblem(Log.ERROR,
459 "Adding duplicate shared user, keeping first: " + name);
460 return null;
461 }
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800462 s = new SharedUserSetting(name, pkgFlags, pkgPrivateFlags);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700463 s.userId = uid;
Kenny Root447106f2011-03-23 11:00:15 -0700464 if (addUserIdLPw(uid, s, name)) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700465 mSharedUsers.put(name, s);
466 return s;
467 }
468 return null;
469 }
470
Christopher Tate86b391c2013-09-13 16:58:36 -0700471 void pruneSharedUsersLPw() {
472 ArrayList<String> removeStage = new ArrayList<String>();
473 for (Map.Entry<String,SharedUserSetting> entry : mSharedUsers.entrySet()) {
474 final SharedUserSetting sus = entry.getValue();
475 if (sus == null || sus.packages.size() == 0) {
476 removeStage.add(entry.getKey());
477 }
478 }
479 for (int i = 0; i < removeStage.size(); i++) {
480 mSharedUsers.remove(removeStage.get(i));
481 }
482 }
483
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700484 // Transfer ownership of permissions from one package to another.
Kenny Root447106f2011-03-23 11:00:15 -0700485 void transferPermissionsLPw(String origPkg, String newPkg) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700486 // Transfer ownership of permissions to the new package.
487 for (int i=0; i<2; i++) {
Jeff Sharkey9f837a92014-10-24 12:07:24 -0700488 ArrayMap<String, BasePermission> permissions =
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700489 i == 0 ? mPermissionTrees : mPermissions;
490 for (BasePermission bp : permissions.values()) {
491 if (origPkg.equals(bp.sourcePackage)) {
492 if (PackageManagerService.DEBUG_UPGRADE) Log.v(PackageManagerService.TAG,
493 "Moving permission " + bp.name
494 + " from pkg " + bp.sourcePackage
495 + " to " + newPkg);
496 bp.sourcePackage = newPkg;
497 bp.packageSetting = null;
498 bp.perm = null;
499 if (bp.pendingInfo != null) {
500 bp.pendingInfo.packageName = newPkg;
501 }
502 bp.uid = 0;
Jeff Sharkey00f39042015-03-23 16:51:22 -0700503 bp.setGids(null, false);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700504 }
505 }
506 }
507 }
Amith Yamasani483f3b02012-03-13 16:08:00 -0700508
Kenny Root447106f2011-03-23 11:00:15 -0700509 private PackageSetting getPackageLPw(String name, PackageSetting origPackage,
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700510 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Svetoslavc6d1c342015-02-26 14:44:43 -0800511 String legacyNativeLibraryPathString, String primaryCpuAbiString,
512 String secondaryCpuAbiString, int vc, int pkgFlags, int pkgPrivateFlags,
513 UserHandle installUser, boolean add, boolean allowInstall) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700514 PackageSetting p = mPackages.get(name);
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700515 UserManagerService userManager = UserManagerService.getInstance();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700516 if (p != null) {
Narayan Kamathff110bd2014-07-04 18:30:45 +0100517 p.primaryCpuAbiString = primaryCpuAbiString;
518 p.secondaryCpuAbiString = secondaryCpuAbiString;
Narayan Kamath4903f642014-08-11 13:33:45 +0100519
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700520 if (!p.codePath.equals(codePath)) {
521 // Check to see if its a disabled system app
522 if ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
523 // This is an updated system app with versions in both system
524 // and data partition. Just let the most recent version
525 // take precedence.
Amith Yamasani483f3b02012-03-13 16:08:00 -0700526 Slog.w(PackageManagerService.TAG, "Trying to update system app code path from "
527 + p.codePathString + " to " + codePath.toString());
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700528 } else {
529 // Just a change in the code path is not an issue, but
530 // let's log a message about it.
Amith Yamasani483f3b02012-03-13 16:08:00 -0700531 Slog.i(PackageManagerService.TAG, "Package " + name + " codePath changed from "
532 + p.codePath + " to " + codePath + "; Retaining data and using new");
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700533 /*
534 * Since we've changed paths, we need to prefer the new
535 * native library path over the one stored in the
536 * package settings since we might have moved from
537 * internal to external storage or vice versa.
538 */
Narayan Kamathff110bd2014-07-04 18:30:45 +0100539 p.legacyNativeLibraryPathString = legacyNativeLibraryPathString;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700540 }
541 }
542 if (p.sharedUser != sharedUser) {
543 PackageManagerService.reportSettingsProblem(Log.WARN,
544 "Package " + name + " shared user changed from "
545 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
546 + " to "
547 + (sharedUser != null ? sharedUser.name : "<nothing>")
548 + "; replacing with new");
549 p = null;
550 } else {
Christopher Tate9f088202013-10-22 15:36:01 -0700551 // If what we are scanning is a system (and possibly privileged) package,
552 // then make it so, regardless of whether it was previously installed only
553 // in the data partition.
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800554 p.pkgFlags |= pkgFlags & ApplicationInfo.FLAG_SYSTEM;
555 p.pkgPrivateFlags |= pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700556 }
557 }
558 if (p == null) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700559 if (origPackage != null) {
560 // We are consuming the data from an existing package.
561 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
Narayan Kamath4903f642014-08-11 13:33:45 +0100562 legacyNativeLibraryPathString, primaryCpuAbiString, secondaryCpuAbiString,
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800563 null /* cpuAbiOverrideString */, vc, pkgFlags, pkgPrivateFlags);
Amith Yamasani483f3b02012-03-13 16:08:00 -0700564 if (PackageManagerService.DEBUG_UPGRADE) Log.v(PackageManagerService.TAG, "Package "
565 + name + " is adopting original package " + origPackage.name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700566 // Note that we will retain the new package's signature so
567 // that we can keep its data.
568 PackageSignatures s = p.signatures;
569 p.copyFrom(origPackage);
570 p.signatures = s;
571 p.sharedUser = origPackage.sharedUser;
Amith Yamasani13593602012-03-22 16:16:17 -0700572 p.appId = origPackage.appId;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700573 p.origPackage = origPackage;
574 mRenamedPackages.put(name, origPackage.name);
575 name = origPackage.name;
576 // Update new package state.
577 p.setTimeStamp(codePath.lastModified());
578 } else {
579 p = new PackageSetting(name, realName, codePath, resourcePath,
Narayan Kamath4903f642014-08-11 13:33:45 +0100580 legacyNativeLibraryPathString, primaryCpuAbiString, secondaryCpuAbiString,
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800581 null /* cpuAbiOverrideString */, vc, pkgFlags, pkgPrivateFlags);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700582 p.setTimeStamp(codePath.lastModified());
583 p.sharedUser = sharedUser;
584 // If this is not a system app, it starts out stopped.
585 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Kenny Root447106f2011-03-23 11:00:15 -0700586 if (DEBUG_STOPPED) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700587 RuntimeException e = new RuntimeException("here");
588 e.fillInStackTrace();
589 Slog.i(PackageManagerService.TAG, "Stopping package " + name, e);
590 }
Amith Yamasani483f3b02012-03-13 16:08:00 -0700591 List<UserInfo> users = getAllUsers();
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700592 final int installUserId = installUser != null ? installUser.getIdentifier() : 0;
Amith Yamasanif031f232012-10-26 15:35:21 -0700593 if (users != null && allowInstall) {
Amith Yamasani483f3b02012-03-13 16:08:00 -0700594 for (UserInfo user : users) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700595 // By default we consider this app to be installed
596 // for the user if no user has been specified (which
597 // means to leave it at its original value, and the
598 // original default value is true), or we are being
599 // asked to install for all users, or this is the
600 // user we are installing for.
601 final boolean installed = installUser == null
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700602 || (installUserId == UserHandle.USER_ALL
603 && !isAdbInstallDisallowed(userManager, user.id))
604 || installUserId == user.id;
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700605 p.setUserState(user.id, COMPONENT_ENABLED_STATE_DEFAULT,
606 installed,
607 true, // stopped,
608 true, // notLaunched
Amith Yamasanie5bcff62014-07-19 15:44:09 -0700609 false, // hidden
Kenny Guyc13053b2014-05-29 14:17:17 +0100610 null, null, null,
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -0800611 false, // blockUninstall
612 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
Amith Yamasani483f3b02012-03-13 16:08:00 -0700613 writePackageRestrictionsLPr(user.id);
614 }
615 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700616 }
617 if (sharedUser != null) {
Amith Yamasani13593602012-03-22 16:16:17 -0700618 p.appId = sharedUser.userId;
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800619 } else {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700620 // Clone the setting here for disabled system packages
621 PackageSetting dis = mDisabledSysPackages.get(name);
622 if (dis != null) {
623 // For disabled packages a new setting is created
624 // from the existing user id. This still has to be
625 // added to list of user id's
626 // Copy signatures from previous setting
627 if (dis.signatures.mSignatures != null) {
628 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
629 }
Amith Yamasani13593602012-03-22 16:16:17 -0700630 p.appId = dis.appId;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700631 // Clone permissions
Svetoslavc6d1c342015-02-26 14:44:43 -0800632 p.getPermissionsState().copyFrom(dis.getPermissionsState());
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700633 // Clone component info
Amith Yamasani483f3b02012-03-13 16:08:00 -0700634 List<UserInfo> users = getAllUsers();
635 if (users != null) {
636 for (UserInfo user : users) {
637 int userId = user.id;
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700638 p.setDisabledComponentsCopy(
639 dis.getDisabledComponents(userId), userId);
640 p.setEnabledComponentsCopy(
641 dis.getEnabledComponents(userId), userId);
Amith Yamasani483f3b02012-03-13 16:08:00 -0700642 }
643 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700644 // Add new setting to list of user ids
Amith Yamasani13593602012-03-22 16:16:17 -0700645 addUserIdLPw(p.appId, p, name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700646 } else {
647 // Assign new user id
Amith Yamasani13593602012-03-22 16:16:17 -0700648 p.appId = newUserIdLPw(p);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700649 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700650 }
651 }
Amith Yamasani13593602012-03-22 16:16:17 -0700652 if (p.appId < 0) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700653 PackageManagerService.reportSettingsProblem(Log.WARN,
654 "Package " + name + " could not be assigned a valid uid");
655 return null;
656 }
657 if (add) {
658 // Finish adding new package by adding it and updating shared
659 // user preferences
Kenny Root447106f2011-03-23 11:00:15 -0700660 addPackageSettingLPw(p, name, sharedUser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700661 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700662 } else {
Amith Yamasanif031f232012-10-26 15:35:21 -0700663 if (installUser != null && allowInstall) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700664 // The caller has explicitly specified the user they want this
665 // package installed for, and the package already exists.
666 // Make sure it conforms to the new request.
667 List<UserInfo> users = getAllUsers();
668 if (users != null) {
669 for (UserInfo user : users) {
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700670 if ((installUser.getIdentifier() == UserHandle.USER_ALL
671 && !isAdbInstallDisallowed(userManager, user.id))
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700672 || installUser.getIdentifier() == user.id) {
673 boolean installed = p.getInstalled(user.id);
674 if (!installed) {
675 p.setInstalled(true, user.id);
676 writePackageRestrictionsLPr(user.id);
677 }
678 }
679 }
680 }
681 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700682 }
683 return p;
684 }
685
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700686 boolean isAdbInstallDisallowed(UserManagerService userManager, int userId) {
687 return userManager.hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES,
688 userId);
689 }
690
Kenny Root447106f2011-03-23 11:00:15 -0700691 void insertPackageSettingLPw(PackageSetting p, PackageParser.Package pkg) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700692 p.pkg = pkg;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700693 // pkg.mSetEnabled = p.getEnabled(userId);
694 // pkg.mSetStopped = p.getStopped(userId);
Jeff Sharkeyb9f36742015-04-08 21:02:14 -0700695 final String volumeUuid = pkg.applicationInfo.volumeUuid;
Jeff Sharkeyd7460572014-07-06 20:44:55 -0700696 final String codePath = pkg.applicationInfo.getCodePath();
697 final String resourcePath = pkg.applicationInfo.getResourcePath();
Jeff Sharkey84f12942014-07-10 17:48:11 -0700698 final String legacyNativeLibraryPath = pkg.applicationInfo.nativeLibraryRootDir;
Jeff Sharkeyb9f36742015-04-08 21:02:14 -0700699 // Update volume if needed
700 if (!Objects.equals(volumeUuid, p.volumeUuid)) {
701 Slog.w(PackageManagerService.TAG, "Volume for " + p.pkg.packageName +
702 " changing from " + p.volumeUuid + " to " + volumeUuid);
703 p.volumeUuid = volumeUuid;
704 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700705 // Update code path if needed
Jeff Sharkey84f12942014-07-10 17:48:11 -0700706 if (!Objects.equals(codePath, p.codePathString)) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -0700707 Slog.w(PackageManagerService.TAG, "Code path for " + p.pkg.packageName +
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700708 " changing from " + p.codePathString + " to " + codePath);
709 p.codePath = new File(codePath);
710 p.codePathString = codePath;
711 }
712 //Update resource path if needed
Jeff Sharkey84f12942014-07-10 17:48:11 -0700713 if (!Objects.equals(resourcePath, p.resourcePathString)) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -0700714 Slog.w(PackageManagerService.TAG, "Resource path for " + p.pkg.packageName +
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700715 " changing from " + p.resourcePathString + " to " + resourcePath);
716 p.resourcePath = new File(resourcePath);
717 p.resourcePathString = resourcePath;
718 }
Narayan Kamathff110bd2014-07-04 18:30:45 +0100719 // Update the native library paths if needed
Jeff Sharkey84f12942014-07-10 17:48:11 -0700720 if (!Objects.equals(legacyNativeLibraryPath, p.legacyNativeLibraryPathString)) {
721 p.legacyNativeLibraryPathString = legacyNativeLibraryPath;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700722 }
Narayan Kamathff110bd2014-07-04 18:30:45 +0100723
Narayan Kamath9e289d72014-04-10 09:26:59 +0000724 // Update the required Cpu Abi
Narayan Kamathff110bd2014-07-04 18:30:45 +0100725 p.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
726 p.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
Narayan Kamath4903f642014-08-11 13:33:45 +0100727 p.cpuAbiOverrideString = pkg.cpuAbiOverride;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700728 // Update version code if needed
Amith Yamasani483f3b02012-03-13 16:08:00 -0700729 if (pkg.mVersionCode != p.versionCode) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700730 p.versionCode = pkg.mVersionCode;
731 }
Amith Yamasani483f3b02012-03-13 16:08:00 -0700732 // Update signatures if needed.
733 if (p.signatures.mSignatures == null) {
734 p.signatures.assignSignatures(pkg.mSignatures);
735 }
Kenny Root5455f682012-09-09 14:52:10 -0700736 // Update flags if needed.
737 if (pkg.applicationInfo.flags != p.pkgFlags) {
738 p.pkgFlags = pkg.applicationInfo.flags;
739 }
Amith Yamasani483f3b02012-03-13 16:08:00 -0700740 // If this app defines a shared user id initialize
741 // the shared user signatures as well.
742 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
743 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
744 }
Kenny Root447106f2011-03-23 11:00:15 -0700745 addPackageSettingLPw(p, pkg.packageName, p.sharedUser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700746 }
747
748 // Utility method that adds a PackageSetting to mPackages and
749 // completes updating the shared user attributes
Kenny Root447106f2011-03-23 11:00:15 -0700750 private void addPackageSettingLPw(PackageSetting p, String name,
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700751 SharedUserSetting sharedUser) {
752 mPackages.put(name, p);
753 if (sharedUser != null) {
754 if (p.sharedUser != null && p.sharedUser != sharedUser) {
755 PackageManagerService.reportSettingsProblem(Log.ERROR,
756 "Package " + p.name + " was user "
757 + p.sharedUser + " but is now " + sharedUser
758 + "; I am not changing its files so it will probably fail!");
Ben Gruverdd72c9e2013-08-06 12:34:17 -0700759 p.sharedUser.removePackage(p);
Amith Yamasani13593602012-03-22 16:16:17 -0700760 } else if (p.appId != sharedUser.userId) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700761 PackageManagerService.reportSettingsProblem(Log.ERROR,
Amith Yamasani13593602012-03-22 16:16:17 -0700762 "Package " + p.name + " was user id " + p.appId
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700763 + " but is now user " + sharedUser
764 + " with id " + sharedUser.userId
765 + "; I am not changing its files so it will probably fail!");
766 }
767
Ben Gruverdd72c9e2013-08-06 12:34:17 -0700768 sharedUser.addPackage(p);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700769 p.sharedUser = sharedUser;
Amith Yamasani13593602012-03-22 16:16:17 -0700770 p.appId = sharedUser.userId;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700771 }
772 }
773
774 /*
775 * Update the shared user setting when a package using
776 * specifying the shared user id is removed. The gids
777 * associated with each permission of the deleted package
778 * are removed from the shared user's gid list only if its
779 * not in use by other permissions of packages in the
780 * shared user setting.
781 */
Svetoslavc6d1c342015-02-26 14:44:43 -0800782 int updateSharedUserPermsLPw(PackageSetting deletedPs, int userId) {
Kenny Root447106f2011-03-23 11:00:15 -0700783 if ((deletedPs == null) || (deletedPs.pkg == null)) {
784 Slog.i(PackageManagerService.TAG,
785 "Trying to update info for null package. Just ignoring");
Svetoslavc6d1c342015-02-26 14:44:43 -0800786 return UserHandle.USER_NULL;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700787 }
Svetoslavc6d1c342015-02-26 14:44:43 -0800788
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700789 // No sharedUserId
790 if (deletedPs.sharedUser == null) {
Svetoslavc6d1c342015-02-26 14:44:43 -0800791 return UserHandle.USER_NULL;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700792 }
Svetoslavc6d1c342015-02-26 14:44:43 -0800793
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700794 SharedUserSetting sus = deletedPs.sharedUser;
Svetoslavc6d1c342015-02-26 14:44:43 -0800795
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700796 // Update permissions
Kenny Root447106f2011-03-23 11:00:15 -0700797 for (String eachPerm : deletedPs.pkg.requestedPermissions) {
Svetoslavc6d1c342015-02-26 14:44:43 -0800798 BasePermission bp = mPermissions.get(eachPerm);
799 if (bp == null) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700800 continue;
801 }
Svetoslavc6d1c342015-02-26 14:44:43 -0800802
803 // If no user has the permission, nothing to remove.
804 if (!sus.getPermissionsState().hasPermission(bp.name, userId)) {
805 continue;
806 }
807
808 boolean used = false;
809
810 // Check if another package in the shared user needs the permission.
811 for (PackageSetting pkg : sus.packages) {
812 if (pkg.pkg != null
813 && !pkg.pkg.packageName.equals(deletedPs.pkg.packageName)
814 && pkg.pkg.requestedPermissions.contains(eachPerm)) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700815 used = true;
816 break;
817 }
818 }
Svetoslavc6d1c342015-02-26 14:44:43 -0800819
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700820 if (!used) {
Svetoslavc6d1c342015-02-26 14:44:43 -0800821 // Try to revoke as an install permission which is for all users.
822 if (sus.getPermissionsState().revokeInstallPermission(bp) ==
823 PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED) {
824 return UserHandle.USER_ALL;
825 }
826
827 // Try to revoke as an install permission which is per user.
828 if (sus.getPermissionsState().revokeRuntimePermission(bp, userId) ==
829 PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED) {
830 return userId;
831 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700832 }
833 }
Svetoslavc6d1c342015-02-26 14:44:43 -0800834
835 return UserHandle.USER_NULL;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700836 }
837
Kenny Root447106f2011-03-23 11:00:15 -0700838 int removePackageLPw(String name) {
839 final PackageSetting p = mPackages.get(name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700840 if (p != null) {
841 mPackages.remove(name);
842 if (p.sharedUser != null) {
Ben Gruverdd72c9e2013-08-06 12:34:17 -0700843 p.sharedUser.removePackage(p);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700844 if (p.sharedUser.packages.size() == 0) {
845 mSharedUsers.remove(p.sharedUser.name);
Kenny Root447106f2011-03-23 11:00:15 -0700846 removeUserIdLPw(p.sharedUser.userId);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700847 return p.sharedUser.userId;
848 }
849 } else {
Amith Yamasani13593602012-03-22 16:16:17 -0700850 removeUserIdLPw(p.appId);
851 return p.appId;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700852 }
853 }
854 return -1;
855 }
856
Kenny Root447106f2011-03-23 11:00:15 -0700857 private void replacePackageLPw(String name, PackageSetting newp) {
858 final PackageSetting p = mPackages.get(name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700859 if (p != null) {
860 if (p.sharedUser != null) {
Ben Gruverdd72c9e2013-08-06 12:34:17 -0700861 p.sharedUser.removePackage(p);
862 p.sharedUser.addPackage(newp);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700863 } else {
Amith Yamasani13593602012-03-22 16:16:17 -0700864 replaceUserIdLPw(p.appId, newp);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700865 }
866 }
867 mPackages.put(name, newp);
868 }
869
Kenny Root447106f2011-03-23 11:00:15 -0700870 private boolean addUserIdLPw(int uid, Object obj, Object name) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800871 if (uid > Process.LAST_APPLICATION_UID) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700872 return false;
873 }
874
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800875 if (uid >= Process.FIRST_APPLICATION_UID) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700876 int N = mUserIds.size();
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800877 final int index = uid - Process.FIRST_APPLICATION_UID;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700878 while (index >= N) {
879 mUserIds.add(null);
880 N++;
881 }
882 if (mUserIds.get(index) != null) {
883 PackageManagerService.reportSettingsProblem(Log.ERROR,
884 "Adding duplicate user id: " + uid
885 + " name=" + name);
886 return false;
887 }
888 mUserIds.set(index, obj);
889 } else {
890 if (mOtherUserIds.get(uid) != null) {
891 PackageManagerService.reportSettingsProblem(Log.ERROR,
892 "Adding duplicate shared id: " + uid
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -0800893 + " name=" + name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700894 return false;
895 }
896 mOtherUserIds.put(uid, obj);
897 }
898 return true;
899 }
900
Kenny Root447106f2011-03-23 11:00:15 -0700901 public Object getUserIdLPr(int uid) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800902 if (uid >= Process.FIRST_APPLICATION_UID) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700903 final int N = mUserIds.size();
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800904 final int index = uid - Process.FIRST_APPLICATION_UID;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700905 return index < N ? mUserIds.get(index) : null;
906 } else {
907 return mOtherUserIds.get(uid);
908 }
909 }
910
Kenny Root447106f2011-03-23 11:00:15 -0700911 private void removeUserIdLPw(int uid) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800912 if (uid >= Process.FIRST_APPLICATION_UID) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700913 final int N = mUserIds.size();
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800914 final int index = uid - Process.FIRST_APPLICATION_UID;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700915 if (index < N) mUserIds.set(index, null);
916 } else {
917 mOtherUserIds.remove(uid);
918 }
Geremy Condra12c18382013-03-06 16:49:06 -0800919 setFirstAvailableUid(uid+1);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700920 }
921
Kenny Root447106f2011-03-23 11:00:15 -0700922 private void replaceUserIdLPw(int uid, Object obj) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800923 if (uid >= Process.FIRST_APPLICATION_UID) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700924 final int N = mUserIds.size();
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800925 final int index = uid - Process.FIRST_APPLICATION_UID;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700926 if (index < N) mUserIds.set(index, obj);
927 } else {
928 mOtherUserIds.put(uid, obj);
929 }
930 }
931
Dianne Hackborn63092712012-10-07 14:45:35 -0700932 PreferredIntentResolver editPreferredActivitiesLPw(int userId) {
933 PreferredIntentResolver pir = mPreferredActivities.get(userId);
934 if (pir == null) {
935 pir = new PreferredIntentResolver();
936 mPreferredActivities.put(userId, pir);
937 }
938 return pir;
939 }
940
Sander Alewijnsef475ca32014-02-17 15:13:58 +0000941 PersistentPreferredIntentResolver editPersistentPreferredActivitiesLPw(int userId) {
942 PersistentPreferredIntentResolver ppir = mPersistentPreferredActivities.get(userId);
943 if (ppir == null) {
944 ppir = new PersistentPreferredIntentResolver();
945 mPersistentPreferredActivities.put(userId, ppir);
946 }
947 return ppir;
948 }
949
Nicolas Prevot81948992014-05-16 18:25:26 +0100950 CrossProfileIntentResolver editCrossProfileIntentResolverLPw(int userId) {
951 CrossProfileIntentResolver cpir = mCrossProfileIntentResolvers.get(userId);
952 if (cpir == null) {
953 cpir = new CrossProfileIntentResolver();
954 mCrossProfileIntentResolvers.put(userId, cpir);
Nicolas Prevot10fa67c2014-03-24 13:44:38 +0000955 }
Nicolas Prevot81948992014-05-16 18:25:26 +0100956 return cpir;
Nicolas Prevot10fa67c2014-03-24 13:44:38 +0000957 }
958
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -0800959 /**
960 * The following functions suppose that you have a lock for managing access to the
961 * mIntentFiltersVerifications map.
962 */
963
964 /* package protected */
965 IntentFilterVerificationInfo getIntentFilterVerificationLPr(String packageName) {
966 PackageSetting ps = mPackages.get(packageName);
967 if (ps == null) {
968 Slog.w(PackageManagerService.TAG, "No package known for name: " + packageName);
969 return null;
970 }
971 return ps.getIntentFilterVerificationInfo();
972 }
973
974 /* package protected */
Fabrice Di Meglio7d014ce2015-04-08 16:17:46 -0700975 IntentFilterVerificationInfo createIntentFilterVerificationIfNeededLPw(String packageName,
Fabrice Di Meglio07885952015-04-06 19:41:28 -0700976 ArrayList<String> domains) {
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -0800977 PackageSetting ps = mPackages.get(packageName);
978 if (ps == null) {
979 Slog.w(PackageManagerService.TAG, "No package known for name: " + packageName);
Fabrice Di Meglio7d014ce2015-04-08 16:17:46 -0700980 return null;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -0800981 }
Fabrice Di Meglio7d014ce2015-04-08 16:17:46 -0700982 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
983 if (ivi == null) {
984 ivi = new IntentFilterVerificationInfo(packageName, domains);
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -0800985 ps.setIntentFilterVerificationInfo(ivi);
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -0800986 }
Fabrice Di Meglio7d014ce2015-04-08 16:17:46 -0700987 return ivi;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -0800988 }
989
990 int getIntentFilterVerificationStatusLPr(String packageName, int userId) {
991 PackageSetting ps = mPackages.get(packageName);
992 if (ps == null) {
993 Slog.w(PackageManagerService.TAG, "No package known for name: " + packageName);
994 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
995 }
996 int status = ps.getDomainVerificationStatusForUser(userId);
997 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
998 if (ps.getIntentFilterVerificationInfo() != null) {
999 status = ps.getIntentFilterVerificationInfo().getStatus();
1000 }
1001 }
1002 return status;
1003 }
1004
1005 boolean updateIntentFilterVerificationStatusLPw(String packageName, int status, int userId) {
Fabrice Di Meglio07885952015-04-06 19:41:28 -07001006 // Update the status for the current package
1007 PackageSetting current = mPackages.get(packageName);
1008 if (current == null) {
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001009 Slog.w(PackageManagerService.TAG, "No package known for name: " + packageName);
1010 return false;
1011 }
Fabrice Di Meglio07885952015-04-06 19:41:28 -07001012 current.setDomainVerificationStatusForUser(status, userId);
1013
1014 if (current.getIntentFilterVerificationInfo() == null) {
1015 Slog.w(PackageManagerService.TAG,
1016 "No IntentFilterVerificationInfo known for name: " + packageName);
1017 return false;
1018 }
1019
1020 // Then, if we set a ALWAYS status, then put NEVER status for Apps whose IntentFilter
1021 // domains overlap the domains of the current package
1022 ArraySet<String> currentDomains = current.getIntentFilterVerificationInfo().getDomainsSet();
1023 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
1024 for (PackageSetting ps : mPackages.values()) {
1025 if (ps == null || ps.pkg.packageName.equals(packageName)) continue;
1026 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
1027 if (ivi == null) {
1028 continue;
1029 }
1030 ArraySet<String> set = ivi.getDomainsSet();
1031 set.retainAll(currentDomains);
1032 if (set.size() > 0) {
1033 ps.setDomainVerificationStatusForUser(
1034 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, userId);
1035 }
1036 }
1037 }
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001038 return true;
1039 }
1040
1041 /**
Fabrice Di Meglio07885952015-04-06 19:41:28 -07001042 * Used for Settings App and PackageManagerService dump. Should be read only.
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001043 */
1044 List<IntentFilterVerificationInfo> getIntentFilterVerificationsLPr(
1045 String packageName) {
1046 if (packageName == null) {
1047 return Collections.<IntentFilterVerificationInfo>emptyList();
1048 }
1049 ArrayList<IntentFilterVerificationInfo> result = new ArrayList<>();
1050 for (PackageSetting ps : mPackages.values()) {
1051 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
1052 if (ivi == null || TextUtils.isEmpty(ivi.getPackageName()) ||
1053 !ivi.getPackageName().equalsIgnoreCase(packageName)) {
1054 continue;
1055 }
1056 result.add(ivi);
1057 }
1058 return result;
1059 }
1060
1061 void removeIntentFilterVerificationLPw(String packageName, int userId) {
1062 PackageSetting ps = mPackages.get(packageName);
1063 if (ps == null) {
1064 Slog.w(PackageManagerService.TAG, "No package known for name: " + packageName);
1065 return;
1066 }
1067 ps.clearDomainVerificationStatusForUser(userId);
1068 }
1069
1070 void removeIntentFilterVerificationLPw(String packageName, int[] userIds) {
1071 for (int userId : userIds) {
1072 removeIntentFilterVerificationLPw(packageName, userId);
1073 }
1074 }
1075
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001076 boolean setDefaultBrowserPackageNameLPr(String packageName, int userId) {
1077 if (userId == UserHandle.USER_ALL) {
1078 return false;
1079 }
1080 mDefaultBrowserApp.put(userId, packageName);
1081 writePackageRestrictionsLPr(userId);
1082 return true;
1083 }
1084
1085 String getDefaultBrowserPackageNameLPw(int userId) {
1086 return (userId == UserHandle.USER_ALL) ? null : mDefaultBrowserApp.get(userId);
1087 }
1088
Amith Yamasani483f3b02012-03-13 16:08:00 -07001089 private File getUserPackagesStateFile(int userId) {
Svetoslavc6d1c342015-02-26 14:44:43 -08001090 // TODO: Implement a cleaner solution when adding tests.
1091 // This instead of Environment.getUserSystemDirectory(userId) to support testing.
1092 File userDir = new File(new File(mSystemDir, "users"), Integer.toString(userId));
1093 return new File(userDir, "package-restrictions.xml");
1094 }
1095
1096 private File getUserRuntimePermissionsFile(int userId) {
1097 // TODO: Implement a cleaner solution when adding tests.
1098 // This instead of Environment.getUserSystemDirectory(userId) to support testing.
1099 File userDir = new File(new File(mSystemDir, "users"), Integer.toString(userId));
1100 return new File(userDir, RUNTIME_PERMISSIONS_FILE_NAME);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001101 }
1102
Svet Ganov12a692a2015-03-28 19:34:15 -07001103 boolean isFirstRuntimePermissionsBoot() {
1104 return !getUserRuntimePermissionsFile(UserHandle.USER_OWNER).exists();
1105 }
1106
1107 void deleteRuntimePermissionsFiles() {
1108 for (int userId : UserManagerService.getInstance().getUserIds()) {
1109 File file = getUserRuntimePermissionsFile(userId);
1110 file.delete();
1111 }
1112 }
1113
Amith Yamasani483f3b02012-03-13 16:08:00 -07001114 private File getUserPackagesStateBackupFile(int userId) {
Amith Yamasani61f57372012-08-31 12:12:28 -07001115 return new File(Environment.getUserSystemDirectory(userId),
1116 "package-restrictions-backup.xml");
Amith Yamasani483f3b02012-03-13 16:08:00 -07001117 }
1118
1119 void writeAllUsersPackageRestrictionsLPr() {
1120 List<UserInfo> users = getAllUsers();
1121 if (users == null) return;
1122
1123 for (UserInfo user : users) {
1124 writePackageRestrictionsLPr(user.id);
1125 }
1126 }
1127
Svetoslavc6d1c342015-02-26 14:44:43 -08001128 void writeAllRuntimePermissionsLPr() {
1129 for (int userId : UserManagerService.getInstance().getUserIds()) {
1130 mRuntimePermissionsPersistence.writePermissionsForUserAsyncLPr(userId);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001131 }
1132 }
1133
Kenny Rootc1c0d3c2014-04-24 13:36:40 -07001134 /**
1135 * Returns whether the current database has is older than {@code version}
1136 * for apps on internal storage.
1137 */
1138 public boolean isInternalDatabaseVersionOlderThan(int version) {
1139 return mInternalDatabaseVersion < version;
1140 }
1141
1142 /**
1143 * Returns whether the current database has is older than {@code version}
1144 * for apps on external storage.
1145 */
1146 public boolean isExternalDatabaseVersionOlderThan(int version) {
1147 return mExternalDatabaseVersion < version;
1148 }
1149
1150 /**
1151 * Updates the database version for apps on internal storage. Called after
1152 * call the updates to the database format are done for apps on internal
1153 * storage after the initial start-up scan.
1154 */
1155 public void updateInternalDatabaseVersion() {
1156 mInternalDatabaseVersion = CURRENT_DATABASE_VERSION;
1157 }
1158
1159 /**
1160 * Updates the database version for apps on internal storage. Called after
1161 * call the updates to the database format are done for apps on internal
1162 * storage after the initial start-up scan.
1163 */
1164 public void updateExternalDatabaseVersion() {
1165 mExternalDatabaseVersion = CURRENT_DATABASE_VERSION;
1166 }
1167
Christopher Tatee012a232015-04-01 17:18:50 -07001168 /**
1169 * Applies the preferred activity state described by the given XML. This code
1170 * also supports the restore-from-backup code path.
1171 *
1172 * @see PreferredActivityBackupHelper
1173 */
1174 void readPreferredActivitiesLPw(XmlPullParser parser, int userId)
Dianne Hackborn63092712012-10-07 14:45:35 -07001175 throws XmlPullParserException, IOException {
1176 int outerDepth = parser.getDepth();
1177 int type;
1178 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1179 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1180 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1181 continue;
1182 }
1183
1184 String tagName = parser.getName();
1185 if (tagName.equals(TAG_ITEM)) {
1186 PreferredActivity pa = new PreferredActivity(parser);
1187 if (pa.mPref.getParseError() == null) {
1188 editPreferredActivitiesLPw(userId).addFilter(pa);
1189 } else {
1190 PackageManagerService.reportSettingsProblem(Log.WARN,
1191 "Error in package manager settings: <preferred-activity> "
1192 + pa.mPref.getParseError() + " at "
1193 + parser.getPositionDescription());
1194 }
1195 } else {
1196 PackageManagerService.reportSettingsProblem(Log.WARN,
1197 "Unknown element under <preferred-activities>: " + parser.getName());
1198 XmlUtils.skipCurrentTag(parser);
1199 }
1200 }
1201 }
1202
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001203 private void readPersistentPreferredActivitiesLPw(XmlPullParser parser, int userId)
1204 throws XmlPullParserException, IOException {
1205 int outerDepth = parser.getDepth();
1206 int type;
1207 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1208 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1209 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1210 continue;
1211 }
1212 String tagName = parser.getName();
1213 if (tagName.equals(TAG_ITEM)) {
1214 PersistentPreferredActivity ppa = new PersistentPreferredActivity(parser);
1215 editPersistentPreferredActivitiesLPw(userId).addFilter(ppa);
1216 } else {
1217 PackageManagerService.reportSettingsProblem(Log.WARN,
Sander Alewijnseaf597622014-03-20 18:44:57 +00001218 "Unknown element under <" + TAG_PERSISTENT_PREFERRED_ACTIVITIES + ">: "
1219 + parser.getName());
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001220 XmlUtils.skipCurrentTag(parser);
1221 }
1222 }
1223 }
1224
Nicolas Prevot81948992014-05-16 18:25:26 +01001225 private void readCrossProfileIntentFiltersLPw(XmlPullParser parser, int userId)
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001226 throws XmlPullParserException, IOException {
1227 int outerDepth = parser.getDepth();
1228 int type;
1229 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1230 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1231 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1232 continue;
1233 }
1234 String tagName = parser.getName();
1235 if (tagName.equals(TAG_ITEM)) {
Nicolas Prevot81948992014-05-16 18:25:26 +01001236 CrossProfileIntentFilter cpif = new CrossProfileIntentFilter(parser);
1237 editCrossProfileIntentResolverLPw(userId).addFilter(cpif);
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001238 } else {
Nicolas Prevot81948992014-05-16 18:25:26 +01001239 String msg = "Unknown element under " + TAG_CROSS_PROFILE_INTENT_FILTERS + ": " +
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001240 parser.getName();
1241 PackageManagerService.reportSettingsProblem(Log.WARN, msg);
1242 XmlUtils.skipCurrentTag(parser);
1243 }
1244 }
1245 }
1246
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001247 private void readDomainVerificationLPw(XmlPullParser parser, PackageSettingBase packageSetting)
1248 throws XmlPullParserException, IOException {
1249 IntentFilterVerificationInfo ivi = new IntentFilterVerificationInfo(parser);
1250 packageSetting.setIntentFilterVerificationInfo(ivi);
1251 Log.d(TAG, "Read domain verification for package:" + ivi.getPackageName());
1252 }
1253
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001254 private void readDefaultAppsLPw(XmlPullParser parser, int userId)
1255 throws XmlPullParserException, IOException {
1256 int outerDepth = parser.getDepth();
1257 int type;
1258 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1259 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1260 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1261 continue;
1262 }
1263 String tagName = parser.getName();
1264 if (tagName.equals(TAG_DEFAULT_BROWSER)) {
1265 String packageName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
1266 mDefaultBrowserApp.put(userId, packageName);
1267 } else {
1268 String msg = "Unknown element under " + TAG_DEFAULT_APPS + ": " +
1269 parser.getName();
1270 PackageManagerService.reportSettingsProblem(Log.WARN, msg);
1271 XmlUtils.skipCurrentTag(parser);
1272 }
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001273 }
1274 }
1275
Amith Yamasani483f3b02012-03-13 16:08:00 -07001276 void readPackageRestrictionsLPr(int userId) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001277 if (DEBUG_MU) {
1278 Log.i(TAG, "Reading package restrictions for user=" + userId);
1279 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07001280 FileInputStream str = null;
1281 File userPackagesStateFile = getUserPackagesStateFile(userId);
1282 File backupFile = getUserPackagesStateBackupFile(userId);
1283 if (backupFile.exists()) {
1284 try {
1285 str = new FileInputStream(backupFile);
1286 mReadMessages.append("Reading from backup stopped packages file\n");
1287 PackageManagerService.reportSettingsProblem(Log.INFO,
1288 "Need to read from backup stopped packages file");
1289 if (userPackagesStateFile.exists()) {
1290 // If both the backup and normal file exist, we
1291 // ignore the normal one since it might have been
1292 // corrupted.
1293 Slog.w(PackageManagerService.TAG, "Cleaning up stopped packages file "
1294 + userPackagesStateFile);
1295 userPackagesStateFile.delete();
1296 }
1297 } catch (java.io.IOException e) {
1298 // We'll try for the normal settings file.
1299 }
1300 }
1301
1302 try {
1303 if (str == null) {
1304 if (!userPackagesStateFile.exists()) {
1305 mReadMessages.append("No stopped packages file found\n");
1306 PackageManagerService.reportSettingsProblem(Log.INFO,
1307 "No stopped packages file; "
1308 + "assuming all started");
1309 // At first boot, make sure no packages are stopped.
1310 // We usually want to have third party apps initialize
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001311 // in the stopped state, but not at first boot. Also
1312 // consider all applications to be installed.
Amith Yamasani483f3b02012-03-13 16:08:00 -07001313 for (PackageSetting pkg : mPackages.values()) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001314 pkg.setUserState(userId, COMPONENT_ENABLED_STATE_DEFAULT,
1315 true, // installed
1316 false, // stopped
1317 false, // notLaunched
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001318 false, // hidden
Kenny Guyc13053b2014-05-29 14:17:17 +01001319 null, null, null,
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001320 false, // blockUninstall
1321 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001322 }
1323 return;
1324 }
1325 str = new FileInputStream(userPackagesStateFile);
1326 }
1327 final XmlPullParser parser = Xml.newPullParser();
1328 parser.setInput(str, null);
1329
1330 int type;
1331 while ((type=parser.next()) != XmlPullParser.START_TAG
1332 && type != XmlPullParser.END_DOCUMENT) {
1333 ;
1334 }
1335
1336 if (type != XmlPullParser.START_TAG) {
1337 mReadMessages.append("No start tag found in package restrictions file\n");
1338 PackageManagerService.reportSettingsProblem(Log.WARN,
1339 "No start tag found in package manager stopped packages");
1340 return;
1341 }
1342
1343 int outerDepth = parser.getDepth();
1344 PackageSetting ps = null;
1345 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1346 && (type != XmlPullParser.END_TAG
1347 || parser.getDepth() > outerDepth)) {
1348 if (type == XmlPullParser.END_TAG
1349 || type == XmlPullParser.TEXT) {
1350 continue;
1351 }
1352
1353 String tagName = parser.getName();
1354 if (tagName.equals(TAG_PACKAGE)) {
1355 String name = parser.getAttributeValue(null, ATTR_NAME);
1356 ps = mPackages.get(name);
1357 if (ps == null) {
1358 Slog.w(PackageManagerService.TAG, "No package known for stopped package: "
1359 + name);
1360 XmlUtils.skipCurrentTag(parser);
1361 continue;
1362 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001363 final String enabledStr = parser.getAttributeValue(null, ATTR_ENABLED);
1364 final int enabled = enabledStr == null
1365 ? COMPONENT_ENABLED_STATE_DEFAULT : Integer.parseInt(enabledStr);
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07001366 final String enabledCaller = parser.getAttributeValue(null,
1367 ATTR_ENABLED_CALLER);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001368 final String installedStr = parser.getAttributeValue(null, ATTR_INSTALLED);
1369 final boolean installed = installedStr == null
1370 ? true : Boolean.parseBoolean(installedStr);
1371 final String stoppedStr = parser.getAttributeValue(null, ATTR_STOPPED);
1372 final boolean stopped = stoppedStr == null
1373 ? false : Boolean.parseBoolean(stoppedStr);
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001374 // For backwards compatibility with the previous name of "blocked", which
1375 // now means hidden, read the old attribute as well.
Amith Yamasani655d0e22013-06-12 14:19:10 -07001376 final String blockedStr = parser.getAttributeValue(null, ATTR_BLOCKED);
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001377 boolean hidden = blockedStr == null
Amith Yamasani655d0e22013-06-12 14:19:10 -07001378 ? false : Boolean.parseBoolean(blockedStr);
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001379 final String hiddenStr = parser.getAttributeValue(null, ATTR_HIDDEN);
1380 hidden = hiddenStr == null
1381 ? hidden : Boolean.parseBoolean(hiddenStr);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001382 final String notLaunchedStr = parser.getAttributeValue(null, ATTR_NOT_LAUNCHED);
1383 final boolean notLaunched = stoppedStr == null
1384 ? false : Boolean.parseBoolean(notLaunchedStr);
Kenny Guyc13053b2014-05-29 14:17:17 +01001385 final String blockUninstallStr = parser.getAttributeValue(null,
1386 ATTR_BLOCK_UNINSTALL);
1387 final boolean blockUninstall = blockUninstallStr == null
1388 ? false : Boolean.parseBoolean(blockUninstallStr);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001389
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001390 final String verifStateStr =
1391 parser.getAttributeValue(null, ATTR_DOMAIN_VERIFICATON_STATE);
1392 final int verifState = (verifStateStr == null) ?
1393 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED :
1394 Integer.parseInt(verifStateStr);
1395
Jeff Sharkey9f837a92014-10-24 12:07:24 -07001396 ArraySet<String> enabledComponents = null;
1397 ArraySet<String> disabledComponents = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001398
1399 int packageDepth = parser.getDepth();
1400 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1401 && (type != XmlPullParser.END_TAG
1402 || parser.getDepth() > packageDepth)) {
1403 if (type == XmlPullParser.END_TAG
1404 || type == XmlPullParser.TEXT) {
1405 continue;
1406 }
1407 tagName = parser.getName();
1408 if (tagName.equals(TAG_ENABLED_COMPONENTS)) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001409 enabledComponents = readComponentsLPr(parser);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001410 } else if (tagName.equals(TAG_DISABLED_COMPONENTS)) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001411 disabledComponents = readComponentsLPr(parser);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001412 }
1413 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001414
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001415 ps.setUserState(userId, enabled, installed, stopped, notLaunched, hidden,
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001416 enabledCaller, enabledComponents, disabledComponents, blockUninstall,
1417 verifState);
Dianne Hackborn63092712012-10-07 14:45:35 -07001418 } else if (tagName.equals("preferred-activities")) {
1419 readPreferredActivitiesLPw(parser, userId);
Sander Alewijnseaf597622014-03-20 18:44:57 +00001420 } else if (tagName.equals(TAG_PERSISTENT_PREFERRED_ACTIVITIES)) {
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001421 readPersistentPreferredActivitiesLPw(parser, userId);
Nicolas Prevot29762c32014-07-29 18:51:32 +01001422 } else if (tagName.equals(TAG_CROSS_PROFILE_INTENT_FILTERS)) {
Nicolas Prevot81948992014-05-16 18:25:26 +01001423 readCrossProfileIntentFiltersLPw(parser, userId);
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001424 } else if (tagName.equals(TAG_DEFAULT_APPS)) {
1425 readDefaultAppsLPw(parser, userId);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001426 } else {
1427 Slog.w(PackageManagerService.TAG, "Unknown element under <stopped-packages>: "
1428 + parser.getName());
1429 XmlUtils.skipCurrentTag(parser);
1430 }
1431 }
1432
1433 str.close();
1434
1435 } catch (XmlPullParserException e) {
1436 mReadMessages.append("Error reading: " + e.toString());
1437 PackageManagerService.reportSettingsProblem(Log.ERROR,
1438 "Error reading stopped packages: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07001439 Slog.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages",
1440 e);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001441
1442 } catch (java.io.IOException e) {
1443 mReadMessages.append("Error reading: " + e.toString());
1444 PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07001445 Slog.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages",
1446 e);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001447 }
1448 }
1449
Jeff Sharkey9f837a92014-10-24 12:07:24 -07001450 private ArraySet<String> readComponentsLPr(XmlPullParser parser)
Amith Yamasani483f3b02012-03-13 16:08:00 -07001451 throws IOException, XmlPullParserException {
Jeff Sharkey9f837a92014-10-24 12:07:24 -07001452 ArraySet<String> components = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001453 int type;
1454 int outerDepth = parser.getDepth();
1455 String tagName;
1456 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1457 && (type != XmlPullParser.END_TAG
1458 || parser.getDepth() > outerDepth)) {
1459 if (type == XmlPullParser.END_TAG
1460 || type == XmlPullParser.TEXT) {
1461 continue;
1462 }
1463 tagName = parser.getName();
1464 if (tagName.equals(TAG_ITEM)) {
1465 String componentName = parser.getAttributeValue(null, ATTR_NAME);
1466 if (componentName != null) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001467 if (components == null) {
Jeff Sharkey9f837a92014-10-24 12:07:24 -07001468 components = new ArraySet<String>();
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001469 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07001470 components.add(componentName);
1471 }
1472 }
1473 }
1474 return components;
1475 }
1476
Christopher Tatee012a232015-04-01 17:18:50 -07001477 /**
1478 * Record the state of preferred activity configuration into XML. This is used both
1479 * for recording packages.xml internally and for supporting backup/restore of the
1480 * preferred activity configuration.
1481 */
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08001482 void writePreferredActivitiesLPr(XmlSerializer serializer, int userId, boolean full)
Dianne Hackborn63092712012-10-07 14:45:35 -07001483 throws IllegalArgumentException, IllegalStateException, IOException {
1484 serializer.startTag(null, "preferred-activities");
1485 PreferredIntentResolver pir = mPreferredActivities.get(userId);
1486 if (pir != null) {
1487 for (final PreferredActivity pa : pir.filterSet()) {
1488 serializer.startTag(null, TAG_ITEM);
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08001489 pa.writeToXml(serializer, full);
Dianne Hackborn63092712012-10-07 14:45:35 -07001490 serializer.endTag(null, TAG_ITEM);
1491 }
1492 }
1493 serializer.endTag(null, "preferred-activities");
1494 }
1495
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001496 void writePersistentPreferredActivitiesLPr(XmlSerializer serializer, int userId)
1497 throws IllegalArgumentException, IllegalStateException, IOException {
Sander Alewijnseaf597622014-03-20 18:44:57 +00001498 serializer.startTag(null, TAG_PERSISTENT_PREFERRED_ACTIVITIES);
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001499 PersistentPreferredIntentResolver ppir = mPersistentPreferredActivities.get(userId);
1500 if (ppir != null) {
1501 for (final PersistentPreferredActivity ppa : ppir.filterSet()) {
1502 serializer.startTag(null, TAG_ITEM);
1503 ppa.writeToXml(serializer);
1504 serializer.endTag(null, TAG_ITEM);
1505 }
1506 }
Sander Alewijnseaf597622014-03-20 18:44:57 +00001507 serializer.endTag(null, TAG_PERSISTENT_PREFERRED_ACTIVITIES);
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001508 }
1509
Nicolas Prevot81948992014-05-16 18:25:26 +01001510 void writeCrossProfileIntentFiltersLPr(XmlSerializer serializer, int userId)
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001511 throws IllegalArgumentException, IllegalStateException, IOException {
Nicolas Prevot81948992014-05-16 18:25:26 +01001512 serializer.startTag(null, TAG_CROSS_PROFILE_INTENT_FILTERS);
1513 CrossProfileIntentResolver cpir = mCrossProfileIntentResolvers.get(userId);
1514 if (cpir != null) {
1515 for (final CrossProfileIntentFilter cpif : cpir.filterSet()) {
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001516 serializer.startTag(null, TAG_ITEM);
Nicolas Prevot81948992014-05-16 18:25:26 +01001517 cpif.writeToXml(serializer);
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001518 serializer.endTag(null, TAG_ITEM);
1519 }
1520 }
Nicolas Prevot81948992014-05-16 18:25:26 +01001521 serializer.endTag(null, TAG_CROSS_PROFILE_INTENT_FILTERS);
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001522 }
1523
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001524 void writeDomainVerificationsLPr(XmlSerializer serializer,
1525 IntentFilterVerificationInfo verificationInfo)
1526 throws IllegalArgumentException, IllegalStateException, IOException {
1527 if (verificationInfo != null && verificationInfo.getPackageName() != null) {
1528 serializer.startTag(null, TAG_DOMAIN_VERIFICATION);
1529 verificationInfo.writeToXml(serializer);
1530 Log.d(TAG, "Wrote domain verification for package: "
1531 + verificationInfo.getPackageName());
1532 serializer.endTag(null, TAG_DOMAIN_VERIFICATION);
1533 }
1534 }
1535
1536 void writeDefaultAppsLPr(XmlSerializer serializer, int userId)
1537 throws IllegalArgumentException, IllegalStateException, IOException {
1538 serializer.startTag(null, TAG_DEFAULT_APPS);
1539 String packageName = mDefaultBrowserApp.get(userId);
1540 if (!TextUtils.isEmpty(packageName)) {
1541 serializer.startTag(null, TAG_DEFAULT_BROWSER);
1542 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
1543 serializer.endTag(null, TAG_DEFAULT_BROWSER);
1544 }
1545 serializer.endTag(null, TAG_DEFAULT_APPS);
1546 }
1547
Amith Yamasani483f3b02012-03-13 16:08:00 -07001548 void writePackageRestrictionsLPr(int userId) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001549 if (DEBUG_MU) {
1550 Log.i(TAG, "Writing package restrictions for user=" + userId);
1551 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001552 // Keep the old stopped packages around until we know the new ones have
1553 // been successfully written.
Amith Yamasani483f3b02012-03-13 16:08:00 -07001554 File userPackagesStateFile = getUserPackagesStateFile(userId);
1555 File backupFile = getUserPackagesStateBackupFile(userId);
1556 new File(userPackagesStateFile.getParent()).mkdirs();
1557 if (userPackagesStateFile.exists()) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001558 // Presence of backup settings file indicates that we failed
1559 // to persist packages earlier. So preserve the older
1560 // backup for future reference since the current packages
1561 // might have been corrupted.
Amith Yamasani483f3b02012-03-13 16:08:00 -07001562 if (!backupFile.exists()) {
1563 if (!userPackagesStateFile.renameTo(backupFile)) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07001564 Slog.wtf(PackageManagerService.TAG,
1565 "Unable to backup user packages state file, "
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001566 + "current changes will be lost at reboot");
1567 return;
1568 }
1569 } else {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001570 userPackagesStateFile.delete();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001571 Slog.w(PackageManagerService.TAG, "Preserving older stopped packages backup");
1572 }
1573 }
1574
1575 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001576 final FileOutputStream fstr = new FileOutputStream(userPackagesStateFile);
Kenny Root447106f2011-03-23 11:00:15 -07001577 final BufferedOutputStream str = new BufferedOutputStream(fstr);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001578
Kenny Root447106f2011-03-23 11:00:15 -07001579 final XmlSerializer serializer = new FastXmlSerializer();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001580 serializer.setOutput(str, "utf-8");
1581 serializer.startDocument(null, true);
1582 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1583
Amith Yamasani483f3b02012-03-13 16:08:00 -07001584 serializer.startTag(null, TAG_PACKAGE_RESTRICTIONS);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001585
Kenny Root447106f2011-03-23 11:00:15 -07001586 for (final PackageSetting pkg : mPackages.values()) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001587 PackageUserState ustate = pkg.readUserState(userId);
1588 if (ustate.stopped || ustate.notLaunched || !ustate.installed
1589 || ustate.enabled != COMPONENT_ENABLED_STATE_DEFAULT
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001590 || ustate.hidden
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001591 || (ustate.enabledComponents != null
1592 && ustate.enabledComponents.size() > 0)
1593 || (ustate.disabledComponents != null
Kenny Guyc13053b2014-05-29 14:17:17 +01001594 && ustate.disabledComponents.size() > 0)
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001595 || ustate.blockUninstall
1596 || (ustate.domainVerificationStatus !=
1597 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED)) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001598 serializer.startTag(null, TAG_PACKAGE);
1599 serializer.attribute(null, ATTR_NAME, pkg.name);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001600 if (DEBUG_MU) Log.i(TAG, " pkg=" + pkg.name + ", state=" + ustate.enabled);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001601
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001602 if (!ustate.installed) {
1603 serializer.attribute(null, ATTR_INSTALLED, "false");
1604 }
1605 if (ustate.stopped) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001606 serializer.attribute(null, ATTR_STOPPED, "true");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001607 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001608 if (ustate.notLaunched) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001609 serializer.attribute(null, ATTR_NOT_LAUNCHED, "true");
1610 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001611 if (ustate.hidden) {
1612 serializer.attribute(null, ATTR_HIDDEN, "true");
Amith Yamasani655d0e22013-06-12 14:19:10 -07001613 }
Kenny Guyc13053b2014-05-29 14:17:17 +01001614 if (ustate.blockUninstall) {
1615 serializer.attribute(null, ATTR_BLOCK_UNINSTALL, "true");
1616 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001617 if (ustate.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
1618 serializer.attribute(null, ATTR_ENABLED,
1619 Integer.toString(ustate.enabled));
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07001620 if (ustate.lastDisableAppCaller != null) {
1621 serializer.attribute(null, ATTR_ENABLED_CALLER,
1622 ustate.lastDisableAppCaller);
1623 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07001624 }
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001625 if (ustate.domainVerificationStatus !=
1626 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
1627 serializer.attribute(null, ATTR_DOMAIN_VERIFICATON_STATE,
1628 Integer.toString(ustate.domainVerificationStatus));
1629 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001630 if (ustate.enabledComponents != null
1631 && ustate.enabledComponents.size() > 0) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001632 serializer.startTag(null, TAG_ENABLED_COMPONENTS);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001633 for (final String name : ustate.enabledComponents) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001634 serializer.startTag(null, TAG_ITEM);
1635 serializer.attribute(null, ATTR_NAME, name);
1636 serializer.endTag(null, TAG_ITEM);
1637 }
1638 serializer.endTag(null, TAG_ENABLED_COMPONENTS);
1639 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001640 if (ustate.disabledComponents != null
1641 && ustate.disabledComponents.size() > 0) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001642 serializer.startTag(null, TAG_DISABLED_COMPONENTS);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001643 for (final String name : ustate.disabledComponents) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001644 serializer.startTag(null, TAG_ITEM);
1645 serializer.attribute(null, ATTR_NAME, name);
1646 serializer.endTag(null, TAG_ITEM);
1647 }
1648 serializer.endTag(null, TAG_DISABLED_COMPONENTS);
1649 }
Svetoslavc6d1c342015-02-26 14:44:43 -08001650
Amith Yamasani483f3b02012-03-13 16:08:00 -07001651 serializer.endTag(null, TAG_PACKAGE);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001652 }
1653 }
1654
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08001655 writePreferredActivitiesLPr(serializer, userId, true);
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001656 writePersistentPreferredActivitiesLPr(serializer, userId);
Nicolas Prevot81948992014-05-16 18:25:26 +01001657 writeCrossProfileIntentFiltersLPr(serializer, userId);
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001658 writeDefaultAppsLPr(serializer, userId);
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001659
Amith Yamasani483f3b02012-03-13 16:08:00 -07001660 serializer.endTag(null, TAG_PACKAGE_RESTRICTIONS);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001661
1662 serializer.endDocument();
1663
1664 str.flush();
1665 FileUtils.sync(fstr);
1666 str.close();
1667
1668 // New settings successfully written, old ones are no longer
1669 // needed.
Amith Yamasani483f3b02012-03-13 16:08:00 -07001670 backupFile.delete();
1671 FileUtils.setPermissions(userPackagesStateFile.toString(),
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001672 FileUtils.S_IRUSR|FileUtils.S_IWUSR
Nick Kralevich70522ad2012-01-06 13:58:01 -08001673 |FileUtils.S_IRGRP|FileUtils.S_IWGRP,
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001674 -1, -1);
1675
1676 // Done, all is good!
1677 return;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001678 } catch(java.io.IOException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07001679 Slog.wtf(PackageManagerService.TAG,
Amith Yamasani483f3b02012-03-13 16:08:00 -07001680 "Unable to write package manager user packages state, "
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001681 + " current changes will be lost at reboot", e);
1682 }
1683
1684 // Clean up partially written files
Amith Yamasani483f3b02012-03-13 16:08:00 -07001685 if (userPackagesStateFile.exists()) {
1686 if (!userPackagesStateFile.delete()) {
1687 Log.i(PackageManagerService.TAG, "Failed to clean up mangled file: "
1688 + mStoppedPackagesFilename);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001689 }
1690 }
1691 }
1692
Svetoslavc6d1c342015-02-26 14:44:43 -08001693 void readInstallPermissionsLPr(XmlPullParser parser,
1694 PermissionsState permissionsState) throws IOException, XmlPullParserException {
1695 int outerDepth = parser.getDepth();
1696 int type;
1697 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1698 && (type != XmlPullParser.END_TAG
1699 || parser.getDepth() > outerDepth)) {
1700 if (type == XmlPullParser.END_TAG
1701 || type == XmlPullParser.TEXT) {
1702 continue;
1703 }
1704 String tagName = parser.getName();
1705 if (tagName.equals(TAG_ITEM)) {
1706 String name = parser.getAttributeValue(null, ATTR_NAME);
1707
1708 BasePermission bp = mPermissions.get(name);
1709 if (bp == null) {
1710 Slog.w(PackageManagerService.TAG, "Unknown permission: " + name);
1711 XmlUtils.skipCurrentTag(parser);
1712 continue;
1713 }
1714
1715 if (permissionsState.grantInstallPermission(bp) ==
1716 PermissionsState.PERMISSION_OPERATION_FAILURE) {
1717 Slog.w(PackageManagerService.TAG, "Permission already added: " + name);
1718 XmlUtils.skipCurrentTag(parser);
1719 }
1720 } else {
1721 Slog.w(PackageManagerService.TAG, "Unknown element under <permissions>: "
1722 + parser.getName());
1723 XmlUtils.skipCurrentTag(parser);
1724 }
1725 }
1726 }
1727
1728 void writePermissionsLPr(XmlSerializer serializer, Set<String> permissions)
1729 throws IOException {
1730 if (permissions.isEmpty()) {
1731 return;
1732 }
1733
1734 serializer.startTag(null, TAG_PERMISSIONS);
1735
1736 for (String permission : permissions) {
1737 serializer.startTag(null, TAG_ITEM);
1738 serializer.attribute(null, ATTR_NAME, permission);
1739 serializer.endTag(null, TAG_ITEM);
1740 }
1741
1742 serializer.endTag(null, TAG_PERMISSIONS);
1743 }
1744
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001745 // Note: assumed "stopped" field is already cleared in all packages.
Amith Yamasani483f3b02012-03-13 16:08:00 -07001746 // Legacy reader, used to read in the old file format after an upgrade. Not used after that.
Kenny Root447106f2011-03-23 11:00:15 -07001747 void readStoppedLPw() {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001748 FileInputStream str = null;
1749 if (mBackupStoppedPackagesFilename.exists()) {
1750 try {
1751 str = new FileInputStream(mBackupStoppedPackagesFilename);
1752 mReadMessages.append("Reading from backup stopped packages file\n");
Amith Yamasani483f3b02012-03-13 16:08:00 -07001753 PackageManagerService.reportSettingsProblem(Log.INFO,
1754 "Need to read from backup stopped packages file");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001755 if (mSettingsFilename.exists()) {
1756 // If both the backup and normal file exist, we
1757 // ignore the normal one since it might have been
1758 // corrupted.
1759 Slog.w(PackageManagerService.TAG, "Cleaning up stopped packages file "
1760 + mStoppedPackagesFilename);
1761 mStoppedPackagesFilename.delete();
1762 }
1763 } catch (java.io.IOException e) {
1764 // We'll try for the normal settings file.
1765 }
1766 }
1767
1768 try {
1769 if (str == null) {
1770 if (!mStoppedPackagesFilename.exists()) {
1771 mReadMessages.append("No stopped packages file found\n");
Amith Yamasani483f3b02012-03-13 16:08:00 -07001772 PackageManagerService.reportSettingsProblem(Log.INFO,
1773 "No stopped packages file file; assuming all started");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001774 // At first boot, make sure no packages are stopped.
1775 // We usually want to have third party apps initialize
1776 // in the stopped state, but not at first boot.
1777 for (PackageSetting pkg : mPackages.values()) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001778 pkg.setStopped(false, 0);
1779 pkg.setNotLaunched(false, 0);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001780 }
1781 return;
1782 }
1783 str = new FileInputStream(mStoppedPackagesFilename);
1784 }
Kenny Root447106f2011-03-23 11:00:15 -07001785 final XmlPullParser parser = Xml.newPullParser();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001786 parser.setInput(str, null);
1787
1788 int type;
1789 while ((type=parser.next()) != XmlPullParser.START_TAG
1790 && type != XmlPullParser.END_DOCUMENT) {
1791 ;
1792 }
1793
1794 if (type != XmlPullParser.START_TAG) {
1795 mReadMessages.append("No start tag found in stopped packages file\n");
1796 PackageManagerService.reportSettingsProblem(Log.WARN,
1797 "No start tag found in package manager stopped packages");
1798 return;
1799 }
1800
1801 int outerDepth = parser.getDepth();
1802 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1803 && (type != XmlPullParser.END_TAG
1804 || parser.getDepth() > outerDepth)) {
1805 if (type == XmlPullParser.END_TAG
1806 || type == XmlPullParser.TEXT) {
1807 continue;
1808 }
1809
1810 String tagName = parser.getName();
Amith Yamasani483f3b02012-03-13 16:08:00 -07001811 if (tagName.equals(TAG_PACKAGE)) {
1812 String name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001813 PackageSetting ps = mPackages.get(name);
1814 if (ps != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001815 ps.setStopped(true, 0);
1816 if ("1".equals(parser.getAttributeValue(null, ATTR_NOT_LAUNCHED))) {
1817 ps.setNotLaunched(true, 0);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001818 }
1819 } else {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001820 Slog.w(PackageManagerService.TAG,
1821 "No package known for stopped package: " + name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001822 }
1823 XmlUtils.skipCurrentTag(parser);
1824 } else {
1825 Slog.w(PackageManagerService.TAG, "Unknown element under <stopped-packages>: "
1826 + parser.getName());
1827 XmlUtils.skipCurrentTag(parser);
1828 }
1829 }
1830
1831 str.close();
1832
Amith Yamasani483f3b02012-03-13 16:08:00 -07001833 } catch (XmlPullParserException e) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001834 mReadMessages.append("Error reading: " + e.toString());
Amith Yamasani483f3b02012-03-13 16:08:00 -07001835 PackageManagerService.reportSettingsProblem(Log.ERROR,
1836 "Error reading stopped packages: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07001837 Slog.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages",
1838 e);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001839
Amith Yamasani483f3b02012-03-13 16:08:00 -07001840 } catch (java.io.IOException e) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001841 mReadMessages.append("Error reading: " + e.toString());
1842 PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07001843 Slog.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages",
1844 e);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001845
1846 }
1847 }
1848
Kenny Root447106f2011-03-23 11:00:15 -07001849 void writeLPr() {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001850 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
1851
1852 // Keep the old settings around until we know the new ones have
1853 // been successfully written.
1854 if (mSettingsFilename.exists()) {
1855 // Presence of backup settings file indicates that we failed
1856 // to persist settings earlier. So preserve the older
1857 // backup for future reference since the current settings
1858 // might have been corrupted.
1859 if (!mBackupSettingsFilename.exists()) {
1860 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07001861 Slog.wtf(PackageManagerService.TAG,
1862 "Unable to backup package manager settings, "
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001863 + " current changes will be lost at reboot");
1864 return;
1865 }
1866 } else {
1867 mSettingsFilename.delete();
1868 Slog.w(PackageManagerService.TAG, "Preserving older settings backup");
1869 }
1870 }
1871
1872 mPastSignatures.clear();
1873
1874 try {
1875 FileOutputStream fstr = new FileOutputStream(mSettingsFilename);
1876 BufferedOutputStream str = new BufferedOutputStream(fstr);
1877
1878 //XmlSerializer serializer = XmlUtils.serializerInstance();
1879 XmlSerializer serializer = new FastXmlSerializer();
1880 serializer.setOutput(str, "utf-8");
1881 serializer.startDocument(null, true);
1882 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1883
1884 serializer.startTag(null, "packages");
1885
1886 serializer.startTag(null, "last-platform-version");
1887 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
1888 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
Jeff Sharkey4ed745d2014-07-15 20:39:15 -07001889 serializer.attribute(null, "fingerprint", mFingerprint);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001890 serializer.endTag(null, "last-platform-version");
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07001891
Kenny Rootc1c0d3c2014-04-24 13:36:40 -07001892 serializer.startTag(null, "database-version");
1893 serializer.attribute(null, "internal", Integer.toString(mInternalDatabaseVersion));
1894 serializer.attribute(null, "external", Integer.toString(mExternalDatabaseVersion));
1895 serializer.endTag(null, "database-version");
1896
Kenny Root0aaa0d92011-09-12 16:42:55 -07001897 if (mVerifierDeviceIdentity != null) {
1898 serializer.startTag(null, "verifier");
1899 serializer.attribute(null, "device", mVerifierDeviceIdentity.toString());
1900 serializer.endTag(null, "verifier");
1901 }
1902
Jeff Sharkeyf5385772012-05-11 14:04:41 -07001903 if (mReadExternalStorageEnforced != null) {
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07001904 serializer.startTag(null, TAG_READ_EXTERNAL_STORAGE);
1905 serializer.attribute(
Jeff Sharkey5d32e772012-04-12 15:59:23 -07001906 null, ATTR_ENFORCEMENT, mReadExternalStorageEnforced ? "1" : "0");
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07001907 serializer.endTag(null, TAG_READ_EXTERNAL_STORAGE);
1908 }
1909
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001910 serializer.startTag(null, "permission-trees");
1911 for (BasePermission bp : mPermissionTrees.values()) {
Kenny Root447106f2011-03-23 11:00:15 -07001912 writePermissionLPr(serializer, bp);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001913 }
1914 serializer.endTag(null, "permission-trees");
1915
1916 serializer.startTag(null, "permissions");
1917 for (BasePermission bp : mPermissions.values()) {
Kenny Root447106f2011-03-23 11:00:15 -07001918 writePermissionLPr(serializer, bp);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001919 }
1920 serializer.endTag(null, "permissions");
1921
Kenny Root447106f2011-03-23 11:00:15 -07001922 for (final PackageSetting pkg : mPackages.values()) {
1923 writePackageLPr(serializer, pkg);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001924 }
1925
Kenny Root447106f2011-03-23 11:00:15 -07001926 for (final PackageSetting pkg : mDisabledSysPackages.values()) {
1927 writeDisabledSysPackageLPr(serializer, pkg);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001928 }
1929
Kenny Root447106f2011-03-23 11:00:15 -07001930 for (final SharedUserSetting usr : mSharedUsers.values()) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001931 serializer.startTag(null, "shared-user");
Amith Yamasani483f3b02012-03-13 16:08:00 -07001932 serializer.attribute(null, ATTR_NAME, usr.name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001933 serializer.attribute(null, "userId",
1934 Integer.toString(usr.userId));
1935 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
Svetoslavc6d1c342015-02-26 14:44:43 -08001936 writePermissionsLPr(serializer, usr.getPermissionsState().getInstallPermissions());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001937 serializer.endTag(null, "shared-user");
1938 }
1939
1940 if (mPackagesToBeCleaned.size() > 0) {
Jeff Sharkey752cd922012-09-23 16:25:12 -07001941 for (PackageCleanItem item : mPackagesToBeCleaned) {
1942 final String userStr = Integer.toString(item.userId);
1943 serializer.startTag(null, "cleaning-package");
1944 serializer.attribute(null, ATTR_NAME, item.packageName);
1945 serializer.attribute(null, ATTR_CODE, item.andCode ? "true" : "false");
1946 serializer.attribute(null, ATTR_USER, userStr);
1947 serializer.endTag(null, "cleaning-package");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001948 }
1949 }
Svetoslavc6d1c342015-02-26 14:44:43 -08001950
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001951 if (mRenamedPackages.size() > 0) {
Andy McFadden2f362292012-01-20 14:43:38 -08001952 for (Map.Entry<String, String> e : mRenamedPackages.entrySet()) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001953 serializer.startTag(null, "renamed-package");
1954 serializer.attribute(null, "new", e.getKey());
1955 serializer.attribute(null, "old", e.getValue());
1956 serializer.endTag(null, "renamed-package");
1957 }
1958 }
Svetoslavc6d1c342015-02-26 14:44:43 -08001959
dcashman55b10782014-04-09 14:20:38 -07001960 mKeySetManagerService.writeKeySetManagerServiceLPr(serializer);
Geremy Condraf1bcca82013-01-07 22:35:24 -08001961
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001962 serializer.endTag(null, "packages");
1963
1964 serializer.endDocument();
1965
1966 str.flush();
1967 FileUtils.sync(fstr);
1968 str.close();
1969
1970 // New settings successfully written, old ones are no longer
1971 // needed.
1972 mBackupSettingsFilename.delete();
1973 FileUtils.setPermissions(mSettingsFilename.toString(),
1974 FileUtils.S_IRUSR|FileUtils.S_IWUSR
Nick Kralevich70522ad2012-01-06 13:58:01 -08001975 |FileUtils.S_IRGRP|FileUtils.S_IWGRP,
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001976 -1, -1);
1977
1978 // Write package list file now, use a JournaledFile.
Jeff Sharkey184a0102013-07-10 16:19:52 -07001979 File tempFile = new File(mPackageListFilename.getAbsolutePath() + ".tmp");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001980 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
1981
Jeff Sharkey184a0102013-07-10 16:19:52 -07001982 final File writeTarget = journal.chooseForWrite();
1983 fstr = new FileOutputStream(writeTarget);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001984 str = new BufferedOutputStream(fstr);
1985 try {
Jeff Sharkeyaebb65c2014-11-24 15:00:13 -08001986 FileUtils.setPermissions(fstr.getFD(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
Jeff Sharkey184a0102013-07-10 16:19:52 -07001987
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001988 StringBuilder sb = new StringBuilder();
Kenny Root447106f2011-03-23 11:00:15 -07001989 for (final PackageSetting pkg : mPackages.values()) {
Jeff Sharkey5dea7d52013-09-03 12:01:20 -07001990 if (pkg.pkg == null || pkg.pkg.applicationInfo == null) {
1991 Slog.w(TAG, "Skipping " + pkg + " due to missing metadata");
1992 continue;
1993 }
1994
Jeff Sharkey02e4d16e2013-08-12 20:31:36 -07001995 final ApplicationInfo ai = pkg.pkg.applicationInfo;
1996 final String dataPath = ai.dataDir;
1997 final boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
Svetoslavc6d1c342015-02-26 14:44:43 -08001998 final int[] gids = pkg.getPermissionsState().computeGids();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001999
Jeff Sharkeycc8f7102013-09-10 16:57:24 -07002000 // Avoid any application that has a space in its path.
2001 if (dataPath.indexOf(" ") >= 0)
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002002 continue;
2003
2004 // we store on each line the following information for now:
2005 //
2006 // pkgName - package name
2007 // userId - application-specific user id
2008 // debugFlag - 0 or 1 if the package is debuggable.
2009 // dataPath - path to package's data path
Robert Craig4a453732013-03-26 08:21:37 -04002010 // seinfo - seinfo label for the app (assigned at install time)
Jeff Sharkey02e4d16e2013-08-12 20:31:36 -07002011 // gids - supplementary gids this app launches with
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002012 //
2013 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
2014 //
2015 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
2016 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
Mark Salyzyn2018fd02015-03-12 09:18:26 -07002017 // system/core/logd/LogStatistics.cpp
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002018 // system/core/run-as/run-as.c
Jeff Sharkey184a0102013-07-10 16:19:52 -07002019 // system/core/sdcard/sdcard.c
Nick Kralevich32cc40a2014-03-26 15:55:41 +00002020 // external/libselinux/src/android.c:package_info_init()
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002021 //
2022 sb.setLength(0);
2023 sb.append(ai.packageName);
2024 sb.append(" ");
2025 sb.append((int)ai.uid);
2026 sb.append(isDebug ? " 1 " : " 0 ");
2027 sb.append(dataPath);
Robert Craig4a453732013-03-26 08:21:37 -04002028 sb.append(" ");
2029 sb.append(ai.seinfo);
Jeff Sharkey02e4d16e2013-08-12 20:31:36 -07002030 sb.append(" ");
2031 if (gids != null && gids.length > 0) {
2032 sb.append(gids[0]);
2033 for (int i = 1; i < gids.length; i++) {
2034 sb.append(",");
2035 sb.append(gids[i]);
2036 }
2037 } else {
2038 sb.append("none");
2039 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002040 sb.append("\n");
2041 str.write(sb.toString().getBytes());
2042 }
2043 str.flush();
2044 FileUtils.sync(fstr);
2045 str.close();
2046 journal.commit();
Kenny Root62539e92011-11-10 09:35:38 -08002047 } catch (Exception e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002048 Slog.wtf(TAG, "Failed to write packages.list", e);
Kenny Root62539e92011-11-10 09:35:38 -08002049 IoUtils.closeQuietly(str);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002050 journal.rollback();
2051 }
2052
Amith Yamasani483f3b02012-03-13 16:08:00 -07002053 writeAllUsersPackageRestrictionsLPr();
Svetoslavc6d1c342015-02-26 14:44:43 -08002054
2055 writeAllRuntimePermissionsLPr();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002056 return;
2057
2058 } catch(XmlPullParserException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002059 Slog.wtf(PackageManagerService.TAG, "Unable to write package manager settings, "
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002060 + "current changes will be lost at reboot", e);
2061 } catch(java.io.IOException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002062 Slog.wtf(PackageManagerService.TAG, "Unable to write package manager settings, "
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002063 + "current changes will be lost at reboot", e);
2064 }
2065 // Clean up partially written files
2066 if (mSettingsFilename.exists()) {
2067 if (!mSettingsFilename.delete()) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002068 Slog.wtf(PackageManagerService.TAG, "Failed to clean up mangled file: "
Amith Yamasani483f3b02012-03-13 16:08:00 -07002069 + mSettingsFilename);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002070 }
2071 }
2072 //Debug.stopMethodTracing();
2073 }
2074
Kenny Root447106f2011-03-23 11:00:15 -07002075 void writeDisabledSysPackageLPr(XmlSerializer serializer, final PackageSetting pkg)
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002076 throws java.io.IOException {
2077 serializer.startTag(null, "updated-package");
Amith Yamasani483f3b02012-03-13 16:08:00 -07002078 serializer.attribute(null, ATTR_NAME, pkg.name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002079 if (pkg.realName != null) {
2080 serializer.attribute(null, "realName", pkg.realName);
2081 }
2082 serializer.attribute(null, "codePath", pkg.codePathString);
2083 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
2084 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
2085 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
2086 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
2087 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
2088 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
2089 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002090 if (pkg.legacyNativeLibraryPathString != null) {
2091 serializer.attribute(null, "nativeLibraryPath", pkg.legacyNativeLibraryPathString);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002092 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002093 if (pkg.primaryCpuAbiString != null) {
2094 serializer.attribute(null, "primaryCpuAbi", pkg.primaryCpuAbiString);
Narayan Kamath9e289d72014-04-10 09:26:59 +00002095 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002096 if (pkg.secondaryCpuAbiString != null) {
2097 serializer.attribute(null, "secondaryCpuAbi", pkg.secondaryCpuAbiString);
2098 }
Narayan Kamath4903f642014-08-11 13:33:45 +01002099 if (pkg.cpuAbiOverrideString != null) {
2100 serializer.attribute(null, "cpuAbiOverride", pkg.cpuAbiOverrideString);
2101 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002102
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002103 if (pkg.sharedUser == null) {
Amith Yamasani13593602012-03-22 16:16:17 -07002104 serializer.attribute(null, "userId", Integer.toString(pkg.appId));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002105 } else {
Amith Yamasani13593602012-03-22 16:16:17 -07002106 serializer.attribute(null, "sharedUserId", Integer.toString(pkg.appId));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002107 }
Svetoslavc6d1c342015-02-26 14:44:43 -08002108
2109 // If this is a shared user, the permissions will be written there.
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002110 if (pkg.sharedUser == null) {
Svetoslavc6d1c342015-02-26 14:44:43 -08002111 writePermissionsLPr(serializer, pkg.getPermissionsState().getInstallPermissions());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002112 }
Svetoslavc6d1c342015-02-26 14:44:43 -08002113
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002114 serializer.endTag(null, "updated-package");
2115 }
2116
Kenny Root447106f2011-03-23 11:00:15 -07002117 void writePackageLPr(XmlSerializer serializer, final PackageSetting pkg)
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002118 throws java.io.IOException {
2119 serializer.startTag(null, "package");
Amith Yamasani483f3b02012-03-13 16:08:00 -07002120 serializer.attribute(null, ATTR_NAME, pkg.name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002121 if (pkg.realName != null) {
2122 serializer.attribute(null, "realName", pkg.realName);
2123 }
2124 serializer.attribute(null, "codePath", pkg.codePathString);
2125 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
2126 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
2127 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002128
2129 if (pkg.legacyNativeLibraryPathString != null) {
2130 serializer.attribute(null, "nativeLibraryPath", pkg.legacyNativeLibraryPathString);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002131 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002132 if (pkg.primaryCpuAbiString != null) {
2133 serializer.attribute(null, "primaryCpuAbi", pkg.primaryCpuAbiString);
Narayan Kamath9e289d72014-04-10 09:26:59 +00002134 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002135 if (pkg.secondaryCpuAbiString != null) {
2136 serializer.attribute(null, "secondaryCpuAbi", pkg.secondaryCpuAbiString);
2137 }
Narayan Kamath4903f642014-08-11 13:33:45 +01002138 if (pkg.cpuAbiOverrideString != null) {
2139 serializer.attribute(null, "cpuAbiOverride", pkg.cpuAbiOverrideString);
2140 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002141
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002142 serializer.attribute(null, "publicFlags", Integer.toString(pkg.pkgFlags));
2143 serializer.attribute(null, "privateFlags", Integer.toString(pkg.pkgPrivateFlags));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002144 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
2145 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
2146 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
2147 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
2148 if (pkg.sharedUser == null) {
Amith Yamasani13593602012-03-22 16:16:17 -07002149 serializer.attribute(null, "userId", Integer.toString(pkg.appId));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002150 } else {
Amith Yamasani13593602012-03-22 16:16:17 -07002151 serializer.attribute(null, "sharedUserId", Integer.toString(pkg.appId));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002152 }
2153 if (pkg.uidError) {
2154 serializer.attribute(null, "uidError", "true");
2155 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002156 if (pkg.installStatus == PackageSettingBase.PKG_INSTALL_INCOMPLETE) {
2157 serializer.attribute(null, "installStatus", "false");
2158 }
2159 if (pkg.installerPackageName != null) {
2160 serializer.attribute(null, "installer", pkg.installerPackageName);
2161 }
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07002162 if (pkg.volumeUuid != null) {
2163 serializer.attribute(null, "volumeUuid", pkg.volumeUuid);
2164 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002165 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
2166 if ((pkg.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
Svetoslavc6d1c342015-02-26 14:44:43 -08002167 writePermissionsLPr(serializer, pkg.getPermissionsState().getInstallPermissions());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002168 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002169
dcashman8c04fac2015-03-23 11:39:42 -07002170 writeSigningKeySetLPr(serializer, pkg.keySetData);
dcashman55b10782014-04-09 14:20:38 -07002171 writeUpgradeKeySetsLPr(serializer, pkg.keySetData);
Geremy Condraf1bcca82013-01-07 22:35:24 -08002172 writeKeySetAliasesLPr(serializer, pkg.keySetData);
Fabrice Di Meglio62271722015-04-10 17:24:02 -07002173 writeDomainVerificationsLPr(serializer, pkg.verificationInfo);
Geremy Condraf1bcca82013-01-07 22:35:24 -08002174
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002175 serializer.endTag(null, "package");
2176 }
2177
dcashman8c04fac2015-03-23 11:39:42 -07002178 void writeSigningKeySetLPr(XmlSerializer serializer,
Geremy Condraf1bcca82013-01-07 22:35:24 -08002179 PackageKeySetData data) throws IOException {
dcashman8c04fac2015-03-23 11:39:42 -07002180 serializer.startTag(null, "proper-signing-keyset");
2181 serializer.attribute(null, "identifier",
2182 Long.toString(data.getProperSigningKeySet()));
2183 serializer.endTag(null, "proper-signing-keyset");
dcashman55b10782014-04-09 14:20:38 -07002184 }
2185
2186 void writeUpgradeKeySetsLPr(XmlSerializer serializer,
2187 PackageKeySetData data) throws IOException {
dcashman8c04fac2015-03-23 11:39:42 -07002188 long properSigning = data.getProperSigningKeySet();
dcashman55b10782014-04-09 14:20:38 -07002189 if (data.isUsingUpgradeKeySets()) {
2190 for (long id : data.getUpgradeKeySets()) {
2191 serializer.startTag(null, "upgrade-keyset");
2192 serializer.attribute(null, "identifier", Long.toString(id));
2193 serializer.endTag(null, "upgrade-keyset");
2194 }
Geremy Condraf1bcca82013-01-07 22:35:24 -08002195 }
2196 }
2197
2198 void writeKeySetAliasesLPr(XmlSerializer serializer,
2199 PackageKeySetData data) throws IOException {
2200 for (Map.Entry<String, Long> e: data.getAliases().entrySet()) {
2201 serializer.startTag(null, "defined-keyset");
2202 serializer.attribute(null, "alias", e.getKey());
2203 serializer.attribute(null, "identifier", Long.toString(e.getValue()));
2204 serializer.endTag(null, "defined-keyset");
2205 }
2206 }
2207
Kenny Root447106f2011-03-23 11:00:15 -07002208 void writePermissionLPr(XmlSerializer serializer, BasePermission bp)
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002209 throws XmlPullParserException, java.io.IOException {
2210 if (bp.type != BasePermission.TYPE_BUILTIN && bp.sourcePackage != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002211 serializer.startTag(null, TAG_ITEM);
2212 serializer.attribute(null, ATTR_NAME, bp.name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002213 serializer.attribute(null, "package", bp.sourcePackage);
2214 if (bp.protectionLevel != PermissionInfo.PROTECTION_NORMAL) {
2215 serializer.attribute(null, "protection", Integer.toString(bp.protectionLevel));
2216 }
2217 if (PackageManagerService.DEBUG_SETTINGS)
2218 Log.v(PackageManagerService.TAG, "Writing perm: name=" + bp.name + " type="
2219 + bp.type);
2220 if (bp.type == BasePermission.TYPE_DYNAMIC) {
Kenny Root447106f2011-03-23 11:00:15 -07002221 final PermissionInfo pi = bp.perm != null ? bp.perm.info : bp.pendingInfo;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002222 if (pi != null) {
2223 serializer.attribute(null, "type", "dynamic");
2224 if (pi.icon != 0) {
2225 serializer.attribute(null, "icon", Integer.toString(pi.icon));
2226 }
2227 if (pi.nonLocalizedLabel != null) {
2228 serializer.attribute(null, "label", pi.nonLocalizedLabel.toString());
2229 }
2230 }
2231 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07002232 serializer.endTag(null, TAG_ITEM);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002233 }
2234 }
2235
Kenny Root447106f2011-03-23 11:00:15 -07002236 ArrayList<PackageSetting> getListOfIncompleteInstallPackagesLPr() {
Jeff Sharkey9f837a92014-10-24 12:07:24 -07002237 final ArraySet<String> kList = new ArraySet<String>(mPackages.keySet());
Kenny Root447106f2011-03-23 11:00:15 -07002238 final Iterator<String> its = kList.iterator();
2239 final ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002240 while (its.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07002241 final String key = its.next();
2242 final PackageSetting ps = mPackages.get(key);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002243 if (ps.getInstallStatus() == PackageSettingBase.PKG_INSTALL_INCOMPLETE) {
2244 ret.add(ps);
2245 }
2246 }
2247 return ret;
2248 }
2249
Jeff Sharkey752cd922012-09-23 16:25:12 -07002250 void addPackageToCleanLPw(PackageCleanItem pkg) {
2251 if (!mPackagesToBeCleaned.contains(pkg)) {
2252 mPackagesToBeCleaned.add(pkg);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002253 }
2254 }
2255
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08002256 boolean readLPw(PackageManagerService service, List<UserInfo> users, int sdkVersion,
2257 boolean onlyCore) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002258 FileInputStream str = null;
2259 if (mBackupSettingsFilename.exists()) {
2260 try {
2261 str = new FileInputStream(mBackupSettingsFilename);
2262 mReadMessages.append("Reading from backup settings file\n");
2263 PackageManagerService.reportSettingsProblem(Log.INFO,
2264 "Need to read from backup settings file");
2265 if (mSettingsFilename.exists()) {
2266 // If both the backup and settings file exist, we
2267 // ignore the settings since it might have been
2268 // corrupted.
2269 Slog.w(PackageManagerService.TAG, "Cleaning up settings file "
2270 + mSettingsFilename);
2271 mSettingsFilename.delete();
2272 }
2273 } catch (java.io.IOException e) {
2274 // We'll try for the normal settings file.
2275 }
2276 }
2277
Kenny Root447106f2011-03-23 11:00:15 -07002278 mPendingPackages.clear();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002279 mPastSignatures.clear();
dcashman8c04fac2015-03-23 11:39:42 -07002280 mKeySetRefs.clear();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002281
2282 try {
2283 if (str == null) {
2284 if (!mSettingsFilename.exists()) {
2285 mReadMessages.append("No settings file found\n");
2286 PackageManagerService.reportSettingsProblem(Log.INFO,
2287 "No settings file; creating initial state");
Dianne Hackborn13579ed2012-11-28 18:05:36 -08002288 mInternalSdkPlatform = mExternalSdkPlatform = sdkVersion;
Jeff Sharkey4ed745d2014-07-15 20:39:15 -07002289 mFingerprint = Build.FINGERPRINT;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002290 return false;
2291 }
2292 str = new FileInputStream(mSettingsFilename);
2293 }
2294 XmlPullParser parser = Xml.newPullParser();
2295 parser.setInput(str, null);
2296
2297 int type;
2298 while ((type = parser.next()) != XmlPullParser.START_TAG
2299 && type != XmlPullParser.END_DOCUMENT) {
2300 ;
2301 }
2302
2303 if (type != XmlPullParser.START_TAG) {
2304 mReadMessages.append("No start tag found in settings file\n");
2305 PackageManagerService.reportSettingsProblem(Log.WARN,
2306 "No start tag found in package manager settings");
Dianne Hackborn8d051722014-10-01 14:59:58 -07002307 Slog.wtf(PackageManagerService.TAG,
Dianne Hackborn58f42a52011-10-10 13:46:34 -07002308 "No start tag found in package manager settings");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002309 return false;
2310 }
2311
2312 int outerDepth = parser.getDepth();
2313 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2314 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2315 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2316 continue;
2317 }
2318
2319 String tagName = parser.getName();
2320 if (tagName.equals("package")) {
Kenny Root447106f2011-03-23 11:00:15 -07002321 readPackageLPw(parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002322 } else if (tagName.equals("permissions")) {
Kenny Root447106f2011-03-23 11:00:15 -07002323 readPermissionsLPw(mPermissions, parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002324 } else if (tagName.equals("permission-trees")) {
Kenny Root447106f2011-03-23 11:00:15 -07002325 readPermissionsLPw(mPermissionTrees, parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002326 } else if (tagName.equals("shared-user")) {
Kenny Root447106f2011-03-23 11:00:15 -07002327 readSharedUserLPw(parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002328 } else if (tagName.equals("preferred-packages")) {
2329 // no longer used.
2330 } else if (tagName.equals("preferred-activities")) {
Dianne Hackborn63092712012-10-07 14:45:35 -07002331 // Upgrading from old single-user implementation;
2332 // these are the preferred activities for user 0.
2333 readPreferredActivitiesLPw(parser, 0);
Sander Alewijnseaf597622014-03-20 18:44:57 +00002334 } else if (tagName.equals(TAG_PERSISTENT_PREFERRED_ACTIVITIES)) {
Sander Alewijnsef475ca32014-02-17 15:13:58 +00002335 // TODO: check whether this is okay! as it is very
2336 // similar to how preferred-activities are treated
2337 readPersistentPreferredActivitiesLPw(parser, 0);
Nicolas Prevot29762c32014-07-29 18:51:32 +01002338 } else if (tagName.equals(TAG_CROSS_PROFILE_INTENT_FILTERS)) {
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00002339 // TODO: check whether this is okay! as it is very
2340 // similar to how preferred-activities are treated
Nicolas Prevot81948992014-05-16 18:25:26 +01002341 readCrossProfileIntentFiltersLPw(parser, 0);
Fabrice Di Meglio62271722015-04-10 17:24:02 -07002342 } else if (tagName.equals(TAG_DEFAULT_BROWSER)) {
2343 readDefaultAppsLPw(parser, 0);
2344 } else if (tagName.equals("updated-package")) {
Kenny Root447106f2011-03-23 11:00:15 -07002345 readDisabledSysPackageLPw(parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002346 } else if (tagName.equals("cleaning-package")) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002347 String name = parser.getAttributeValue(null, ATTR_NAME);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002348 String userStr = parser.getAttributeValue(null, ATTR_USER);
2349 String codeStr = parser.getAttributeValue(null, ATTR_CODE);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002350 if (name != null) {
Jeff Sharkey752cd922012-09-23 16:25:12 -07002351 int userId = 0;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002352 boolean andCode = true;
2353 try {
2354 if (userStr != null) {
Jeff Sharkey752cd922012-09-23 16:25:12 -07002355 userId = Integer.parseInt(userStr);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002356 }
2357 } catch (NumberFormatException e) {
2358 }
2359 if (codeStr != null) {
2360 andCode = Boolean.parseBoolean(codeStr);
2361 }
Jeff Sharkey752cd922012-09-23 16:25:12 -07002362 addPackageToCleanLPw(new PackageCleanItem(userId, name, andCode));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002363 }
2364 } else if (tagName.equals("renamed-package")) {
2365 String nname = parser.getAttributeValue(null, "new");
2366 String oname = parser.getAttributeValue(null, "old");
2367 if (nname != null && oname != null) {
2368 mRenamedPackages.put(nname, oname);
2369 }
2370 } else if (tagName.equals("last-platform-version")) {
2371 mInternalSdkPlatform = mExternalSdkPlatform = 0;
2372 try {
2373 String internal = parser.getAttributeValue(null, "internal");
2374 if (internal != null) {
2375 mInternalSdkPlatform = Integer.parseInt(internal);
2376 }
2377 String external = parser.getAttributeValue(null, "external");
2378 if (external != null) {
2379 mExternalSdkPlatform = Integer.parseInt(external);
2380 }
2381 } catch (NumberFormatException e) {
2382 }
Jeff Sharkey4ed745d2014-07-15 20:39:15 -07002383 mFingerprint = parser.getAttributeValue(null, "fingerprint");
Kenny Rootc1c0d3c2014-04-24 13:36:40 -07002384 } else if (tagName.equals("database-version")) {
2385 mInternalDatabaseVersion = mExternalDatabaseVersion = 0;
2386 try {
2387 String internalDbVersionString = parser.getAttributeValue(null, "internal");
2388 if (internalDbVersionString != null) {
2389 mInternalDatabaseVersion = Integer.parseInt(internalDbVersionString);
2390 }
2391 String externalDbVersionString = parser.getAttributeValue(null, "external");
2392 if (externalDbVersionString != null) {
2393 mExternalDatabaseVersion = Integer.parseInt(externalDbVersionString);
2394 }
2395 } catch (NumberFormatException ignored) {
2396 }
Kenny Root0aaa0d92011-09-12 16:42:55 -07002397 } else if (tagName.equals("verifier")) {
2398 final String deviceIdentity = parser.getAttributeValue(null, "device");
2399 try {
2400 mVerifierDeviceIdentity = VerifierDeviceIdentity.parse(deviceIdentity);
2401 } catch (IllegalArgumentException e) {
2402 Slog.w(PackageManagerService.TAG, "Discard invalid verifier device id: "
2403 + e.getMessage());
2404 }
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07002405 } else if (TAG_READ_EXTERNAL_STORAGE.equals(tagName)) {
2406 final String enforcement = parser.getAttributeValue(null, ATTR_ENFORCEMENT);
Jeff Sharkey5d32e772012-04-12 15:59:23 -07002407 mReadExternalStorageEnforced = "1".equals(enforcement);
Geremy Condraf1bcca82013-01-07 22:35:24 -08002408 } else if (tagName.equals("keyset-settings")) {
dcashman8c04fac2015-03-23 11:39:42 -07002409 mKeySetManagerService.readKeySetsLPw(parser, mKeySetRefs);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002410 } else {
2411 Slog.w(PackageManagerService.TAG, "Unknown element under <packages>: "
2412 + parser.getName());
2413 XmlUtils.skipCurrentTag(parser);
2414 }
2415 }
2416
2417 str.close();
2418
2419 } catch (XmlPullParserException e) {
2420 mReadMessages.append("Error reading: " + e.toString());
2421 PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07002422 Slog.wtf(PackageManagerService.TAG, "Error reading package manager settings", e);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002423
2424 } catch (java.io.IOException e) {
2425 mReadMessages.append("Error reading: " + e.toString());
2426 PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07002427 Slog.wtf(PackageManagerService.TAG, "Error reading package manager settings", e);
Amith Yamasani258848d2012-08-10 17:06:33 -07002428 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002429
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002430 final int N = mPendingPackages.size();
dcashman8c04fac2015-03-23 11:39:42 -07002431
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002432 for (int i = 0; i < N; i++) {
2433 final PendingPackage pp = mPendingPackages.get(i);
Kenny Root447106f2011-03-23 11:00:15 -07002434 Object idObj = getUserIdLPr(pp.sharedId);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002435 if (idObj != null && idObj instanceof SharedUserSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002436 PackageSetting p = getPackageLPw(pp.name, null, pp.realName,
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002437 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
Narayan Kamathff110bd2014-07-04 18:30:45 +01002438 pp.legacyNativeLibraryPathString, pp.primaryCpuAbiString,
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002439 pp.secondaryCpuAbiString, pp.versionCode, pp.pkgFlags, pp.pkgPrivateFlags,
2440 null, true /* add */, false /* allowInstall */);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002441 if (p == null) {
2442 PackageManagerService.reportSettingsProblem(Log.WARN,
2443 "Unable to create application package for " + pp.name);
2444 continue;
2445 }
2446 p.copyFrom(pp);
2447 } else if (idObj != null) {
2448 String msg = "Bad package setting: package " + pp.name + " has shared uid "
2449 + pp.sharedId + " that is not a shared uid\n";
2450 mReadMessages.append(msg);
2451 PackageManagerService.reportSettingsProblem(Log.ERROR, msg);
2452 } else {
2453 String msg = "Bad package setting: package " + pp.name + " has shared uid "
2454 + pp.sharedId + " that is not defined\n";
2455 mReadMessages.append(msg);
2456 PackageManagerService.reportSettingsProblem(Log.ERROR, msg);
2457 }
2458 }
2459 mPendingPackages.clear();
2460
Amith Yamasanif031f232012-10-26 15:35:21 -07002461 if (mBackupStoppedPackagesFilename.exists()
2462 || mStoppedPackagesFilename.exists()) {
2463 // Read old file
2464 readStoppedLPw();
2465 mBackupStoppedPackagesFilename.delete();
2466 mStoppedPackagesFilename.delete();
2467 // Migrate to new file format
2468 writePackageRestrictionsLPr(0);
2469 } else {
2470 if (users == null) {
2471 readPackageRestrictionsLPr(0);
Svetoslavc6d1c342015-02-26 14:44:43 -08002472 mRuntimePermissionsPersistence.readStateForUserSyncLPr(UserHandle.USER_OWNER);
Amith Yamasanif031f232012-10-26 15:35:21 -07002473 } else {
2474 for (UserInfo user : users) {
2475 readPackageRestrictionsLPr(user.id);
Svetoslavc6d1c342015-02-26 14:44:43 -08002476 mRuntimePermissionsPersistence.readStateForUserSyncLPr(user.id);
Amith Yamasanif031f232012-10-26 15:35:21 -07002477 }
2478 }
2479 }
2480
Kenny Root1d1b4892011-04-08 14:25:24 -07002481 /*
2482 * Make sure all the updated system packages have their shared users
2483 * associated with them.
2484 */
2485 final Iterator<PackageSetting> disabledIt = mDisabledSysPackages.values().iterator();
2486 while (disabledIt.hasNext()) {
2487 final PackageSetting disabledPs = disabledIt.next();
Amith Yamasani13593602012-03-22 16:16:17 -07002488 final Object id = getUserIdLPr(disabledPs.appId);
Kenny Root1d1b4892011-04-08 14:25:24 -07002489 if (id != null && id instanceof SharedUserSetting) {
2490 disabledPs.sharedUser = (SharedUserSetting) id;
2491 }
2492 }
2493
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002494 mReadMessages.append("Read completed successfully: " + mPackages.size() + " packages, "
2495 + mSharedUsers.size() + " shared uids\n");
2496
2497 return true;
2498 }
2499
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08002500 void readDefaultPreferredAppsLPw(PackageManagerService service, int userId) {
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002501 // First pull data from any pre-installed apps.
2502 for (PackageSetting ps : mPackages.values()) {
2503 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0 && ps.pkg != null
2504 && ps.pkg.preferredActivityFilters != null) {
2505 ArrayList<PackageParser.ActivityIntentInfo> intents
2506 = ps.pkg.preferredActivityFilters;
2507 for (int i=0; i<intents.size(); i++) {
2508 PackageParser.ActivityIntentInfo aii = intents.get(i);
2509 applyDefaultPreferredActivityLPw(service, aii, new ComponentName(
2510 ps.name, aii.activity.className), userId);
2511 }
2512 }
2513 }
2514
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07002515 // Read preferred apps from .../etc/preferred-apps directory.
2516 File preferredDir = new File(Environment.getRootDirectory(), "etc/preferred-apps");
2517 if (!preferredDir.exists() || !preferredDir.isDirectory()) {
2518 return;
2519 }
2520 if (!preferredDir.canRead()) {
2521 Slog.w(TAG, "Directory " + preferredDir + " cannot be read");
2522 return;
2523 }
2524
2525 // Iterate over the files in the directory and scan .xml files
2526 for (File f : preferredDir.listFiles()) {
2527 if (!f.getPath().endsWith(".xml")) {
2528 Slog.i(TAG, "Non-xml file " + f + " in " + preferredDir + " directory, ignoring");
2529 continue;
2530 }
2531 if (!f.canRead()) {
2532 Slog.w(TAG, "Preferred apps file " + f + " cannot be read");
2533 continue;
2534 }
2535
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08002536 if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Reading default preferred " + f);
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07002537 FileInputStream str = null;
2538 try {
2539 str = new FileInputStream(f);
2540 XmlPullParser parser = Xml.newPullParser();
2541 parser.setInput(str, null);
2542
2543 int type;
2544 while ((type = parser.next()) != XmlPullParser.START_TAG
2545 && type != XmlPullParser.END_DOCUMENT) {
2546 ;
2547 }
2548
2549 if (type != XmlPullParser.START_TAG) {
2550 Slog.w(TAG, "Preferred apps file " + f + " does not have start tag");
2551 continue;
2552 }
2553 if (!"preferred-activities".equals(parser.getName())) {
2554 Slog.w(TAG, "Preferred apps file " + f
2555 + " does not start with 'preferred-activities'");
2556 continue;
2557 }
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08002558 readDefaultPreferredActivitiesLPw(service, parser, userId);
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07002559 } catch (XmlPullParserException e) {
2560 Slog.w(TAG, "Error reading apps file " + f, e);
2561 } catch (IOException e) {
2562 Slog.w(TAG, "Error reading apps file " + f, e);
2563 } finally {
2564 if (str != null) {
2565 try {
2566 str.close();
2567 } catch (IOException e) {
2568 }
2569 }
2570 }
2571 }
2572 }
2573
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002574 private void applyDefaultPreferredActivityLPw(PackageManagerService service,
2575 IntentFilter tmpPa, ComponentName cn, int userId) {
2576 // The initial preferences only specify the target activity
2577 // component and intent-filter, not the set of matches. So we
2578 // now need to query for the matches to build the correct
2579 // preferred activity entry.
2580 if (PackageManagerService.DEBUG_PREFERRED) {
2581 Log.d(TAG, "Processing preferred:");
2582 tmpPa.dump(new LogPrinter(Log.DEBUG, TAG), " ");
2583 }
2584 Intent intent = new Intent();
2585 int flags = 0;
2586 intent.setAction(tmpPa.getAction(0));
2587 for (int i=0; i<tmpPa.countCategories(); i++) {
2588 String cat = tmpPa.getCategory(i);
2589 if (cat.equals(Intent.CATEGORY_DEFAULT)) {
2590 flags |= PackageManager.MATCH_DEFAULT_ONLY;
2591 } else {
2592 intent.addCategory(cat);
2593 }
2594 }
2595
2596 boolean doNonData = true;
Christopher Tate2298ef22013-11-04 17:02:10 -08002597 boolean hasSchemes = false;
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002598
2599 for (int ischeme=0; ischeme<tmpPa.countDataSchemes(); ischeme++) {
2600 boolean doScheme = true;
2601 String scheme = tmpPa.getDataScheme(ischeme);
Christopher Tate2298ef22013-11-04 17:02:10 -08002602 if (scheme != null && !scheme.isEmpty()) {
2603 hasSchemes = true;
2604 }
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002605 for (int issp=0; issp<tmpPa.countDataSchemeSpecificParts(); issp++) {
2606 Uri.Builder builder = new Uri.Builder();
2607 builder.scheme(scheme);
2608 PatternMatcher ssp = tmpPa.getDataSchemeSpecificPart(issp);
2609 builder.opaquePart(ssp.getPath());
2610 Intent finalIntent = new Intent(intent);
2611 finalIntent.setData(builder.build());
2612 applyDefaultPreferredActivityLPw(service, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002613 scheme, ssp, null, null, userId);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002614 doScheme = false;
2615 }
2616 for (int iauth=0; iauth<tmpPa.countDataAuthorities(); iauth++) {
2617 boolean doAuth = true;
2618 IntentFilter.AuthorityEntry auth = tmpPa.getDataAuthority(iauth);
2619 for (int ipath=0; ipath<tmpPa.countDataPaths(); ipath++) {
2620 Uri.Builder builder = new Uri.Builder();
2621 builder.scheme(scheme);
2622 if (auth.getHost() != null) {
2623 builder.authority(auth.getHost());
2624 }
2625 PatternMatcher path = tmpPa.getDataPath(ipath);
2626 builder.path(path.getPath());
2627 Intent finalIntent = new Intent(intent);
2628 finalIntent.setData(builder.build());
2629 applyDefaultPreferredActivityLPw(service, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002630 scheme, null, auth, path, userId);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002631 doAuth = doScheme = false;
2632 }
2633 if (doAuth) {
2634 Uri.Builder builder = new Uri.Builder();
2635 builder.scheme(scheme);
2636 if (auth.getHost() != null) {
2637 builder.authority(auth.getHost());
2638 }
2639 Intent finalIntent = new Intent(intent);
2640 finalIntent.setData(builder.build());
2641 applyDefaultPreferredActivityLPw(service, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002642 scheme, null, auth, null, userId);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002643 doScheme = false;
2644 }
2645 }
2646 if (doScheme) {
2647 Uri.Builder builder = new Uri.Builder();
2648 builder.scheme(scheme);
2649 Intent finalIntent = new Intent(intent);
2650 finalIntent.setData(builder.build());
2651 applyDefaultPreferredActivityLPw(service, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002652 scheme, null, null, null, userId);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002653 }
2654 doNonData = false;
2655 }
2656
2657 for (int idata=0; idata<tmpPa.countDataTypes(); idata++) {
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002658 String mimeType = tmpPa.getDataType(idata);
Christopher Tate2298ef22013-11-04 17:02:10 -08002659 if (hasSchemes) {
2660 Uri.Builder builder = new Uri.Builder();
2661 for (int ischeme=0; ischeme<tmpPa.countDataSchemes(); ischeme++) {
2662 String scheme = tmpPa.getDataScheme(ischeme);
2663 if (scheme != null && !scheme.isEmpty()) {
2664 Intent finalIntent = new Intent(intent);
2665 builder.scheme(scheme);
2666 finalIntent.setDataAndType(builder.build(), mimeType);
2667 applyDefaultPreferredActivityLPw(service, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002668 scheme, null, null, null, userId);
Christopher Tate2298ef22013-11-04 17:02:10 -08002669 }
2670 }
2671 } else {
2672 Intent finalIntent = new Intent(intent);
2673 finalIntent.setType(mimeType);
2674 applyDefaultPreferredActivityLPw(service, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002675 null, null, null, null, userId);
Christopher Tate2298ef22013-11-04 17:02:10 -08002676 }
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002677 doNonData = false;
2678 }
2679
2680 if (doNonData) {
2681 applyDefaultPreferredActivityLPw(service, intent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002682 null, null, null, null, userId);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002683 }
2684 }
2685
2686 private void applyDefaultPreferredActivityLPw(PackageManagerService service,
2687 Intent intent, int flags, ComponentName cn, String scheme, PatternMatcher ssp,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002688 IntentFilter.AuthorityEntry auth, PatternMatcher path, int userId) {
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002689 List<ResolveInfo> ri = service.mActivities.queryIntent(intent,
2690 intent.getType(), flags, 0);
2691 if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Queried " + intent
2692 + " results: " + ri);
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002693 int systemMatch = 0;
2694 int thirdPartyMatch = 0;
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002695 if (ri != null && ri.size() > 1) {
2696 boolean haveAct = false;
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002697 ComponentName haveNonSys = null;
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002698 ComponentName[] set = new ComponentName[ri.size()];
2699 for (int i=0; i<ri.size(); i++) {
2700 ActivityInfo ai = ri.get(i).activityInfo;
2701 set[i] = new ComponentName(ai.packageName, ai.name);
2702 if ((ai.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002703 if (ri.get(i).match >= thirdPartyMatch) {
2704 // Keep track of the best match we find of all third
2705 // party apps, for use later to determine if we actually
2706 // want to set a preferred app for this intent.
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002707 if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Result "
2708 + ai.packageName + "/" + ai.name + ": non-system!");
2709 haveNonSys = set[i];
2710 break;
2711 }
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002712 } else if (cn.getPackageName().equals(ai.packageName)
2713 && cn.getClassName().equals(ai.name)) {
2714 if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Result "
2715 + ai.packageName + "/" + ai.name + ": default!");
2716 haveAct = true;
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002717 systemMatch = ri.get(i).match;
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002718 } else {
2719 if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Result "
2720 + ai.packageName + "/" + ai.name + ": skipped");
2721 }
2722 }
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002723 if (haveNonSys != null && thirdPartyMatch < systemMatch) {
2724 // If we have a matching third party app, but its match is not as
2725 // good as the built-in system app, then we don't want to actually
2726 // consider it a match because presumably the built-in app is still
2727 // the thing we want users to see by default.
2728 haveNonSys = null;
2729 }
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002730 if (haveAct && haveNonSys == null) {
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002731 IntentFilter filter = new IntentFilter();
2732 if (intent.getAction() != null) {
2733 filter.addAction(intent.getAction());
2734 }
Erin Dahlgren707a59d2013-10-24 15:13:39 -07002735 if (intent.getCategories() != null) {
2736 for (String cat : intent.getCategories()) {
2737 filter.addCategory(cat);
2738 }
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002739 }
2740 if ((flags&PackageManager.MATCH_DEFAULT_ONLY) != 0) {
2741 filter.addCategory(Intent.CATEGORY_DEFAULT);
2742 }
2743 if (scheme != null) {
2744 filter.addDataScheme(scheme);
2745 }
2746 if (ssp != null) {
2747 filter.addDataSchemeSpecificPart(ssp.getPath(), ssp.getType());
2748 }
2749 if (auth != null) {
2750 filter.addDataAuthority(auth);
2751 }
2752 if (path != null) {
2753 filter.addDataPath(path);
2754 }
Erin Dahlgren707a59d2013-10-24 15:13:39 -07002755 if (intent.getType() != null) {
2756 try {
2757 filter.addDataType(intent.getType());
2758 } catch (IntentFilter.MalformedMimeTypeException ex) {
2759 Slog.w(TAG, "Malformed mimetype " + intent.getType() + " for " + cn);
2760 }
2761 }
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002762 PreferredActivity pa = new PreferredActivity(filter, systemMatch, set, cn, true);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002763 editPreferredActivitiesLPw(userId).addFilter(pa);
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002764 } else if (haveNonSys == null) {
2765 StringBuilder sb = new StringBuilder();
2766 sb.append("No component ");
2767 sb.append(cn.flattenToShortString());
2768 sb.append(" found setting preferred ");
2769 sb.append(intent);
2770 sb.append("; possible matches are ");
2771 for (int i=0; i<set.length; i++) {
2772 if (i > 0) sb.append(", ");
2773 sb.append(set[i].flattenToShortString());
2774 }
2775 Slog.w(TAG, sb.toString());
2776 } else {
2777 Slog.i(TAG, "Not setting preferred " + intent + "; found third party match "
2778 + haveNonSys.flattenToShortString());
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002779 }
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07002780 } else {
2781 Slog.w(TAG, "No potential matches found for " + intent + " while setting preferred "
2782 + cn.flattenToShortString());
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002783 }
2784 }
2785
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08002786 private void readDefaultPreferredActivitiesLPw(PackageManagerService service,
2787 XmlPullParser parser, int userId)
2788 throws XmlPullParserException, IOException {
2789 int outerDepth = parser.getDepth();
2790 int type;
2791 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2792 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2793 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2794 continue;
2795 }
2796
2797 String tagName = parser.getName();
2798 if (tagName.equals(TAG_ITEM)) {
2799 PreferredActivity tmpPa = new PreferredActivity(parser);
2800 if (tmpPa.mPref.getParseError() == null) {
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002801 applyDefaultPreferredActivityLPw(service, tmpPa, tmpPa.mPref.mComponent,
2802 userId);
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08002803 } else {
2804 PackageManagerService.reportSettingsProblem(Log.WARN,
2805 "Error in package manager settings: <preferred-activity> "
2806 + tmpPa.mPref.getParseError() + " at "
2807 + parser.getPositionDescription());
2808 }
2809 } else {
2810 PackageManagerService.reportSettingsProblem(Log.WARN,
2811 "Unknown element under <preferred-activities>: " + parser.getName());
2812 XmlUtils.skipCurrentTag(parser);
2813 }
2814 }
2815 }
2816
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002817 private int readInt(XmlPullParser parser, String ns, String name, int defValue) {
2818 String v = parser.getAttributeValue(ns, name);
2819 try {
2820 if (v == null) {
2821 return defValue;
2822 }
2823 return Integer.parseInt(v);
2824 } catch (NumberFormatException e) {
2825 PackageManagerService.reportSettingsProblem(Log.WARN,
2826 "Error in package manager settings: attribute " + name
2827 + " has bad integer value " + v + " at "
2828 + parser.getPositionDescription());
2829 }
2830 return defValue;
2831 }
2832
Jeff Sharkey9f837a92014-10-24 12:07:24 -07002833 private void readPermissionsLPw(ArrayMap<String, BasePermission> out, XmlPullParser parser)
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002834 throws IOException, XmlPullParserException {
2835 int outerDepth = parser.getDepth();
2836 int type;
2837 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2838 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2839 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2840 continue;
2841 }
2842
Kenny Root447106f2011-03-23 11:00:15 -07002843 final String tagName = parser.getName();
Amith Yamasani483f3b02012-03-13 16:08:00 -07002844 if (tagName.equals(TAG_ITEM)) {
2845 final String name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Root447106f2011-03-23 11:00:15 -07002846 final String sourcePackage = parser.getAttributeValue(null, "package");
2847 final String ptype = parser.getAttributeValue(null, "type");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002848 if (name != null && sourcePackage != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002849 final boolean dynamic = "dynamic".equals(ptype);
Svetoslavc6d1c342015-02-26 14:44:43 -08002850 final BasePermission bp = new BasePermission(name.intern(), sourcePackage,
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002851 dynamic ? BasePermission.TYPE_DYNAMIC : BasePermission.TYPE_NORMAL);
2852 bp.protectionLevel = readInt(parser, null, "protection",
2853 PermissionInfo.PROTECTION_NORMAL);
Dianne Hackborne639da72012-02-21 15:11:13 -08002854 bp.protectionLevel = PermissionInfo.fixProtectionLevel(bp.protectionLevel);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002855 if (dynamic) {
2856 PermissionInfo pi = new PermissionInfo();
2857 pi.packageName = sourcePackage.intern();
2858 pi.name = name.intern();
2859 pi.icon = readInt(parser, null, "icon", 0);
2860 pi.nonLocalizedLabel = parser.getAttributeValue(null, "label");
2861 pi.protectionLevel = bp.protectionLevel;
2862 bp.pendingInfo = pi;
2863 }
2864 out.put(bp.name, bp);
2865 } else {
2866 PackageManagerService.reportSettingsProblem(Log.WARN,
2867 "Error in package manager settings: permissions has" + " no name at "
2868 + parser.getPositionDescription());
2869 }
2870 } else {
2871 PackageManagerService.reportSettingsProblem(Log.WARN,
2872 "Unknown element reading permissions: " + parser.getName() + " at "
2873 + parser.getPositionDescription());
2874 }
2875 XmlUtils.skipCurrentTag(parser);
2876 }
2877 }
2878
Kenny Root447106f2011-03-23 11:00:15 -07002879 private void readDisabledSysPackageLPw(XmlPullParser parser) throws XmlPullParserException,
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002880 IOException {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002881 String name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002882 String realName = parser.getAttributeValue(null, "realName");
2883 String codePathStr = parser.getAttributeValue(null, "codePath");
2884 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Narayan Kamathff110bd2014-07-04 18:30:45 +01002885
2886 String legacyCpuAbiStr = parser.getAttributeValue(null, "requiredCpuAbi");
2887 String legacyNativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
2888
2889 String primaryCpuAbiStr = parser.getAttributeValue(null, "primaryCpuAbi");
2890 String secondaryCpuAbiStr = parser.getAttributeValue(null, "secondaryCpuAbi");
Narayan Kamath4903f642014-08-11 13:33:45 +01002891 String cpuAbiOverrideStr = parser.getAttributeValue(null, "cpuAbiOverride");
Narayan Kamathff110bd2014-07-04 18:30:45 +01002892
2893 if (primaryCpuAbiStr == null && legacyCpuAbiStr != null) {
2894 primaryCpuAbiStr = legacyCpuAbiStr;
2895 }
Narayan Kamath9e289d72014-04-10 09:26:59 +00002896
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002897 if (resourcePathStr == null) {
2898 resourcePathStr = codePathStr;
2899 }
2900 String version = parser.getAttributeValue(null, "version");
2901 int versionCode = 0;
2902 if (version != null) {
2903 try {
2904 versionCode = Integer.parseInt(version);
2905 } catch (NumberFormatException e) {
2906 }
2907 }
2908
2909 int pkgFlags = 0;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002910 int pkgPrivateFlags = 0;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002911 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Christopher Tate628946a2013-10-18 18:11:05 -07002912 final File codePathFile = new File(codePathStr);
2913 if (PackageManagerService.locationIsPrivileged(codePathFile)) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002914 pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
Christopher Tate628946a2013-10-18 18:11:05 -07002915 }
2916 PackageSetting ps = new PackageSetting(name, realName, codePathFile,
Narayan Kamathff110bd2014-07-04 18:30:45 +01002917 new File(resourcePathStr), legacyNativeLibraryPathStr, primaryCpuAbiStr,
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002918 secondaryCpuAbiStr, cpuAbiOverrideStr, versionCode, pkgFlags, pkgPrivateFlags);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002919 String timeStampStr = parser.getAttributeValue(null, "ft");
2920 if (timeStampStr != null) {
2921 try {
2922 long timeStamp = Long.parseLong(timeStampStr, 16);
2923 ps.setTimeStamp(timeStamp);
2924 } catch (NumberFormatException e) {
2925 }
2926 } else {
2927 timeStampStr = parser.getAttributeValue(null, "ts");
2928 if (timeStampStr != null) {
2929 try {
2930 long timeStamp = Long.parseLong(timeStampStr);
2931 ps.setTimeStamp(timeStamp);
2932 } catch (NumberFormatException e) {
2933 }
2934 }
2935 }
2936 timeStampStr = parser.getAttributeValue(null, "it");
2937 if (timeStampStr != null) {
2938 try {
2939 ps.firstInstallTime = Long.parseLong(timeStampStr, 16);
2940 } catch (NumberFormatException e) {
2941 }
2942 }
2943 timeStampStr = parser.getAttributeValue(null, "ut");
2944 if (timeStampStr != null) {
2945 try {
2946 ps.lastUpdateTime = Long.parseLong(timeStampStr, 16);
2947 } catch (NumberFormatException e) {
2948 }
2949 }
2950 String idStr = parser.getAttributeValue(null, "userId");
Amith Yamasani13593602012-03-22 16:16:17 -07002951 ps.appId = idStr != null ? Integer.parseInt(idStr) : 0;
2952 if (ps.appId <= 0) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002953 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
Amith Yamasani13593602012-03-22 16:16:17 -07002954 ps.appId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002955 }
Svetoslavc6d1c342015-02-26 14:44:43 -08002956
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002957 int outerDepth = parser.getDepth();
2958 int type;
2959 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2960 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2961 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2962 continue;
2963 }
2964
Svetoslavc6d1c342015-02-26 14:44:43 -08002965 if (parser.getName().equals(TAG_PERMISSIONS)) {
2966 readInstallPermissionsLPr(parser, ps.getPermissionsState());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002967 } else {
2968 PackageManagerService.reportSettingsProblem(Log.WARN,
2969 "Unknown element under <updated-package>: " + parser.getName());
2970 XmlUtils.skipCurrentTag(parser);
2971 }
2972 }
Christopher Tate628946a2013-10-18 18:11:05 -07002973
Svet Ganov12a692a2015-03-28 19:34:15 -07002974 // We keep track for which users we granted permissions to be able
2975 // to grant runtime permissions to system apps for newly appeared
2976 // users or newly appeared system apps. If we supported runtime
2977 // permissions during the previous boot, then we already granted
2978 // permissions for all device users. In such a case we set the users
2979 // for which we granted permissions to avoid clobbering of runtime
2980 // permissions we granted to system apps but the user revoked later.
2981 if (!isFirstRuntimePermissionsBoot()) {
2982 final int[] userIds = UserManagerService.getInstance().getUserIds();
2983 ps.setPermissionsUpdatedForUserIds(userIds);
2984 }
2985
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002986 mDisabledSysPackages.put(name, ps);
2987 }
2988
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002989 private static int PRE_M_APP_INFO_FLAG_HIDDEN = 1<<27;
2990 private static int PRE_M_APP_INFO_FLAG_CANT_SAVE_STATE = 1<<28;
2991 private static int PRE_M_APP_INFO_FLAG_FORWARD_LOCK = 1<<29;
2992 private static int PRE_M_APP_INFO_FLAG_PRIVILEGED = 1<<30;
2993
Kenny Root447106f2011-03-23 11:00:15 -07002994 private void readPackageLPw(XmlPullParser parser) throws XmlPullParserException, IOException {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002995 String name = null;
2996 String realName = null;
2997 String idStr = null;
2998 String sharedIdStr = null;
2999 String codePathStr = null;
3000 String resourcePathStr = null;
Narayan Kamathff110bd2014-07-04 18:30:45 +01003001 String legacyCpuAbiString = null;
3002 String legacyNativeLibraryPathStr = null;
3003 String primaryCpuAbiString = null;
3004 String secondaryCpuAbiString = null;
Narayan Kamath4903f642014-08-11 13:33:45 +01003005 String cpuAbiOverrideString = null;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003006 String systemStr = null;
3007 String installerPackageName = null;
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07003008 String volumeUuid = null;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003009 String uidError = null;
3010 int pkgFlags = 0;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003011 int pkgPrivateFlags = 0;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003012 long timeStamp = 0;
3013 long firstInstallTime = 0;
3014 long lastUpdateTime = 0;
3015 PackageSettingBase packageSetting = null;
3016 String version = null;
3017 int versionCode = 0;
3018 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003019 name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003020 realName = parser.getAttributeValue(null, "realName");
3021 idStr = parser.getAttributeValue(null, "userId");
3022 uidError = parser.getAttributeValue(null, "uidError");
3023 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
3024 codePathStr = parser.getAttributeValue(null, "codePath");
3025 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Narayan Kamath9e289d72014-04-10 09:26:59 +00003026
Narayan Kamathff110bd2014-07-04 18:30:45 +01003027 legacyCpuAbiString = parser.getAttributeValue(null, "requiredCpuAbi");
3028
3029 legacyNativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
3030 primaryCpuAbiString = parser.getAttributeValue(null, "primaryCpuAbi");
3031 secondaryCpuAbiString = parser.getAttributeValue(null, "secondaryCpuAbi");
Narayan Kamath4903f642014-08-11 13:33:45 +01003032 cpuAbiOverrideString = parser.getAttributeValue(null, "cpuAbiOverride");
Narayan Kamathff110bd2014-07-04 18:30:45 +01003033
3034 if (primaryCpuAbiString == null && legacyCpuAbiString != null) {
3035 primaryCpuAbiString = legacyCpuAbiString;
3036 }
Svetoslavc6d1c342015-02-26 14:44:43 -08003037
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003038 version = parser.getAttributeValue(null, "version");
3039 if (version != null) {
3040 try {
3041 versionCode = Integer.parseInt(version);
3042 } catch (NumberFormatException e) {
3043 }
3044 }
3045 installerPackageName = parser.getAttributeValue(null, "installer");
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07003046 volumeUuid = parser.getAttributeValue(null, "volumeUuid");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003047
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003048 systemStr = parser.getAttributeValue(null, "publicFlags");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003049 if (systemStr != null) {
3050 try {
3051 pkgFlags = Integer.parseInt(systemStr);
3052 } catch (NumberFormatException e) {
3053 }
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003054 systemStr = parser.getAttributeValue(null, "privateFlags");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003055 if (systemStr != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003056 try {
3057 pkgPrivateFlags = Integer.parseInt(systemStr);
3058 } catch (NumberFormatException e) {
3059 }
3060 }
3061 } else {
3062 // Pre-M -- both public and private flags were stored in one "flags" field.
3063 systemStr = parser.getAttributeValue(null, "flags");
3064 if (systemStr != null) {
3065 try {
3066 pkgFlags = Integer.parseInt(systemStr);
3067 } catch (NumberFormatException e) {
3068 }
3069 if ((pkgFlags & PRE_M_APP_INFO_FLAG_HIDDEN) != 0) {
3070 pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_HIDDEN;
3071 }
3072 if ((pkgFlags & PRE_M_APP_INFO_FLAG_CANT_SAVE_STATE) != 0) {
3073 pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE;
3074 }
3075 if ((pkgFlags & PRE_M_APP_INFO_FLAG_FORWARD_LOCK) != 0) {
3076 pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_FORWARD_LOCK;
3077 }
3078 if ((pkgFlags & PRE_M_APP_INFO_FLAG_PRIVILEGED) != 0) {
3079 pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
3080 }
3081 pkgFlags &= ~(PRE_M_APP_INFO_FLAG_HIDDEN
3082 | PRE_M_APP_INFO_FLAG_CANT_SAVE_STATE
3083 | PRE_M_APP_INFO_FLAG_FORWARD_LOCK
3084 | PRE_M_APP_INFO_FLAG_PRIVILEGED);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003085 } else {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003086 // For backward compatibility
3087 systemStr = parser.getAttributeValue(null, "system");
3088 if (systemStr != null) {
3089 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM
3090 : 0;
3091 } else {
3092 // Old settings that don't specify system... just treat
3093 // them as system, good enough.
3094 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
3095 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003096 }
3097 }
3098 String timeStampStr = parser.getAttributeValue(null, "ft");
3099 if (timeStampStr != null) {
3100 try {
3101 timeStamp = Long.parseLong(timeStampStr, 16);
3102 } catch (NumberFormatException e) {
3103 }
3104 } else {
3105 timeStampStr = parser.getAttributeValue(null, "ts");
3106 if (timeStampStr != null) {
3107 try {
3108 timeStamp = Long.parseLong(timeStampStr);
3109 } catch (NumberFormatException e) {
3110 }
3111 }
3112 }
3113 timeStampStr = parser.getAttributeValue(null, "it");
3114 if (timeStampStr != null) {
3115 try {
3116 firstInstallTime = Long.parseLong(timeStampStr, 16);
3117 } catch (NumberFormatException e) {
3118 }
3119 }
3120 timeStampStr = parser.getAttributeValue(null, "ut");
3121 if (timeStampStr != null) {
3122 try {
3123 lastUpdateTime = Long.parseLong(timeStampStr, 16);
3124 } catch (NumberFormatException e) {
3125 }
3126 }
3127 if (PackageManagerService.DEBUG_SETTINGS)
3128 Log.v(PackageManagerService.TAG, "Reading package: " + name + " userId=" + idStr
3129 + " sharedUserId=" + sharedIdStr);
3130 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
3131 if (resourcePathStr == null) {
3132 resourcePathStr = codePathStr;
3133 }
3134 if (realName != null) {
3135 realName = realName.intern();
3136 }
3137 if (name == null) {
3138 PackageManagerService.reportSettingsProblem(Log.WARN,
3139 "Error in package manager settings: <package> has no name at "
3140 + parser.getPositionDescription());
3141 } else if (codePathStr == null) {
3142 PackageManagerService.reportSettingsProblem(Log.WARN,
3143 "Error in package manager settings: <package> has no codePath at "
3144 + parser.getPositionDescription());
3145 } else if (userId > 0) {
Kenny Root447106f2011-03-23 11:00:15 -07003146 packageSetting = addPackageLPw(name.intern(), realName, new File(codePathStr),
Narayan Kamathff110bd2014-07-04 18:30:45 +01003147 new File(resourcePathStr), legacyNativeLibraryPathStr, primaryCpuAbiString,
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003148 secondaryCpuAbiString, cpuAbiOverrideString, userId, versionCode, pkgFlags,
3149 pkgPrivateFlags);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003150 if (PackageManagerService.DEBUG_SETTINGS)
3151 Log.i(PackageManagerService.TAG, "Reading package " + name + ": userId="
3152 + userId + " pkg=" + packageSetting);
3153 if (packageSetting == null) {
3154 PackageManagerService.reportSettingsProblem(Log.ERROR, "Failure adding uid "
3155 + userId + " while parsing settings at "
3156 + parser.getPositionDescription());
3157 } else {
3158 packageSetting.setTimeStamp(timeStamp);
3159 packageSetting.firstInstallTime = firstInstallTime;
3160 packageSetting.lastUpdateTime = lastUpdateTime;
3161 }
3162 } else if (sharedIdStr != null) {
3163 userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
3164 if (userId > 0) {
3165 packageSetting = new PendingPackage(name.intern(), realName, new File(
Narayan Kamathff110bd2014-07-04 18:30:45 +01003166 codePathStr), new File(resourcePathStr), legacyNativeLibraryPathStr,
Narayan Kamath4903f642014-08-11 13:33:45 +01003167 primaryCpuAbiString, secondaryCpuAbiString, cpuAbiOverrideString,
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003168 userId, versionCode, pkgFlags, pkgPrivateFlags);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003169 packageSetting.setTimeStamp(timeStamp);
3170 packageSetting.firstInstallTime = firstInstallTime;
3171 packageSetting.lastUpdateTime = lastUpdateTime;
3172 mPendingPackages.add((PendingPackage) packageSetting);
3173 if (PackageManagerService.DEBUG_SETTINGS)
3174 Log.i(PackageManagerService.TAG, "Reading package " + name
3175 + ": sharedUserId=" + userId + " pkg=" + packageSetting);
3176 } else {
3177 PackageManagerService.reportSettingsProblem(Log.WARN,
3178 "Error in package manager settings: package " + name
3179 + " has bad sharedId " + sharedIdStr + " at "
3180 + parser.getPositionDescription());
3181 }
3182 } else {
3183 PackageManagerService.reportSettingsProblem(Log.WARN,
3184 "Error in package manager settings: package " + name + " has bad userId "
3185 + idStr + " at " + parser.getPositionDescription());
3186 }
3187 } catch (NumberFormatException e) {
3188 PackageManagerService.reportSettingsProblem(Log.WARN,
3189 "Error in package manager settings: package " + name + " has bad userId "
3190 + idStr + " at " + parser.getPositionDescription());
3191 }
3192 if (packageSetting != null) {
3193 packageSetting.uidError = "true".equals(uidError);
3194 packageSetting.installerPackageName = installerPackageName;
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07003195 packageSetting.volumeUuid = volumeUuid;
Narayan Kamathff110bd2014-07-04 18:30:45 +01003196 packageSetting.legacyNativeLibraryPathString = legacyNativeLibraryPathStr;
3197 packageSetting.primaryCpuAbiString = primaryCpuAbiString;
3198 packageSetting.secondaryCpuAbiString = secondaryCpuAbiString;
Amith Yamasani483f3b02012-03-13 16:08:00 -07003199 // Handle legacy string here for single-user mode
3200 final String enabledStr = parser.getAttributeValue(null, ATTR_ENABLED);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003201 if (enabledStr != null) {
Dianne Hackbornb8f40002011-07-19 15:17:43 -07003202 try {
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07003203 packageSetting.setEnabled(Integer.parseInt(enabledStr), 0 /* userId */, null);
Dianne Hackbornb8f40002011-07-19 15:17:43 -07003204 } catch (NumberFormatException e) {
3205 if (enabledStr.equalsIgnoreCase("true")) {
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07003206 packageSetting.setEnabled(COMPONENT_ENABLED_STATE_ENABLED, 0, null);
Dianne Hackbornb8f40002011-07-19 15:17:43 -07003207 } else if (enabledStr.equalsIgnoreCase("false")) {
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07003208 packageSetting.setEnabled(COMPONENT_ENABLED_STATE_DISABLED, 0, null);
Dianne Hackbornb8f40002011-07-19 15:17:43 -07003209 } else if (enabledStr.equalsIgnoreCase("default")) {
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07003210 packageSetting.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 0, null);
Dianne Hackbornb8f40002011-07-19 15:17:43 -07003211 } else {
3212 PackageManagerService.reportSettingsProblem(Log.WARN,
3213 "Error in package manager settings: package " + name
3214 + " has bad enabled value: " + idStr + " at "
3215 + parser.getPositionDescription());
3216 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003217 }
3218 } else {
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07003219 packageSetting.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 0, null);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003220 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003221
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003222 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
3223 if (installStatusStr != null) {
3224 if (installStatusStr.equalsIgnoreCase("false")) {
3225 packageSetting.installStatus = PackageSettingBase.PKG_INSTALL_INCOMPLETE;
3226 } else {
3227 packageSetting.installStatus = PackageSettingBase.PKG_INSTALL_COMPLETE;
3228 }
3229 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003230 int outerDepth = parser.getDepth();
3231 int type;
3232 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3233 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3234 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3235 continue;
3236 }
3237
3238 String tagName = parser.getName();
Amith Yamasani483f3b02012-03-13 16:08:00 -07003239 // Legacy
3240 if (tagName.equals(TAG_DISABLED_COMPONENTS)) {
3241 readDisabledComponentsLPw(packageSetting, parser, 0);
3242 } else if (tagName.equals(TAG_ENABLED_COMPONENTS)) {
3243 readEnabledComponentsLPw(packageSetting, parser, 0);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003244 } else if (tagName.equals("sigs")) {
3245 packageSetting.signatures.readXml(parser, mPastSignatures);
Svetoslavc6d1c342015-02-26 14:44:43 -08003246 } else if (tagName.equals(TAG_PERMISSIONS)) {
3247 readInstallPermissionsLPr(parser,
3248 packageSetting.getPermissionsState());
Svetoslavcf959f62015-03-26 20:53:34 -07003249 packageSetting.installPermissionsFixed = true;
dcashman3a0dbfb2014-07-07 13:53:36 -07003250 } else if (tagName.equals("proper-signing-keyset")) {
3251 long id = Long.parseLong(parser.getAttributeValue(null, "identifier"));
dcashman8c04fac2015-03-23 11:39:42 -07003252 Integer refCt = mKeySetRefs.get(id);
3253 if (refCt != null) {
3254 mKeySetRefs.put(id, refCt + 1);
3255 } else {
3256 mKeySetRefs.put(id, 1);
3257 }
dcashman3a0dbfb2014-07-07 13:53:36 -07003258 packageSetting.keySetData.setProperSigningKeySet(id);
Geremy Condraf1bcca82013-01-07 22:35:24 -08003259 } else if (tagName.equals("signing-keyset")) {
dcashman8c04fac2015-03-23 11:39:42 -07003260 // from v1 of keysetmanagerservice - no longer used
dcashman55b10782014-04-09 14:20:38 -07003261 } else if (tagName.equals("upgrade-keyset")) {
3262 long id = Long.parseLong(parser.getAttributeValue(null, "identifier"));
3263 packageSetting.keySetData.addUpgradeKeySetById(id);
Geremy Condraf1bcca82013-01-07 22:35:24 -08003264 } else if (tagName.equals("defined-keyset")) {
3265 long id = Long.parseLong(parser.getAttributeValue(null, "identifier"));
3266 String alias = parser.getAttributeValue(null, "alias");
dcashman8c04fac2015-03-23 11:39:42 -07003267 Integer refCt = mKeySetRefs.get(id);
3268 if (refCt != null) {
3269 mKeySetRefs.put(id, refCt + 1);
3270 } else {
3271 mKeySetRefs.put(id, 1);
3272 }
Geremy Condraf1bcca82013-01-07 22:35:24 -08003273 packageSetting.keySetData.addDefinedKeySet(id, alias);
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08003274 } else if (tagName.equals(TAG_DOMAIN_VERIFICATION)) {
3275 readDomainVerificationLPw(parser, packageSetting);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003276 } else {
3277 PackageManagerService.reportSettingsProblem(Log.WARN,
3278 "Unknown element under <package>: " + parser.getName());
3279 XmlUtils.skipCurrentTag(parser);
3280 }
3281 }
Svet Ganov12a692a2015-03-28 19:34:15 -07003282
3283 // We keep track for which users we granted permissions to be able
3284 // to grant runtime permissions to system apps for newly appeared
3285 // users or newly appeared system apps. If we supported runtime
3286 // permissions during the previous boot, then we already granted
3287 // permissions for all device users. In such a case we set the users
3288 // for which we granted permissions to avoid clobbering of runtime
3289 // permissions we granted to system apps but the user revoked later.
3290 if (!isFirstRuntimePermissionsBoot()) {
3291 final int[] userIds = UserManagerService.getInstance().getUserIds();
3292 packageSetting.setPermissionsUpdatedForUserIds(userIds);
3293 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003294 } else {
3295 XmlUtils.skipCurrentTag(parser);
3296 }
3297 }
3298
Amith Yamasani483f3b02012-03-13 16:08:00 -07003299 private void readDisabledComponentsLPw(PackageSettingBase packageSetting, XmlPullParser parser,
3300 int userId) throws IOException, XmlPullParserException {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003301 int outerDepth = parser.getDepth();
3302 int type;
3303 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3304 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3305 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3306 continue;
3307 }
3308
3309 String tagName = parser.getName();
Amith Yamasani483f3b02012-03-13 16:08:00 -07003310 if (tagName.equals(TAG_ITEM)) {
3311 String name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003312 if (name != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003313 packageSetting.addDisabledComponent(name.intern(), userId);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003314 } else {
3315 PackageManagerService.reportSettingsProblem(Log.WARN,
3316 "Error in package manager settings: <disabled-components> has"
3317 + " no name at " + parser.getPositionDescription());
3318 }
3319 } else {
3320 PackageManagerService.reportSettingsProblem(Log.WARN,
3321 "Unknown element under <disabled-components>: " + parser.getName());
3322 }
3323 XmlUtils.skipCurrentTag(parser);
3324 }
3325 }
3326
Amith Yamasani483f3b02012-03-13 16:08:00 -07003327 private void readEnabledComponentsLPw(PackageSettingBase packageSetting, XmlPullParser parser,
3328 int userId) throws IOException, XmlPullParserException {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003329 int outerDepth = parser.getDepth();
3330 int type;
3331 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3332 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3333 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3334 continue;
3335 }
3336
3337 String tagName = parser.getName();
Amith Yamasani483f3b02012-03-13 16:08:00 -07003338 if (tagName.equals(TAG_ITEM)) {
3339 String name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003340 if (name != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003341 packageSetting.addEnabledComponent(name.intern(), userId);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003342 } else {
3343 PackageManagerService.reportSettingsProblem(Log.WARN,
3344 "Error in package manager settings: <enabled-components> has"
3345 + " no name at " + parser.getPositionDescription());
3346 }
3347 } else {
3348 PackageManagerService.reportSettingsProblem(Log.WARN,
3349 "Unknown element under <enabled-components>: " + parser.getName());
3350 }
3351 XmlUtils.skipCurrentTag(parser);
3352 }
3353 }
3354
Amith Yamasani483f3b02012-03-13 16:08:00 -07003355 private void readSharedUserLPw(XmlPullParser parser) throws XmlPullParserException,IOException {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003356 String name = null;
3357 String idStr = null;
3358 int pkgFlags = 0;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003359 int pkgPrivateFlags = 0;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003360 SharedUserSetting su = null;
3361 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003362 name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003363 idStr = parser.getAttributeValue(null, "userId");
3364 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
3365 if ("true".equals(parser.getAttributeValue(null, "system"))) {
3366 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
3367 }
3368 if (name == null) {
3369 PackageManagerService.reportSettingsProblem(Log.WARN,
3370 "Error in package manager settings: <shared-user> has no name at "
3371 + parser.getPositionDescription());
3372 } else if (userId == 0) {
3373 PackageManagerService.reportSettingsProblem(Log.WARN,
3374 "Error in package manager settings: shared-user " + name
3375 + " has bad userId " + idStr + " at "
3376 + parser.getPositionDescription());
3377 } else {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003378 if ((su = addSharedUserLPw(name.intern(), userId, pkgFlags, pkgPrivateFlags))
3379 == null) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003380 PackageManagerService
3381 .reportSettingsProblem(Log.ERROR, "Occurred while parsing settings at "
3382 + parser.getPositionDescription());
3383 }
3384 }
3385 } catch (NumberFormatException e) {
3386 PackageManagerService.reportSettingsProblem(Log.WARN,
3387 "Error in package manager settings: package " + name + " has bad userId "
3388 + idStr + " at " + parser.getPositionDescription());
3389 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003390
3391 if (su != null) {
3392 int outerDepth = parser.getDepth();
3393 int type;
3394 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3395 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3396 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3397 continue;
3398 }
3399
3400 String tagName = parser.getName();
3401 if (tagName.equals("sigs")) {
3402 su.signatures.readXml(parser, mPastSignatures);
3403 } else if (tagName.equals("perms")) {
Svetoslavc6d1c342015-02-26 14:44:43 -08003404 readInstallPermissionsLPr(parser, su.getPermissionsState());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003405 } else {
3406 PackageManagerService.reportSettingsProblem(Log.WARN,
3407 "Unknown element under <shared-user>: " + parser.getName());
3408 XmlUtils.skipCurrentTag(parser);
3409 }
3410 }
Svet Ganov12a692a2015-03-28 19:34:15 -07003411
3412 // We keep track for which users we granted permissions to be able
3413 // to grant runtime permissions to system apps for newly appeared
3414 // users or newly appeared system apps. If we supported runtime
3415 // permissions during the previous boot, then we already granted
3416 // permissions for all device users. In such a case we set the users
3417 // for which we granted permissions to avoid clobbering of runtime
3418 // permissions we granted to system apps but the user revoked later.
3419 if (!isFirstRuntimePermissionsBoot()) {
3420 final int[] userIds = UserManagerService.getInstance().getUserIds();
3421 su.setPermissionsUpdatedForUserIds(userIds);
3422 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003423 } else {
3424 XmlUtils.skipCurrentTag(parser);
3425 }
3426 }
3427
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08003428 void createNewUserLILPw(PackageManagerService service, Installer installer,
3429 int userHandle, File path) {
Dianne Hackborn63092712012-10-07 14:45:35 -07003430 path.mkdir();
3431 FileUtils.setPermissions(path.toString(), FileUtils.S_IRWXU | FileUtils.S_IRWXG
3432 | FileUtils.S_IXOTH, -1, -1);
3433 for (PackageSetting ps : mPackages.values()) {
Amith Yamasani41cd5772014-07-10 15:26:00 -07003434 if (ps.pkg == null || ps.pkg.applicationInfo == null) {
3435 continue;
3436 }
Dianne Hackborn63092712012-10-07 14:45:35 -07003437 // Only system apps are initially installed.
3438 ps.setInstalled((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0, userHandle);
3439 // Need to create a data directory for all apps under this user.
3440 installer.createUserData(ps.name,
Robert Craig8643dc62013-07-29 09:06:51 -04003441 UserHandle.getUid(userHandle, ps.appId), userHandle,
3442 ps.pkg.applicationInfo.seinfo);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003443 }
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08003444 readDefaultPreferredAppsLPw(service, userHandle);
Dianne Hackborn63092712012-10-07 14:45:35 -07003445 writePackageRestrictionsLPr(userHandle);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003446 }
3447
Alexandra Gherghina539a7ef2014-07-07 12:27:54 +01003448 void removeUserLPw(int userId) {
Dianne Hackborn63092712012-10-07 14:45:35 -07003449 Set<Entry<String, PackageSetting>> entries = mPackages.entrySet();
3450 for (Entry<String, PackageSetting> entry : entries) {
3451 entry.getValue().removeUser(userId);
3452 }
3453 mPreferredActivities.remove(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07003454 File file = getUserPackagesStateFile(userId);
3455 file.delete();
3456 file = getUserPackagesStateBackupFile(userId);
3457 file.delete();
Nicolas Prevote7024042014-07-08 15:47:17 +01003458 removeCrossProfileIntentFiltersLPw(userId);
Svetoslavc6d1c342015-02-26 14:44:43 -08003459
3460 mRuntimePermissionsPersistence.onUserRemoved(userId);
Nicolas Prevota0f48852014-05-27 11:21:11 +01003461 }
3462
Nicolas Prevote7024042014-07-08 15:47:17 +01003463 void removeCrossProfileIntentFiltersLPw(int userId) {
3464 synchronized (mCrossProfileIntentResolvers) {
3465 // userId is the source user
3466 if (mCrossProfileIntentResolvers.get(userId) != null) {
3467 mCrossProfileIntentResolvers.remove(userId);
3468 writePackageRestrictionsLPr(userId);
Nicolas Prevota0f48852014-05-27 11:21:11 +01003469 }
Nicolas Prevote7024042014-07-08 15:47:17 +01003470 // userId is the target user
3471 int count = mCrossProfileIntentResolvers.size();
3472 for (int i = 0; i < count; i++) {
3473 int sourceUserId = mCrossProfileIntentResolvers.keyAt(i);
3474 CrossProfileIntentResolver cpir = mCrossProfileIntentResolvers.get(sourceUserId);
3475 boolean needsWriting = false;
Jeff Sharkey9f837a92014-10-24 12:07:24 -07003476 ArraySet<CrossProfileIntentFilter> cpifs =
3477 new ArraySet<CrossProfileIntentFilter>(cpir.filterSet());
Nicolas Prevote7024042014-07-08 15:47:17 +01003478 for (CrossProfileIntentFilter cpif : cpifs) {
3479 if (cpif.getTargetUserId() == userId) {
3480 needsWriting = true;
3481 cpir.removeFilter(cpif);
3482 }
3483 }
3484 if (needsWriting) {
3485 writePackageRestrictionsLPr(sourceUserId);
3486 }
Nicolas Prevota0f48852014-05-27 11:21:11 +01003487 }
3488 }
Amith Yamasani13593602012-03-22 16:16:17 -07003489 }
3490
Geremy Condra12c18382013-03-06 16:49:06 -08003491 // This should be called (at least) whenever an application is removed
3492 private void setFirstAvailableUid(int uid) {
3493 if (uid > mFirstAvailableUid) {
3494 mFirstAvailableUid = uid;
3495 }
3496 }
3497
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003498 // Returns -1 if we could not find an available UserId to assign
Kenny Root447106f2011-03-23 11:00:15 -07003499 private int newUserIdLPw(Object obj) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003500 // Let's be stupidly inefficient for now...
3501 final int N = mUserIds.size();
Geremy Condra12c18382013-03-06 16:49:06 -08003502 for (int i = mFirstAvailableUid; i < N; i++) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003503 if (mUserIds.get(i) == null) {
3504 mUserIds.set(i, obj);
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003505 return Process.FIRST_APPLICATION_UID + i;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003506 }
3507 }
3508
3509 // None left?
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003510 if (N > (Process.LAST_APPLICATION_UID-Process.FIRST_APPLICATION_UID)) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003511 return -1;
3512 }
3513
3514 mUserIds.add(obj);
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003515 return Process.FIRST_APPLICATION_UID + N;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003516 }
3517
Kenny Root0aaa0d92011-09-12 16:42:55 -07003518 public VerifierDeviceIdentity getVerifierDeviceIdentityLPw() {
3519 if (mVerifierDeviceIdentity == null) {
3520 mVerifierDeviceIdentity = VerifierDeviceIdentity.generate();
3521
3522 writeLPr();
3523 }
3524
3525 return mVerifierDeviceIdentity;
3526 }
3527
Kenny Root447106f2011-03-23 11:00:15 -07003528 public PackageSetting getDisabledSystemPkgLPr(String name) {
3529 PackageSetting ps = mDisabledSysPackages.get(name);
3530 return ps;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003531 }
3532
Jeff Sharkey9f837a92014-10-24 12:07:24 -07003533 private String compToString(ArraySet<String> cmp) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003534 return cmp != null ? Arrays.toString(cmp.toArray()) : "[]";
3535 }
3536
Amith Yamasani483f3b02012-03-13 16:08:00 -07003537 boolean isEnabledLPr(ComponentInfo componentInfo, int flags, int userId) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003538 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
3539 return true;
3540 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003541 final String pkgName = componentInfo.packageName;
3542 final PackageSetting packageSettings = mPackages.get(pkgName);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003543 if (PackageManagerService.DEBUG_SETTINGS) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003544 Log.v(PackageManagerService.TAG, "isEnabledLock - packageName = "
3545 + componentInfo.packageName + " componentName = " + componentInfo.name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003546 Log.v(PackageManagerService.TAG, "enabledComponents: "
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003547 + compToString(packageSettings.getEnabledComponents(userId)));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003548 Log.v(PackageManagerService.TAG, "disabledComponents: "
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003549 + compToString(packageSettings.getDisabledComponents(userId)));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003550 }
3551 if (packageSettings == null) {
3552 return false;
3553 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003554 PackageUserState ustate = packageSettings.readUserState(userId);
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08003555 if ((flags&PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS) != 0) {
3556 if (ustate.enabled == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
3557 return true;
3558 }
3559 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003560 if (ustate.enabled == COMPONENT_ENABLED_STATE_DISABLED
3561 || ustate.enabled == COMPONENT_ENABLED_STATE_DISABLED_USER
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08003562 || ustate.enabled == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003563 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003564 && ustate.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003565 return false;
3566 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003567 if (ustate.enabledComponents != null
3568 && ustate.enabledComponents.contains(componentInfo.name)) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003569 return true;
3570 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003571 if (ustate.disabledComponents != null
3572 && ustate.disabledComponents.contains(componentInfo.name)) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003573 return false;
3574 }
3575 return componentInfo.enabled;
3576 }
Kenny Root447106f2011-03-23 11:00:15 -07003577
3578 String getInstallerPackageNameLPr(String packageName) {
3579 final PackageSetting pkg = mPackages.get(packageName);
3580 if (pkg == null) {
3581 throw new IllegalArgumentException("Unknown package: " + packageName);
3582 }
3583 return pkg.installerPackageName;
3584 }
3585
Amith Yamasani483f3b02012-03-13 16:08:00 -07003586 int getApplicationEnabledSettingLPr(String packageName, int userId) {
Kenny Root447106f2011-03-23 11:00:15 -07003587 final PackageSetting pkg = mPackages.get(packageName);
3588 if (pkg == null) {
3589 throw new IllegalArgumentException("Unknown package: " + packageName);
3590 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003591 return pkg.getEnabled(userId);
Kenny Root447106f2011-03-23 11:00:15 -07003592 }
3593
Amith Yamasani483f3b02012-03-13 16:08:00 -07003594 int getComponentEnabledSettingLPr(ComponentName componentName, int userId) {
Kenny Root447106f2011-03-23 11:00:15 -07003595 final String packageName = componentName.getPackageName();
3596 final PackageSetting pkg = mPackages.get(packageName);
3597 if (pkg == null) {
3598 throw new IllegalArgumentException("Unknown component: " + componentName);
3599 }
3600 final String classNameStr = componentName.getClassName();
Amith Yamasani483f3b02012-03-13 16:08:00 -07003601 return pkg.getCurrentEnabledStateLPr(classNameStr, userId);
Kenny Root447106f2011-03-23 11:00:15 -07003602 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003603
Kenny Root447106f2011-03-23 11:00:15 -07003604 boolean setPackageStoppedStateLPw(String packageName, boolean stopped,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003605 boolean allowedByPermission, int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003606 int appId = UserHandle.getAppId(uid);
Kenny Root447106f2011-03-23 11:00:15 -07003607 final PackageSetting pkgSetting = mPackages.get(packageName);
3608 if (pkgSetting == null) {
3609 throw new IllegalArgumentException("Unknown package: " + packageName);
3610 }
Amith Yamasani13593602012-03-22 16:16:17 -07003611 if (!allowedByPermission && (appId != pkgSetting.appId)) {
Kenny Root447106f2011-03-23 11:00:15 -07003612 throw new SecurityException(
3613 "Permission Denial: attempt to change stopped state from pid="
3614 + Binder.getCallingPid()
Amith Yamasani13593602012-03-22 16:16:17 -07003615 + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
Kenny Root447106f2011-03-23 11:00:15 -07003616 }
3617 if (DEBUG_STOPPED) {
3618 if (stopped) {
3619 RuntimeException e = new RuntimeException("here");
3620 e.fillInStackTrace();
3621 Slog.i(TAG, "Stopping package " + packageName, e);
3622 }
3623 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003624 if (pkgSetting.getStopped(userId) != stopped) {
3625 pkgSetting.setStopped(stopped, userId);
3626 // pkgSetting.pkg.mSetStopped = stopped;
3627 if (pkgSetting.getNotLaunched(userId)) {
Kenny Root447106f2011-03-23 11:00:15 -07003628 if (pkgSetting.installerPackageName != null) {
3629 PackageManagerService.sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH,
3630 pkgSetting.name, null,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003631 pkgSetting.installerPackageName, null, new int[] {userId});
Kenny Root447106f2011-03-23 11:00:15 -07003632 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003633 pkgSetting.setNotLaunched(false, userId);
Kenny Root447106f2011-03-23 11:00:15 -07003634 }
3635 return true;
3636 }
3637 return false;
3638 }
3639
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08003640 List<UserInfo> getAllUsers() {
Amith Yamasani7ea3e7d2012-04-20 15:19:35 -07003641 long id = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07003642 try {
Amith Yamasani920ace02012-09-20 22:15:37 -07003643 return UserManagerService.getInstance().getUsers(false);
Amith Yamasani483f3b02012-03-13 16:08:00 -07003644 } catch (NullPointerException npe) {
3645 // packagemanager not yet initialized
Amith Yamasani7ea3e7d2012-04-20 15:19:35 -07003646 } finally {
3647 Binder.restoreCallingIdentity(id);
Amith Yamasani483f3b02012-03-13 16:08:00 -07003648 }
3649 return null;
3650 }
3651
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07003652 /**
3653 * Return all {@link PackageSetting} that are actively installed on the
3654 * given {@link VolumeInfo#fsUuid}.
3655 */
3656 List<PackageSetting> getVolumePackagesLPr(String volumeUuid) {
3657 Preconditions.checkNotNull(volumeUuid);
3658 ArrayList<PackageSetting> res = new ArrayList<>();
3659 for (int i = 0; i < mPackages.size(); i++) {
3660 final PackageSetting setting = mPackages.valueAt(i);
3661 if (Objects.equals(volumeUuid, setting.volumeUuid)) {
3662 res.add(setting);
3663 }
3664 }
3665 return res;
3666 }
3667
Svetoslavc6d1c342015-02-26 14:44:43 -08003668 static void printFlags(PrintWriter pw, int val, Object[] spec) {
Joe Onorato20963df2012-01-04 18:13:24 -08003669 pw.print("[ ");
3670 for (int i=0; i<spec.length; i+=2) {
3671 int mask = (Integer)spec[i];
3672 if ((val & mask) != 0) {
3673 pw.print(spec[i+1]);
3674 pw.print(" ");
3675 }
3676 }
3677 pw.print("]");
3678 }
3679
3680 static final Object[] FLAG_DUMP_SPEC = new Object[] {
3681 ApplicationInfo.FLAG_SYSTEM, "SYSTEM",
3682 ApplicationInfo.FLAG_DEBUGGABLE, "DEBUGGABLE",
3683 ApplicationInfo.FLAG_HAS_CODE, "HAS_CODE",
3684 ApplicationInfo.FLAG_PERSISTENT, "PERSISTENT",
3685 ApplicationInfo.FLAG_FACTORY_TEST, "FACTORY_TEST",
3686 ApplicationInfo.FLAG_ALLOW_TASK_REPARENTING, "ALLOW_TASK_REPARENTING",
3687 ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA, "ALLOW_CLEAR_USER_DATA",
3688 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, "UPDATED_SYSTEM_APP",
3689 ApplicationInfo.FLAG_TEST_ONLY, "TEST_ONLY",
3690 ApplicationInfo.FLAG_VM_SAFE_MODE, "VM_SAFE_MODE",
3691 ApplicationInfo.FLAG_ALLOW_BACKUP, "ALLOW_BACKUP",
3692 ApplicationInfo.FLAG_KILL_AFTER_RESTORE, "KILL_AFTER_RESTORE",
3693 ApplicationInfo.FLAG_RESTORE_ANY_VERSION, "RESTORE_ANY_VERSION",
3694 ApplicationInfo.FLAG_EXTERNAL_STORAGE, "EXTERNAL_STORAGE",
3695 ApplicationInfo.FLAG_LARGE_HEAP, "LARGE_HEAP",
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003696 };
3697
3698 static final Object[] PRIVATE_FLAG_DUMP_SPEC = new Object[] {
3699 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED, "PRIVILEGED",
3700 ApplicationInfo.PRIVATE_FLAG_FORWARD_LOCK, "FORWARD_LOCK",
3701 ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE, "CANT_SAVE_STATE",
Joe Onorato20963df2012-01-04 18:13:24 -08003702 };
3703
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08003704 void dumpPackageLPr(PrintWriter pw, String prefix, String checkinTag, PackageSetting ps,
3705 SimpleDateFormat sdf, Date date, List<UserInfo> users) {
3706 if (checkinTag != null) {
3707 pw.print(checkinTag);
3708 pw.print(",");
3709 pw.print(ps.realName != null ? ps.realName : ps.name);
3710 pw.print(",");
3711 pw.print(ps.appId);
3712 pw.print(",");
3713 pw.print(ps.versionCode);
3714 pw.print(",");
3715 pw.print(ps.firstInstallTime);
3716 pw.print(",");
3717 pw.print(ps.lastUpdateTime);
3718 pw.print(",");
3719 pw.print(ps.installerPackageName != null ? ps.installerPackageName : "?");
3720 pw.println();
Jeff Sharkeyc4d05fc2014-12-01 16:24:01 -08003721 if (ps.pkg != null) {
3722 pw.print(checkinTag); pw.print("-"); pw.print("splt,");
3723 pw.print("base,");
3724 pw.println(ps.pkg.baseRevisionCode);
3725 if (ps.pkg.splitNames != null) {
3726 for (int i = 0; i < ps.pkg.splitNames.length; i++) {
3727 pw.print(checkinTag); pw.print("-"); pw.print("splt,");
3728 pw.print(ps.pkg.splitNames[i]); pw.print(",");
3729 pw.println(ps.pkg.splitRevisionCodes[i]);
3730 }
3731 }
3732 }
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08003733 for (UserInfo user : users) {
3734 pw.print(checkinTag);
3735 pw.print("-");
3736 pw.print("usr");
3737 pw.print(",");
3738 pw.print(user.id);
3739 pw.print(",");
3740 pw.print(ps.getInstalled(user.id) ? "I" : "i");
Amith Yamasanie5bcff62014-07-19 15:44:09 -07003741 pw.print(ps.getHidden(user.id) ? "B" : "b");
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08003742 pw.print(ps.getStopped(user.id) ? "S" : "s");
3743 pw.print(ps.getNotLaunched(user.id) ? "l" : "L");
3744 pw.print(",");
3745 pw.print(ps.getEnabled(user.id));
3746 String lastDisabledAppCaller = ps.getLastDisabledAppCaller(user.id);
3747 pw.print(",");
3748 pw.print(lastDisabledAppCaller != null ? lastDisabledAppCaller : "?");
3749 pw.println();
3750 }
3751 return;
3752 }
3753
Dianne Hackbornc895be72013-03-11 17:48:43 -07003754 pw.print(prefix); pw.print("Package [");
3755 pw.print(ps.realName != null ? ps.realName : ps.name);
3756 pw.print("] (");
3757 pw.print(Integer.toHexString(System.identityHashCode(ps)));
3758 pw.println("):");
3759
3760 if (ps.realName != null) {
3761 pw.print(prefix); pw.print(" compat name=");
3762 pw.println(ps.name);
3763 }
3764
Svetoslavc6d1c342015-02-26 14:44:43 -08003765 pw.print(prefix); pw.print(" userId="); pw.println(ps.appId);
3766
Dianne Hackbornc895be72013-03-11 17:48:43 -07003767 if (ps.sharedUser != null) {
3768 pw.print(prefix); pw.print(" sharedUser="); pw.println(ps.sharedUser);
3769 }
3770 pw.print(prefix); pw.print(" pkg="); pw.println(ps.pkg);
3771 pw.print(prefix); pw.print(" codePath="); pw.println(ps.codePathString);
3772 pw.print(prefix); pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Narayan Kamathff110bd2014-07-04 18:30:45 +01003773 pw.print(prefix); pw.print(" legacyNativeLibraryDir="); pw.println(ps.legacyNativeLibraryPathString);
3774 pw.print(prefix); pw.print(" primaryCpuAbi="); pw.println(ps.primaryCpuAbiString);
3775 pw.print(prefix); pw.print(" secondaryCpuAbi="); pw.println(ps.secondaryCpuAbiString);
Dianne Hackbornc895be72013-03-11 17:48:43 -07003776 pw.print(prefix); pw.print(" versionCode="); pw.print(ps.versionCode);
3777 if (ps.pkg != null) {
3778 pw.print(" targetSdk="); pw.print(ps.pkg.applicationInfo.targetSdkVersion);
3779 }
3780 pw.println();
3781 if (ps.pkg != null) {
3782 pw.print(prefix); pw.print(" versionName="); pw.println(ps.pkg.mVersionName);
Jeff Sharkeyc4d05fc2014-12-01 16:24:01 -08003783 pw.print(prefix); pw.print(" splits="); dumpSplitNames(pw, ps.pkg); pw.println();
Dianne Hackbornc895be72013-03-11 17:48:43 -07003784 pw.print(prefix); pw.print(" applicationInfo=");
3785 pw.println(ps.pkg.applicationInfo.toString());
3786 pw.print(prefix); pw.print(" flags="); printFlags(pw, ps.pkg.applicationInfo.flags,
3787 FLAG_DUMP_SPEC); pw.println();
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003788 pw.print(prefix); pw.print(" priavateFlags="); printFlags(pw,
3789 ps.pkg.applicationInfo.privateFlags, PRIVATE_FLAG_DUMP_SPEC); pw.println();
Dianne Hackbornc895be72013-03-11 17:48:43 -07003790 pw.print(prefix); pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
3791 if (ps.pkg.mOperationPending) {
3792 pw.print(prefix); pw.println(" mOperationPending=true");
3793 }
3794 pw.print(prefix); pw.print(" supportsScreens=[");
3795 boolean first = true;
3796 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
3797 if (!first)
3798 pw.print(", ");
3799 first = false;
3800 pw.print("small");
3801 }
3802 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
3803 if (!first)
3804 pw.print(", ");
3805 first = false;
3806 pw.print("medium");
3807 }
3808 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
3809 if (!first)
3810 pw.print(", ");
3811 first = false;
3812 pw.print("large");
3813 }
3814 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
3815 if (!first)
3816 pw.print(", ");
3817 first = false;
3818 pw.print("xlarge");
3819 }
3820 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
3821 if (!first)
3822 pw.print(", ");
3823 first = false;
3824 pw.print("resizeable");
3825 }
3826 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
3827 if (!first)
3828 pw.print(", ");
3829 first = false;
3830 pw.print("anyDensity");
3831 }
3832 pw.println("]");
3833 if (ps.pkg.libraryNames != null && ps.pkg.libraryNames.size() > 0) {
3834 pw.print(prefix); pw.println(" libraries:");
3835 for (int i=0; i<ps.pkg.libraryNames.size(); i++) {
3836 pw.print(prefix); pw.print(" "); pw.println(ps.pkg.libraryNames.get(i));
3837 }
3838 }
3839 if (ps.pkg.usesLibraries != null && ps.pkg.usesLibraries.size() > 0) {
3840 pw.print(prefix); pw.println(" usesLibraries:");
3841 for (int i=0; i<ps.pkg.usesLibraries.size(); i++) {
3842 pw.print(prefix); pw.print(" "); pw.println(ps.pkg.usesLibraries.get(i));
3843 }
3844 }
3845 if (ps.pkg.usesOptionalLibraries != null
3846 && ps.pkg.usesOptionalLibraries.size() > 0) {
3847 pw.print(prefix); pw.println(" usesOptionalLibraries:");
3848 for (int i=0; i<ps.pkg.usesOptionalLibraries.size(); i++) {
3849 pw.print(prefix); pw.print(" ");
3850 pw.println(ps.pkg.usesOptionalLibraries.get(i));
3851 }
3852 }
3853 if (ps.pkg.usesLibraryFiles != null
3854 && ps.pkg.usesLibraryFiles.length > 0) {
3855 pw.print(prefix); pw.println(" usesLibraryFiles:");
3856 for (int i=0; i<ps.pkg.usesLibraryFiles.length; i++) {
3857 pw.print(prefix); pw.print(" "); pw.println(ps.pkg.usesLibraryFiles[i]);
3858 }
3859 }
3860 }
3861 pw.print(prefix); pw.print(" timeStamp=");
3862 date.setTime(ps.timeStamp);
3863 pw.println(sdf.format(date));
3864 pw.print(prefix); pw.print(" firstInstallTime=");
3865 date.setTime(ps.firstInstallTime);
3866 pw.println(sdf.format(date));
3867 pw.print(prefix); pw.print(" lastUpdateTime=");
3868 date.setTime(ps.lastUpdateTime);
3869 pw.println(sdf.format(date));
3870 if (ps.installerPackageName != null) {
3871 pw.print(prefix); pw.print(" installerPackageName=");
3872 pw.println(ps.installerPackageName);
3873 }
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07003874 if (ps.volumeUuid != null) {
3875 pw.print(prefix); pw.print(" volumeUuid=");
3876 pw.println(ps.volumeUuid);
3877 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07003878 pw.print(prefix); pw.print(" signatures="); pw.println(ps.signatures);
Svetoslavcf959f62015-03-26 20:53:34 -07003879 pw.print(prefix); pw.print(" installPermissionsFixed=");
3880 pw.print(ps.installPermissionsFixed);
Dianne Hackbornc895be72013-03-11 17:48:43 -07003881 pw.print(" installStatus="); pw.println(ps.installStatus);
3882 pw.print(prefix); pw.print(" pkgFlags="); printFlags(pw, ps.pkgFlags, FLAG_DUMP_SPEC);
3883 pw.println();
Svetoslavc6d1c342015-02-26 14:44:43 -08003884
3885 if (ps.sharedUser == null) {
3886 PermissionsState permissionsState = ps.getPermissionsState();
3887 dumpInstallPermissionsLPr(pw, prefix + " ", permissionsState);
3888 }
3889
Dianne Hackbornc895be72013-03-11 17:48:43 -07003890 for (UserInfo user : users) {
3891 pw.print(prefix); pw.print(" User "); pw.print(user.id); pw.print(": ");
3892 pw.print(" installed=");
3893 pw.print(ps.getInstalled(user.id));
Amith Yamasanie5bcff62014-07-19 15:44:09 -07003894 pw.print(" hidden=");
3895 pw.print(ps.getHidden(user.id));
Dianne Hackbornc895be72013-03-11 17:48:43 -07003896 pw.print(" stopped=");
3897 pw.print(ps.getStopped(user.id));
3898 pw.print(" notLaunched=");
3899 pw.print(ps.getNotLaunched(user.id));
3900 pw.print(" enabled=");
3901 pw.println(ps.getEnabled(user.id));
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07003902 String lastDisabledAppCaller = ps.getLastDisabledAppCaller(user.id);
3903 if (lastDisabledAppCaller != null) {
3904 pw.print(prefix); pw.print(" lastDisabledCaller: ");
3905 pw.println(lastDisabledAppCaller);
3906 }
Svetoslavc6d1c342015-02-26 14:44:43 -08003907
3908 if (ps.sharedUser == null) {
3909 PermissionsState permissionsState = ps.getPermissionsState();
3910 dumpGidsLPr(pw, prefix + " ", permissionsState.computeGids(user.id));
3911 dumpRuntimePermissionsLPr(pw, prefix + " ", permissionsState
3912 .getRuntimePermissions(user.id));
3913 }
3914
Jeff Sharkey9f837a92014-10-24 12:07:24 -07003915 ArraySet<String> cmp = ps.getDisabledComponents(user.id);
Dianne Hackbornc895be72013-03-11 17:48:43 -07003916 if (cmp != null && cmp.size() > 0) {
3917 pw.print(prefix); pw.println(" disabledComponents:");
3918 for (String s : cmp) {
3919 pw.print(prefix); pw.print(" "); pw.println(s);
3920 }
3921 }
3922 cmp = ps.getEnabledComponents(user.id);
3923 if (cmp != null && cmp.size() > 0) {
3924 pw.print(prefix); pw.println(" enabledComponents:");
3925 for (String s : cmp) {
3926 pw.print(prefix); pw.print(" "); pw.println(s);
3927 }
3928 }
3929 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07003930 }
3931
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08003932 void dumpPackagesLPr(PrintWriter pw, String packageName, DumpState dumpState, boolean checkin) {
Kenny Root447106f2011-03-23 11:00:15 -07003933 final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
3934 final Date date = new Date();
3935 boolean printedSomething = false;
Amith Yamasani7ea3e7d2012-04-20 15:19:35 -07003936 List<UserInfo> users = getAllUsers();
Kenny Root447106f2011-03-23 11:00:15 -07003937 for (final PackageSetting ps : mPackages.values()) {
3938 if (packageName != null && !packageName.equals(ps.realName)
3939 && !packageName.equals(ps.name)) {
3940 continue;
3941 }
3942
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08003943 if (!checkin && packageName != null) {
Kenny Root447106f2011-03-23 11:00:15 -07003944 dumpState.setSharedUser(ps.sharedUser);
3945 }
3946
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08003947 if (!checkin && !printedSomething) {
Kenny Root447106f2011-03-23 11:00:15 -07003948 if (dumpState.onTitlePrinted())
Dianne Hackborncbfd23e2013-06-11 14:26:53 -07003949 pw.println();
Kenny Root447106f2011-03-23 11:00:15 -07003950 pw.println("Packages:");
3951 printedSomething = true;
3952 }
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08003953 dumpPackageLPr(pw, " ", checkin ? "pkg" : null, ps, sdf, date, users);
Kenny Root447106f2011-03-23 11:00:15 -07003954 }
3955
3956 printedSomething = false;
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08003957 if (!checkin && mRenamedPackages.size() > 0) {
Andy McFadden2f362292012-01-20 14:43:38 -08003958 for (final Map.Entry<String, String> e : mRenamedPackages.entrySet()) {
Kenny Root447106f2011-03-23 11:00:15 -07003959 if (packageName != null && !packageName.equals(e.getKey())
3960 && !packageName.equals(e.getValue())) {
3961 continue;
3962 }
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08003963 if (!checkin) {
3964 if (!printedSomething) {
3965 if (dumpState.onTitlePrinted())
3966 pw.println();
3967 pw.println("Renamed packages:");
3968 printedSomething = true;
3969 }
3970 pw.print(" ");
3971 } else {
3972 pw.print("ren,");
Kenny Root447106f2011-03-23 11:00:15 -07003973 }
Kenny Root447106f2011-03-23 11:00:15 -07003974 pw.print(e.getKey());
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08003975 pw.print(checkin ? " -> " : ",");
Kenny Root447106f2011-03-23 11:00:15 -07003976 pw.println(e.getValue());
3977 }
3978 }
3979
3980 printedSomething = false;
3981 if (mDisabledSysPackages.size() > 0) {
3982 for (final PackageSetting ps : mDisabledSysPackages.values()) {
3983 if (packageName != null && !packageName.equals(ps.realName)
3984 && !packageName.equals(ps.name)) {
3985 continue;
3986 }
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08003987 if (!checkin && !printedSomething) {
Kenny Root447106f2011-03-23 11:00:15 -07003988 if (dumpState.onTitlePrinted())
Dianne Hackborncbfd23e2013-06-11 14:26:53 -07003989 pw.println();
Kenny Root447106f2011-03-23 11:00:15 -07003990 pw.println("Hidden system packages:");
3991 printedSomething = true;
3992 }
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08003993 dumpPackageLPr(pw, " ", checkin ? "dis" : null, ps, sdf, date, users);
Kenny Root447106f2011-03-23 11:00:15 -07003994 }
3995 }
3996 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003997
Kenny Root447106f2011-03-23 11:00:15 -07003998 void dumpPermissionsLPr(PrintWriter pw, String packageName, DumpState dumpState) {
3999 boolean printedSomething = false;
4000 for (BasePermission p : mPermissions.values()) {
4001 if (packageName != null && !packageName.equals(p.sourcePackage)) {
4002 continue;
4003 }
4004 if (!printedSomething) {
4005 if (dumpState.onTitlePrinted())
Dianne Hackborncbfd23e2013-06-11 14:26:53 -07004006 pw.println();
Kenny Root447106f2011-03-23 11:00:15 -07004007 pw.println("Permissions:");
4008 printedSomething = true;
4009 }
4010 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
4011 pw.print(Integer.toHexString(System.identityHashCode(p)));
4012 pw.println("):");
4013 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
4014 pw.print(" uid="); pw.print(p.uid);
Jeff Sharkey00f39042015-03-23 16:51:22 -07004015 pw.print(" gids="); pw.print(Arrays.toString(
4016 p.computeGids(UserHandle.USER_OWNER)));
Kenny Root447106f2011-03-23 11:00:15 -07004017 pw.print(" type="); pw.print(p.type);
Dianne Hackborne639da72012-02-21 15:11:13 -08004018 pw.print(" prot=");
4019 pw.println(PermissionInfo.protectionToString(p.protectionLevel));
Kenny Root447106f2011-03-23 11:00:15 -07004020 if (p.packageSetting != null) {
4021 pw.print(" packageSetting="); pw.println(p.packageSetting);
4022 }
4023 if (p.perm != null) {
4024 pw.print(" perm="); pw.println(p.perm);
4025 }
Jeff Sharkey1c27576a2012-04-11 19:07:08 -07004026 if (READ_EXTERNAL_STORAGE.equals(p.name)) {
Jeff Sharkey5d32e772012-04-12 15:59:23 -07004027 pw.print(" enforced=");
4028 pw.println(mReadExternalStorageEnforced);
Jeff Sharkey1c27576a2012-04-11 19:07:08 -07004029 }
Kenny Root447106f2011-03-23 11:00:15 -07004030 }
4031 }
Jeff Sharkey1c27576a2012-04-11 19:07:08 -07004032
Dianne Hackbornd052a942014-11-21 15:23:13 -08004033 void dumpSharedUsersLPr(PrintWriter pw, String packageName, DumpState dumpState,
4034 boolean checkin) {
Kenny Root447106f2011-03-23 11:00:15 -07004035 boolean printedSomething = false;
4036 for (SharedUserSetting su : mSharedUsers.values()) {
4037 if (packageName != null && su != dumpState.getSharedUser()) {
4038 continue;
4039 }
Dianne Hackbornd052a942014-11-21 15:23:13 -08004040 if (!checkin) {
4041 if (!printedSomething) {
4042 if (dumpState.onTitlePrinted())
4043 pw.println();
4044 pw.println("Shared users:");
4045 printedSomething = true;
4046 }
4047 pw.print(" SharedUser [");
4048 pw.print(su.name);
4049 pw.print("] (");
4050 pw.print(Integer.toHexString(System.identityHashCode(su)));
4051 pw.println("):");
Svetoslavc6d1c342015-02-26 14:44:43 -08004052
4053 String prefix = " ";
4054 pw.print(prefix); pw.print("userId="); pw.println(su.userId);
4055
4056 PermissionsState permissionsState = su.getPermissionsState();
4057 dumpInstallPermissionsLPr(pw, prefix, permissionsState);
4058
4059 for (int userId : UserManagerService.getInstance().getUserIds()) {
4060 final int[] gids = permissionsState.computeGids(userId);
4061 Set<String> permissions = permissionsState.getRuntimePermissions(userId);
4062 if (!ArrayUtils.isEmpty(gids) || !permissions.isEmpty()) {
4063 pw.print(prefix); pw.print("User "); pw.print(userId); pw.println(": ");
4064 dumpGidsLPr(pw, prefix + " ", gids);
4065 dumpRuntimePermissionsLPr(pw, prefix + " ", permissions);
4066 }
Dianne Hackbornd052a942014-11-21 15:23:13 -08004067 }
4068 } else {
4069 pw.print("suid,"); pw.print(su.userId); pw.print(","); pw.println(su.name);
Kenny Root447106f2011-03-23 11:00:15 -07004070 }
4071 }
4072 }
4073
4074 void dumpReadMessagesLPr(PrintWriter pw, DumpState dumpState) {
4075 pw.println("Settings parse messages:");
4076 pw.print(mReadMessages.toString());
4077 }
Jeff Sharkeyc4d05fc2014-12-01 16:24:01 -08004078
4079 private static void dumpSplitNames(PrintWriter pw, PackageParser.Package pkg) {
4080 if (pkg == null) {
4081 pw.print("unknown");
4082 } else {
4083 // [base:10, config.mdpi, config.xhdpi:12]
4084 pw.print("[");
4085 pw.print("base");
4086 if (pkg.baseRevisionCode != 0) {
4087 pw.print(":"); pw.print(pkg.baseRevisionCode);
4088 }
4089 if (pkg.splitNames != null) {
4090 for (int i = 0; i < pkg.splitNames.length; i++) {
4091 pw.print(", ");
4092 pw.print(pkg.splitNames[i]);
4093 if (pkg.splitRevisionCodes[i] != 0) {
4094 pw.print(":"); pw.print(pkg.splitRevisionCodes[i]);
4095 }
4096 }
4097 }
4098 pw.print("]");
4099 }
4100 }
Svetoslavc6d1c342015-02-26 14:44:43 -08004101
4102 void dumpGidsLPr(PrintWriter pw, String prefix, int[] gids) {
4103 if (!ArrayUtils.isEmpty(gids)) {
Fabrice Di Meglio62271722015-04-10 17:24:02 -07004104 pw.print(prefix);
4105 pw.print("gids="); pw.println(
Svetoslavc6d1c342015-02-26 14:44:43 -08004106 PackageManagerService.arrayToString(gids));
4107 }
4108 }
4109
4110 void dumpRuntimePermissionsLPr(PrintWriter pw, String prefix, Set<String> permissions) {
4111 if (!permissions.isEmpty()) {
4112 pw.print(prefix); pw.println("runtime permissions:");
4113 for (String permission : permissions) {
4114 pw.print(prefix); pw.print(" "); pw.println(permission);
4115 }
4116 }
4117 }
4118
4119 void dumpInstallPermissionsLPr(PrintWriter pw, String prefix,
4120 PermissionsState permissionsState) {
4121 Set<String> permissions = permissionsState.getInstallPermissions();
4122 if (!permissions.isEmpty()) {
4123 pw.print(prefix); pw.println("install permissions:");
4124 for (String permission : permissions) {
4125 pw.print(prefix); pw.print(" "); pw.println(permission);
4126 }
4127 }
4128 }
4129
4130 public void writeRuntimePermissionsForUserLPr(int userId, boolean sync) {
4131 if (sync) {
4132 mRuntimePermissionsPersistence.writePermissionsForUserSyncLPr(userId);
4133 } else {
4134 mRuntimePermissionsPersistence.writePermissionsForUserAsyncLPr(userId);
4135 }
4136 }
4137
4138 private final class RuntimePermissionPersistence {
4139 private static final long WRITE_PERMISSIONS_DELAY_MILLIS = 200;
4140
4141 private static final long MAX_WRITE_PERMISSIONS_DELAY_MILLIS = 2000;
4142
4143 private final Handler mHandler = new MyHandler();
4144
4145 private final Object mLock;
4146
4147 @GuardedBy("mLock")
4148 private SparseBooleanArray mWriteScheduled = new SparseBooleanArray();
4149
4150 @GuardedBy("mLock")
4151 private SparseLongArray mLastNotWrittenMutationTimesMillis = new SparseLongArray();
4152
4153 public RuntimePermissionPersistence(Object lock) {
4154 mLock = lock;
4155 }
4156
4157 public void writePermissionsForUserSyncLPr(int userId) {
Svet Ganov12a692a2015-03-28 19:34:15 -07004158 if (!PackageManagerService.RUNTIME_PERMISSIONS_ENABLED) {
4159 return;
4160 }
4161
Svetoslavc6d1c342015-02-26 14:44:43 -08004162 mHandler.removeMessages(userId);
4163 writePermissionsSync(userId);
4164 }
4165
4166 public void writePermissionsForUserAsyncLPr(int userId) {
Svet Ganov12a692a2015-03-28 19:34:15 -07004167 if (!PackageManagerService.RUNTIME_PERMISSIONS_ENABLED) {
4168 return;
4169 }
4170
Svetoslavc6d1c342015-02-26 14:44:43 -08004171 final long currentTimeMillis = SystemClock.uptimeMillis();
4172
4173 if (mWriteScheduled.get(userId)) {
4174 mHandler.removeMessages(userId);
4175
4176 // If enough time passed, write without holding off anymore.
4177 final long lastNotWrittenMutationTimeMillis = mLastNotWrittenMutationTimesMillis
4178 .get(userId);
4179 final long timeSinceLastNotWrittenMutationMillis = currentTimeMillis
4180 - lastNotWrittenMutationTimeMillis;
4181 if (timeSinceLastNotWrittenMutationMillis >= MAX_WRITE_PERMISSIONS_DELAY_MILLIS) {
4182 mHandler.obtainMessage(userId).sendToTarget();
4183 return;
4184 }
4185
4186 // Hold off a bit more as settings are frequently changing.
4187 final long maxDelayMillis = Math.max(lastNotWrittenMutationTimeMillis
4188 + MAX_WRITE_PERMISSIONS_DELAY_MILLIS - currentTimeMillis, 0);
4189 final long writeDelayMillis = Math.min(WRITE_PERMISSIONS_DELAY_MILLIS,
4190 maxDelayMillis);
4191
4192 Message message = mHandler.obtainMessage(userId);
4193 mHandler.sendMessageDelayed(message, writeDelayMillis);
4194 } else {
4195 mLastNotWrittenMutationTimesMillis.put(userId, currentTimeMillis);
4196 Message message = mHandler.obtainMessage(userId);
4197 mHandler.sendMessageDelayed(message, WRITE_PERMISSIONS_DELAY_MILLIS);
4198 mWriteScheduled.put(userId, true);
4199 }
4200 }
4201
4202 private void writePermissionsSync(int userId) {
4203 AtomicFile destination = new AtomicFile(getUserRuntimePermissionsFile(userId));
4204
4205 ArrayMap<String, Set<String>> permissionsForPackage = new ArrayMap<>();
4206 ArrayMap<String, Set<String>> permissionsForSharedUser = new ArrayMap<>();
4207
4208 synchronized (mLock) {
4209 mWriteScheduled.delete(userId);
4210
4211 final int packageCount = mPackages.size();
4212 for (int i = 0; i < packageCount; i++) {
4213 String packageName = mPackages.keyAt(i);
4214 PackageSetting packageSetting = mPackages.valueAt(i);
4215 if (packageSetting.sharedUser == null) {
4216 PermissionsState permissionsState = packageSetting.getPermissionsState();
4217 Set<String> permissions = permissionsState.getRuntimePermissions(userId);
4218 if (!permissions.isEmpty()) {
4219 permissionsForPackage.put(packageName, permissions);
4220 }
4221 }
4222 }
4223
4224 final int sharedUserCount = mSharedUsers.size();
4225 for (int i = 0; i < sharedUserCount; i++) {
4226 String sharedUserName = mSharedUsers.keyAt(i);
4227 SharedUserSetting sharedUser = mSharedUsers.valueAt(i);
4228 PermissionsState permissionsState = sharedUser.getPermissionsState();
4229 Set<String> permissions = permissionsState.getRuntimePermissions(userId);
4230 if (!permissions.isEmpty()) {
4231 permissionsForSharedUser.put(sharedUserName, permissions);
4232 }
4233 }
4234 }
4235
4236 FileOutputStream out = null;
4237 try {
4238 out = destination.startWrite();
4239
4240 XmlSerializer serializer = Xml.newSerializer();
4241 serializer.setOutput(out, "utf-8");
4242 serializer.setFeature(
4243 "http://xmlpull.org/v1/doc/features.html#indent-output", true);
4244 serializer.startDocument(null, true);
4245 serializer.startTag(null, TAG_RUNTIME_PERMISSIONS);
4246
4247 final int packageCount = permissionsForPackage.size();
4248 for (int i = 0; i < packageCount; i++) {
4249 String packageName = permissionsForPackage.keyAt(i);
4250 Set<String> permissions = permissionsForPackage.valueAt(i);
4251 serializer.startTag(null, TAG_PACKAGE);
4252 serializer.attribute(null, ATTR_NAME, packageName);
4253 writePermissions(serializer, permissions);
4254 serializer.endTag(null, TAG_PACKAGE);
4255 }
4256
4257 final int sharedUserCount = permissionsForSharedUser.size();
4258 for (int i = 0; i < sharedUserCount; i++) {
4259 String packageName = permissionsForSharedUser.keyAt(i);
4260 Set<String> permissions = permissionsForSharedUser.valueAt(i);
4261 serializer.startTag(null, TAG_SHARED_USER);
4262 serializer.attribute(null, ATTR_NAME, packageName);
4263 writePermissions(serializer, permissions);
4264 serializer.endTag(null, TAG_SHARED_USER);
4265 }
4266
4267 serializer.endTag(null, TAG_RUNTIME_PERMISSIONS);
4268 serializer.endDocument();
4269 destination.finishWrite(out);
4270 } catch (IOException e) {
4271 Slog.wtf(PackageManagerService.TAG,
4272 "Failed to write settings, restoring backup", e);
4273 destination.failWrite(out);
4274 } finally {
4275 IoUtils.closeQuietly(out);
4276 }
4277 }
4278
4279 private void onUserRemoved(int userId) {
4280 // Make sure we do not
4281 mHandler.removeMessages(userId);
4282
4283 for (SettingBase sb : mPackages.values()) {
4284 revokeRuntimePermissions(sb, userId);
4285 }
4286
4287 for (SettingBase sb : mSharedUsers.values()) {
4288 revokeRuntimePermissions(sb, userId);
4289 }
4290 }
4291
4292 private void revokeRuntimePermissions(SettingBase sb, int userId) {
4293 PermissionsState permissionsState = sb.getPermissionsState();
4294 for (String permission : permissionsState.getRuntimePermissions(userId)) {
4295 BasePermission bp = mPermissions.get(permission);
4296 if (bp != null) {
4297 permissionsState.revokeRuntimePermission(bp, userId);
4298 }
4299 }
4300 }
4301
4302 public void readStateForUserSyncLPr(int userId) {
4303 File permissionsFile = getUserRuntimePermissionsFile(userId);
4304 if (!permissionsFile.exists()) {
4305 return;
4306 }
4307
4308 FileInputStream in;
4309 try {
4310 in = new FileInputStream(permissionsFile);
4311 } catch (FileNotFoundException fnfe) {
4312 Slog.i(PackageManagerService.TAG, "No permissions state");
4313 return;
4314 }
4315
4316 try {
4317 XmlPullParser parser = Xml.newPullParser();
4318 parser.setInput(in, null);
4319 parseRuntimePermissionsLPr(parser, userId);
4320 } catch (XmlPullParserException | IOException ise) {
4321 throw new IllegalStateException("Failed parsing permissions file: "
4322 + permissionsFile , ise);
4323 } finally {
4324 IoUtils.closeQuietly(in);
4325 }
4326 }
4327
4328 private void parseRuntimePermissionsLPr(XmlPullParser parser, int userId)
4329 throws IOException, XmlPullParserException {
Svet Ganov12a692a2015-03-28 19:34:15 -07004330 final int outerDepth = parser.getDepth();
4331 int type;
4332 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
4333 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
4334 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
4335 continue;
4336 }
Svetoslavc6d1c342015-02-26 14:44:43 -08004337
Svet Ganov12a692a2015-03-28 19:34:15 -07004338 switch (parser.getName()) {
4339 case TAG_PACKAGE: {
4340 String name = parser.getAttributeValue(null, ATTR_NAME);
4341 PackageSetting ps = mPackages.get(name);
4342 if (ps == null) {
4343 Slog.w(PackageManagerService.TAG, "Unknown package:" + name);
4344 XmlUtils.skipCurrentTag(parser);
4345 continue;
4346 }
4347 parsePermissionsLPr(parser, ps.getPermissionsState(), userId);
4348 } break;
Svetoslavc6d1c342015-02-26 14:44:43 -08004349
Svet Ganov12a692a2015-03-28 19:34:15 -07004350 case TAG_SHARED_USER: {
4351 String name = parser.getAttributeValue(null, ATTR_NAME);
4352 SharedUserSetting sus = mSharedUsers.get(name);
4353 if (sus == null) {
4354 Slog.w(PackageManagerService.TAG, "Unknown shared user:" + name);
4355 XmlUtils.skipCurrentTag(parser);
4356 continue;
4357 }
4358 parsePermissionsLPr(parser, sus.getPermissionsState(), userId);
4359 } break;
Svetoslavc6d1c342015-02-26 14:44:43 -08004360 }
4361 }
Svetoslavc6d1c342015-02-26 14:44:43 -08004362 }
4363
Svet Ganov12a692a2015-03-28 19:34:15 -07004364 private void parsePermissionsLPr(XmlPullParser parser, PermissionsState permissionsState,
Svetoslavc6d1c342015-02-26 14:44:43 -08004365 int userId) throws IOException, XmlPullParserException {
Svet Ganov12a692a2015-03-28 19:34:15 -07004366 final int outerDepth = parser.getDepth();
4367 int type;
4368 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
4369 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
4370 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
4371 continue;
Svetoslavc6d1c342015-02-26 14:44:43 -08004372 }
Svetoslavc6d1c342015-02-26 14:44:43 -08004373
Svet Ganov12a692a2015-03-28 19:34:15 -07004374 switch (parser.getName()) {
4375 case TAG_ITEM: {
4376 String name = parser.getAttributeValue(null, ATTR_NAME);
4377 BasePermission bp = mPermissions.get(name);
4378 if (bp == null) {
4379 Slog.w(PackageManagerService.TAG, "Unknown permission:" + name);
4380 XmlUtils.skipCurrentTag(parser);
4381 continue;
4382 }
Svetoslavc6d1c342015-02-26 14:44:43 -08004383
Svet Ganov12a692a2015-03-28 19:34:15 -07004384 if (permissionsState.grantRuntimePermission(bp, userId) ==
4385 PermissionsState.PERMISSION_OPERATION_FAILURE) {
4386 Slog.w(PackageManagerService.TAG, "Duplicate permission:" + name);
4387 }
4388 } break;
Svetoslavc6d1c342015-02-26 14:44:43 -08004389 }
Svetoslavc6d1c342015-02-26 14:44:43 -08004390 }
Svetoslavc6d1c342015-02-26 14:44:43 -08004391 }
4392
4393 private void writePermissions(XmlSerializer serializer, Set<String> permissions)
4394 throws IOException {
4395 for (String permission : permissions) {
4396 serializer.startTag(null, TAG_ITEM);
4397 serializer.attribute(null, ATTR_NAME, permission);
4398 serializer.endTag(null, TAG_ITEM);
4399 }
4400 }
4401
4402 private final class MyHandler extends Handler {
4403 public MyHandler() {
4404 super(BackgroundThread.getHandler().getLooper());
4405 }
4406
4407 @Override
4408 public void handleMessage(Message message) {
4409 final int userId = message.what;
4410 Runnable callback = (Runnable) message.obj;
4411 writePermissionsSync(userId);
4412 if (callback != null) {
4413 callback.run();
4414 }
4415 }
4416 }
4417 }
Andy McFadden2f362292012-01-20 14:43:38 -08004418}