blob: 1872371681098ccc367ce38f1cbc71e01272e6e6 [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
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070019import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070020import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
Dianne Hackbornfd7aded2013-01-22 17:10:23 -080022import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
Dianne Hackborn0ac30312011-06-17 14:49:23 -070023import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070024import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
Christopher Tatee9fd1fa2015-09-15 16:43:07 -070025import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
26import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
27import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
Fabrice Di Meglio07885952015-04-06 19:41:28 -070028import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -080029import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070030import static android.content.pm.PackageManager.MATCH_DEFAULT_ONLY;
31import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
32import static android.content.pm.PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS;
33import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE;
34import static android.content.pm.PackageManager.MATCH_ENCRYPTION_UNAWARE;
35import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
Jeff Sharkey184a0102013-07-10 16:19:52 -070036import static android.os.Process.PACKAGE_INFO_GID;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070037import static android.os.Process.SYSTEM_UID;
Christopher Tate72c10a22015-06-12 18:31:24 -070038import static com.android.server.pm.PackageManagerService.DEBUG_DOMAIN_VERIFICATION;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070039
Xiaohui Chen594f2082015-08-18 11:04:20 -070040import android.annotation.NonNull;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070041import android.content.ComponentName;
42import android.content.Intent;
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080043import android.content.IntentFilter;
44import android.content.pm.ActivityInfo;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070045import android.content.pm.ApplicationInfo;
46import android.content.pm.ComponentInfo;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -080047import android.content.pm.IntentFilterVerificationInfo;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070048import android.content.pm.PackageCleanItem;
49import android.content.pm.PackageManager;
50import android.content.pm.PackageParser;
51import android.content.pm.PackageUserState;
52import android.content.pm.PermissionInfo;
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080053import android.content.pm.ResolveInfo;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070054import android.content.pm.Signature;
55import android.content.pm.UserInfo;
56import android.content.pm.VerifierDeviceIdentity;
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080057import android.net.Uri;
Narayan Kamathff110bd2014-07-04 18:30:45 +010058import android.os.Binder;
Jeff Sharkey4ed745d2014-07-15 20:39:15 -070059import android.os.Build;
Narayan Kamathff110bd2014-07-04 18:30:45 +010060import android.os.Environment;
61import android.os.FileUtils;
Svetoslavc6d1c342015-02-26 14:44:43 -080062import android.os.Handler;
63import android.os.Message;
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080064import android.os.PatternMatcher;
Narayan Kamathff110bd2014-07-04 18:30:45 +010065import android.os.Process;
Svetoslavc6d1c342015-02-26 14:44:43 -080066import android.os.SystemClock;
Narayan Kamathff110bd2014-07-04 18:30:45 +010067import android.os.UserHandle;
Amith Yamasani26f9ea32014-09-11 10:56:51 -070068import android.os.UserManager;
Paul Crowleybcf48ed2015-04-22 13:36:59 +010069import android.os.storage.StorageManager;
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -070070import android.os.storage.VolumeInfo;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -080071import android.text.TextUtils;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070072import android.util.ArrayMap;
73import android.util.ArraySet;
74import android.util.AtomicFile;
75import android.util.Log;
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080076import android.util.LogPrinter;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070077import android.util.Slog;
78import android.util.SparseArray;
Svetoslavc6d1c342015-02-26 14:44:43 -080079import android.util.SparseBooleanArray;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070080import android.util.SparseIntArray;
Svetoslavc6d1c342015-02-26 14:44:43 -080081import android.util.SparseLongArray;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070082import android.util.Xml;
Christopher Tatee012a232015-04-01 17:18:50 -070083
Svetoslavc6d1c342015-02-26 14:44:43 -080084import com.android.internal.annotations.GuardedBy;
85import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -070086import com.android.internal.os.InstallerConnection.InstallerException;
Svetoslavc6d1c342015-02-26 14:44:43 -080087import com.android.internal.util.ArrayUtils;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070088import com.android.internal.util.FastXmlSerializer;
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -070089import com.android.internal.util.IndentingPrintWriter;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070090import com.android.internal.util.JournaledFile;
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -070091import com.android.internal.util.Preconditions;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070092import com.android.internal.util.XmlUtils;
Christopher Tatee012a232015-04-01 17:18:50 -070093import com.android.server.backup.PreferredActivityBackupHelper;
Kenny Root447106f2011-03-23 11:00:15 -070094import com.android.server.pm.PackageManagerService.DumpState;
Svet Ganov8c7f7002015-05-07 10:48:44 -070095import com.android.server.pm.PermissionsState.PermissionState;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070096
Jeff Sharkey2a90f6732016-01-06 12:26:11 -070097import libcore.io.IoUtils;
Alexandra Gherghina6e2ae252014-06-12 16:03:58 +010098
Kenny Rootcf0b38c2011-03-22 14:17:59 -070099import org.xmlpull.v1.XmlPullParser;
100import org.xmlpull.v1.XmlPullParserException;
101import org.xmlpull.v1.XmlSerializer;
102
Jeff Sharkey2a90f6732016-01-06 12:26:11 -0700103import java.io.BufferedInputStream;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700104import java.io.BufferedOutputStream;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -0700105import java.io.BufferedWriter;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700106import java.io.File;
107import java.io.FileInputStream;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -0700108import java.io.FileNotFoundException;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700109import java.io.FileOutputStream;
110import java.io.IOException;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -0700111import java.io.InputStream;
112import java.io.OutputStreamWriter;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700113import java.io.PrintWriter;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -0700114import java.nio.charset.Charset;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100115import java.nio.charset.StandardCharsets;
Kenny Root447106f2011-03-23 11:00:15 -0700116import java.text.SimpleDateFormat;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700117import java.util.ArrayList;
118import java.util.Arrays;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -0700119import java.util.Collection;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -0800120import java.util.Collections;
Kenny Root447106f2011-03-23 11:00:15 -0700121import java.util.Date;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700122import java.util.Iterator;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700123import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800124import java.util.Map;
Jeff Sharkey2a90f6732016-01-06 12:26:11 -0700125import java.util.Map.Entry;
Jeff Sharkey84f12942014-07-10 17:48:11 -0700126import java.util.Objects;
Dianne Hackborn63092712012-10-07 14:45:35 -0700127import java.util.Set;
Kenny Root62539e92011-11-10 09:35:38 -0800128
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700129/**
130 * Holds information about dynamic settings.
131 */
132final class Settings {
Kenny Root447106f2011-03-23 11:00:15 -0700133 private static final String TAG = "PackageSettings";
134
Kenny Rootc1c0d3c2014-04-24 13:36:40 -0700135 /**
136 * Current version of the package database. Set it to the latest version in
137 * the {@link DatabaseVersion} class below to ensure the database upgrade
138 * doesn't happen repeatedly.
139 * <p>
140 * Note that care should be taken to make sure all database upgrades are
141 * idempotent.
142 */
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700143 public static final int CURRENT_DATABASE_VERSION = DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
Kenny Rootc1c0d3c2014-04-24 13:36:40 -0700144
145 /**
146 * This class contains constants that can be referred to from upgrade code.
147 * Insert constant values here that describe the upgrade reason. The version
148 * code must be monotonically increasing.
149 */
150 public static class DatabaseVersion {
151 /**
152 * The initial version of the database.
153 */
154 public static final int FIRST_VERSION = 1;
Kenny Roota8e65fd2014-04-24 11:44:47 -0700155
156 /**
157 * Migrating the Signature array from the entire certificate chain to
158 * just the signing certificate.
159 */
160 public static final int SIGNATURE_END_ENTITY = 2;
Jeff Sharkeyd68b87c2014-11-12 12:18:11 -0800161
162 /**
163 * There was a window of time in
164 * {@link android.os.Build.VERSION_CODES#LOLLIPOP} where we persisted
165 * certificates after potentially mutating them. To switch back to the
166 * original untouched certificates, we need to force a collection pass.
167 */
168 public static final int SIGNATURE_MALFORMED_RECOVER = 3;
Kenny Rootc1c0d3c2014-04-24 13:36:40 -0700169 }
170
Kenny Root447106f2011-03-23 11:00:15 -0700171 private static final boolean DEBUG_STOPPED = false;
Amith Yamasani258848d2012-08-10 17:06:33 -0700172 private static final boolean DEBUG_MU = false;
Kenny Root447106f2011-03-23 11:00:15 -0700173
Svetoslavc6d1c342015-02-26 14:44:43 -0800174 private static final String RUNTIME_PERMISSIONS_FILE_NAME = "runtime-permissions.xml";
175
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -0700176 private static final String TAG_READ_EXTERNAL_STORAGE = "read-external-storage";
177 private static final String ATTR_ENFORCEMENT = "enforcement";
178
Amith Yamasani483f3b02012-03-13 16:08:00 -0700179 private static final String TAG_ITEM = "item";
180 private static final String TAG_DISABLED_COMPONENTS = "disabled-components";
181 private static final String TAG_ENABLED_COMPONENTS = "enabled-components";
182 private static final String TAG_PACKAGE_RESTRICTIONS = "package-restrictions";
183 private static final String TAG_PACKAGE = "pkg";
Svetoslavc6d1c342015-02-26 14:44:43 -0800184 private static final String TAG_SHARED_USER = "shared-user";
185 private static final String TAG_RUNTIME_PERMISSIONS = "runtime-permissions";
186 private static final String TAG_PERMISSIONS = "perms";
Svet Ganov354cd3c2015-12-17 11:35:04 -0800187 private static final String TAG_CHILD_PACKAGE = "child-package";
188
Sander Alewijnseaf597622014-03-20 18:44:57 +0000189 private static final String TAG_PERSISTENT_PREFERRED_ACTIVITIES =
190 "persistent-preferred-activities";
Nicolas Prevot81948992014-05-16 18:25:26 +0100191 static final String TAG_CROSS_PROFILE_INTENT_FILTERS =
192 "crossProfile-intent-filters";
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700193 private static final String TAG_DOMAIN_VERIFICATION = "domain-verification";
194 private static final String TAG_DEFAULT_APPS = "default-apps";
195 private static final String TAG_ALL_INTENT_FILTER_VERIFICATION =
Christopher Tate6038d152015-06-17 13:07:46 -0700196 "all-intent-filter-verifications";
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700197 private static final String TAG_DEFAULT_BROWSER = "default-browser";
198 private static final String TAG_VERSION = "version";
Amith Yamasani483f3b02012-03-13 16:08:00 -0700199
200 private static final String ATTR_NAME = "name";
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700201 private static final String ATTR_USER = "user";
202 private static final String ATTR_CODE = "code";
Amith Yamasani483f3b02012-03-13 16:08:00 -0700203 private static final String ATTR_NOT_LAUNCHED = "nl";
204 private static final String ATTR_ENABLED = "enabled";
Svet Ganov8c7f7002015-05-07 10:48:44 -0700205 private static final String ATTR_GRANTED = "granted";
206 private static final String ATTR_FLAGS = "flags";
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -0700207 private static final String ATTR_ENABLED_CALLER = "enabledCaller";
Amith Yamasani483f3b02012-03-13 16:08:00 -0700208 private static final String ATTR_STOPPED = "stopped";
Amith Yamasanie5bcff62014-07-19 15:44:09 -0700209 // Legacy, here for reading older versions of the package-restrictions.
Amith Yamasani655d0e22013-06-12 14:19:10 -0700210 private static final String ATTR_BLOCKED = "blocked";
Amith Yamasanie5bcff62014-07-19 15:44:09 -0700211 // New name for the above attribute.
212 private static final String ATTR_HIDDEN = "hidden";
Andrei Stingaceanu1e283912015-11-26 15:26:28 +0000213 private static final String ATTR_SUSPENDED = "suspended";
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700214 private static final String ATTR_INSTALLED = "inst";
Kenny Guyc13053b2014-05-29 14:17:17 +0100215 private static final String ATTR_BLOCK_UNINSTALL = "blockUninstall";
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -0800216 private static final String ATTR_DOMAIN_VERIFICATON_STATE = "domainVerificationStatus";
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700217 private static final String ATTR_PACKAGE_NAME = "packageName";
Svet Ganovba3ba812015-06-26 10:54:06 -0700218 private static final String ATTR_FINGERPRINT = "fingerprint";
Christopher Tatef0d6cb32015-07-10 17:44:53 -0700219 private static final String ATTR_APP_LINK_GENERATION = "app-link-generation";
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700220 private static final String ATTR_VOLUME_UUID = "volumeUuid";
221 private static final String ATTR_SDK_VERSION = "sdkVersion";
222 private static final String ATTR_DATABASE_VERSION = "databaseVersion";
Amith Yamasani483f3b02012-03-13 16:08:00 -0700223
Christopher Tatee9fd1fa2015-09-15 16:43:07 -0700224 // Bookkeeping for restored permission grants
225 private static final String TAG_RESTORED_RUNTIME_PERMISSIONS = "restored-perms";
226 // package name: ATTR_PACKAGE_NAME
227 private static final String TAG_PERMISSION_ENTRY = "perm";
228 // permission name: ATTR_NAME
229 // permission granted (boolean): ATTR_GRANTED
230 private static final String ATTR_USER_SET = "set";
231 private static final String ATTR_USER_FIXED = "fixed";
232 private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
233
234 // Flag mask of restored permission grants that are applied at install time
235 private static final int USER_RUNTIME_GRANT_MASK =
236 FLAG_PERMISSION_USER_SET
237 | FLAG_PERMISSION_USER_FIXED
238 | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
239
Svetoslavc6d1c342015-02-26 14:44:43 -0800240 private final Object mLock;
Svetoslavc6d1c342015-02-26 14:44:43 -0800241
242 private final RuntimePermissionPersistence mRuntimePermissionsPersistence;
243
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700244 private final File mSettingsFilename;
245 private final File mBackupSettingsFilename;
246 private final File mPackageListFilename;
247 private final File mStoppedPackagesFilename;
248 private final File mBackupStoppedPackagesFilename;
Jeff Sharkey184a0102013-07-10 16:19:52 -0700249
Jeff Sharkey9f837a92014-10-24 12:07:24 -0700250 final ArrayMap<String, PackageSetting> mPackages =
251 new ArrayMap<String, PackageSetting>();
Christopher Tate6038d152015-06-17 13:07:46 -0700252
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700253 // List of replaced system applications
Jeff Sharkey9f837a92014-10-24 12:07:24 -0700254 private final ArrayMap<String, PackageSetting> mDisabledSysPackages =
255 new ArrayMap<String, PackageSetting>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700256
Christopher Tate6038d152015-06-17 13:07:46 -0700257 // Set of restored intent-filter verification states
258 private final ArrayMap<String, IntentFilterVerificationInfo> mRestoredIntentFilterVerifications =
259 new ArrayMap<String, IntentFilterVerificationInfo>();
260
Christopher Tatee9fd1fa2015-09-15 16:43:07 -0700261 // Bookkeeping for restored user permission grants
262 final class RestoredPermissionGrant {
263 String permissionName;
264 boolean granted;
265 int grantBits;
266
267 RestoredPermissionGrant(String name, boolean isGranted, int theGrantBits) {
268 permissionName = name;
269 granted = isGranted;
270 grantBits = theGrantBits;
271 }
272 }
273
274 // This would be more compact as a flat array of restored grants or something, but we
275 // may have quite a few, especially during early device lifetime, and avoiding all those
276 // linear lookups will be important.
277 private final SparseArray<ArrayMap<String, ArraySet<RestoredPermissionGrant>>>
278 mRestoredUserGrants =
279 new SparseArray<ArrayMap<String, ArraySet<RestoredPermissionGrant>>>();
280
Geremy Condra12c18382013-03-06 16:49:06 -0800281 private static int mFirstAvailableUid = 0;
282
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700283 /** Map from volume UUID to {@link VersionInfo} */
284 private ArrayMap<String, VersionInfo> mVersion = new ArrayMap<>();
Kenny Root0aaa0d92011-09-12 16:42:55 -0700285
Kenny Rootc1c0d3c2014-04-24 13:36:40 -0700286 /**
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700287 * Version details for a storage volume that may hold apps.
Kenny Rootc1c0d3c2014-04-24 13:36:40 -0700288 */
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700289 public static class VersionInfo {
290 /**
291 * These are the last platform API version we were using for the apps
292 * installed on internal and external storage. It is used to grant newer
293 * permissions one time during a system upgrade.
294 */
295 int sdkVersion;
Kenny Rootc1c0d3c2014-04-24 13:36:40 -0700296
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -0700297 /**
298 * The current database version for apps on internal storage. This is
299 * used to upgrade the format of the packages.xml database not
300 * necessarily tied to an SDK version.
301 */
302 int databaseVersion;
303
304 /**
305 * Last known value of {@link Build#FINGERPRINT}. Used to determine when
306 * an system update has occurred, meaning we need to clear code caches.
307 */
308 String fingerprint;
309
310 /**
311 * Force all version information to match current system values,
312 * typically after resolving any required upgrade steps.
313 */
314 public void forceCurrent() {
315 sdkVersion = Build.VERSION.SDK_INT;
316 databaseVersion = CURRENT_DATABASE_VERSION;
317 fingerprint = Build.FINGERPRINT;
318 }
319 }
Jeff Sharkey4ed745d2014-07-15 20:39:15 -0700320
Jeff Sharkeyf5385772012-05-11 14:04:41 -0700321 Boolean mReadExternalStorageEnforced;
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -0700322
Kenny Root0aaa0d92011-09-12 16:42:55 -0700323 /** Device identity for the purpose of package verification. */
324 private VerifierDeviceIdentity mVerifierDeviceIdentity;
325
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700326 // The user's preferred activities associated with particular intent
327 // filters.
Dianne Hackborn63092712012-10-07 14:45:35 -0700328 final SparseArray<PreferredIntentResolver> mPreferredActivities =
329 new SparseArray<PreferredIntentResolver>();
330
Sander Alewijnsef475ca32014-02-17 15:13:58 +0000331 // The persistent preferred activities of the user's profile/device owner
332 // associated with particular intent filters.
333 final SparseArray<PersistentPreferredIntentResolver> mPersistentPreferredActivities =
334 new SparseArray<PersistentPreferredIntentResolver>();
335
Nicolas Prevot10fa67c2014-03-24 13:44:38 +0000336 // For every user, it is used to find to which other users the intent can be forwarded.
Nicolas Prevot81948992014-05-16 18:25:26 +0100337 final SparseArray<CrossProfileIntentResolver> mCrossProfileIntentResolvers =
338 new SparseArray<CrossProfileIntentResolver>();
Nicolas Prevot10fa67c2014-03-24 13:44:38 +0000339
Jeff Sharkey9f837a92014-10-24 12:07:24 -0700340 final ArrayMap<String, SharedUserSetting> mSharedUsers =
341 new ArrayMap<String, SharedUserSetting>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700342 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
343 private final SparseArray<Object> mOtherUserIds =
344 new SparseArray<Object>();
345
346 // For reading/writing settings file.
347 private final ArrayList<Signature> mPastSignatures =
348 new ArrayList<Signature>();
dcashman8c04fac2015-03-23 11:39:42 -0700349 private final ArrayMap<Long, Integer> mKeySetRefs =
350 new ArrayMap<Long, Integer>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700351
352 // Mapping from permission names to info about them.
Jeff Sharkey9f837a92014-10-24 12:07:24 -0700353 final ArrayMap<String, BasePermission> mPermissions =
354 new ArrayMap<String, BasePermission>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700355
356 // Mapping from permission tree names to info about them.
Jeff Sharkey9f837a92014-10-24 12:07:24 -0700357 final ArrayMap<String, BasePermission> mPermissionTrees =
358 new ArrayMap<String, BasePermission>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700359
360 // Packages that have been uninstalled and still need their external
361 // storage data deleted.
Jeff Sharkey752cd922012-09-23 16:25:12 -0700362 final ArrayList<PackageCleanItem> mPackagesToBeCleaned = new ArrayList<PackageCleanItem>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700363
364 // Packages that have been renamed since they were first installed.
365 // Keys are the new names of the packages, values are the original
366 // names. The packages appear everwhere else under their original
367 // names.
Jeff Sharkey9f837a92014-10-24 12:07:24 -0700368 final ArrayMap<String, String> mRenamedPackages = new ArrayMap<String, String>();
Fabrice Di Meglio62271722015-04-10 17:24:02 -0700369
370 // For every user, it is used to find the package name of the default Browser App.
371 final SparseArray<String> mDefaultBrowserApp = new SparseArray<String>();
372
Christopher Tatef0d6cb32015-07-10 17:44:53 -0700373 // App-link priority tracking, per-user
374 final SparseIntArray mNextAppLinkGeneration = new SparseIntArray();
375
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700376 final StringBuilder mReadMessages = new StringBuilder();
377
Kenny Root447106f2011-03-23 11:00:15 -0700378 /**
379 * Used to track packages that have a shared user ID that hasn't been read
380 * in yet.
381 * <p>
382 * TODO: make this just a local variable that is passed in during package
383 * scanning to make it less confusing.
384 */
385 private final ArrayList<PendingPackage> mPendingPackages = new ArrayList<PendingPackage>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700386
Amith Yamasani483f3b02012-03-13 16:08:00 -0700387 private final File mSystemDir;
Geremy Condraf1bcca82013-01-07 22:35:24 -0800388
dcashman55b10782014-04-09 14:20:38 -0700389 public final KeySetManagerService mKeySetManagerService = new KeySetManagerService(mPackages);
Geremy Condraf1bcca82013-01-07 22:35:24 -0800390
Svet Ganov12a692a2015-03-28 19:34:15 -0700391 Settings(Object lock) {
392 this(Environment.getDataDirectory(), lock);
Amith Yamasani483f3b02012-03-13 16:08:00 -0700393 }
394
Svet Ganov12a692a2015-03-28 19:34:15 -0700395 Settings(File dataDir, Object lock) {
Svetoslavc6d1c342015-02-26 14:44:43 -0800396 mLock = lock;
397
398 mRuntimePermissionsPersistence = new RuntimePermissionPersistence(mLock);
399
Amith Yamasani483f3b02012-03-13 16:08:00 -0700400 mSystemDir = new File(dataDir, "system");
401 mSystemDir.mkdirs();
402 FileUtils.setPermissions(mSystemDir.toString(),
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700403 FileUtils.S_IRWXU|FileUtils.S_IRWXG
404 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
405 -1, -1);
Amith Yamasani483f3b02012-03-13 16:08:00 -0700406 mSettingsFilename = new File(mSystemDir, "packages.xml");
407 mBackupSettingsFilename = new File(mSystemDir, "packages-backup.xml");
408 mPackageListFilename = new File(mSystemDir, "packages.list");
Jeff Sharkeyaebb65c2014-11-24 15:00:13 -0800409 FileUtils.setPermissions(mPackageListFilename, 0640, SYSTEM_UID, PACKAGE_INFO_GID);
Jeff Sharkey184a0102013-07-10 16:19:52 -0700410
Amith Yamasani483f3b02012-03-13 16:08:00 -0700411 // Deprecated: Needed for migration
412 mStoppedPackagesFilename = new File(mSystemDir, "packages-stopped.xml");
413 mBackupStoppedPackagesFilename = new File(mSystemDir, "packages-stopped-backup.xml");
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700414 }
415
Kenny Root447106f2011-03-23 11:00:15 -0700416 PackageSetting getPackageLPw(PackageParser.Package pkg, PackageSetting origPackage,
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700417 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Narayan Kamath4903f642014-08-11 13:33:45 +0100418 String legacyNativeLibraryPathString, String primaryCpuAbi, String secondaryCpuAbi,
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800419 int pkgFlags, int pkgPrivateFlags, UserHandle user, boolean add) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700420 final String name = pkg.packageName;
Svet Ganov354cd3c2015-12-17 11:35:04 -0800421 final String parentPackageName = (pkg.parentPackage != null)
422 ? pkg.parentPackage.packageName : null;
423
424 List<String> childPackageNames = null;
425 if (pkg.childPackages != null) {
426 final int childCount = pkg.childPackages.size();
427 childPackageNames = new ArrayList<>(childCount);
428 for (int i = 0; i < childCount; i++) {
429 String childPackageName = pkg.childPackages.get(i).packageName;
430 childPackageNames.add(childPackageName);
431 }
432 }
433
Kenny Root447106f2011-03-23 11:00:15 -0700434 PackageSetting p = getPackageLPw(name, origPackage, realName, sharedUser, codePath,
Jeff Sharkey84f12942014-07-10 17:48:11 -0700435 resourcePath, legacyNativeLibraryPathString, primaryCpuAbi, secondaryCpuAbi,
Svet Ganov354cd3c2015-12-17 11:35:04 -0800436 pkg.mVersionCode, pkgFlags, pkgPrivateFlags, user, add, true /* allowInstall */,
437 parentPackageName, childPackageNames);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700438 return p;
439 }
440
Kenny Root447106f2011-03-23 11:00:15 -0700441 PackageSetting peekPackageLPr(String name) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700442 return mPackages.get(name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700443 }
444
Christopher Tatee9fd1fa2015-09-15 16:43:07 -0700445 void setInstallStatus(String pkgName, final int status) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700446 PackageSetting p = mPackages.get(pkgName);
447 if(p != null) {
448 if(p.getInstallStatus() != status) {
449 p.setInstallStatus(status);
450 }
451 }
452 }
453
Christopher Tatee9fd1fa2015-09-15 16:43:07 -0700454 void applyPendingPermissionGrantsLPw(String packageName, int userId) {
455 ArrayMap<String, ArraySet<RestoredPermissionGrant>> grantsByPackage =
456 mRestoredUserGrants.get(userId);
457 if (grantsByPackage == null || grantsByPackage.size() == 0) {
458 return;
459 }
460
461 ArraySet<RestoredPermissionGrant> grants = grantsByPackage.get(packageName);
462 if (grants == null || grants.size() == 0) {
463 return;
464 }
465
466 final PackageSetting ps = mPackages.get(packageName);
467 if (ps == null) {
468 Slog.e(TAG, "Can't find supposedly installed package " + packageName);
469 return;
470 }
471 final PermissionsState perms = ps.getPermissionsState();
472
473 for (RestoredPermissionGrant grant : grants) {
474 BasePermission bp = mPermissions.get(grant.permissionName);
475 if (bp != null) {
476 if (grant.granted) {
477 perms.grantRuntimePermission(bp, userId);
478 }
479 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, grant.grantBits);
480 }
481 }
482
483 // And remove it from the pending-grant bookkeeping
484 grantsByPackage.remove(packageName);
485 if (grantsByPackage.size() < 1) {
486 mRestoredUserGrants.remove(userId);
487 }
488 writeRuntimePermissionsForUserLPr(userId, false);
489 }
490
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -0700491 void setInstallerPackageName(String pkgName, String installerPkgName) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700492 PackageSetting p = mPackages.get(pkgName);
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -0700493 if (p != null) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700494 p.setInstallerPackageName(installerPkgName);
495 }
496 }
497
Kenny Root447106f2011-03-23 11:00:15 -0700498 SharedUserSetting getSharedUserLPw(String name,
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800499 int pkgFlags, int pkgPrivateFlags, boolean create) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700500 SharedUserSetting s = mSharedUsers.get(name);
501 if (s == null) {
502 if (!create) {
503 return null;
504 }
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800505 s = new SharedUserSetting(name, pkgFlags, pkgPrivateFlags);
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800506 s.userId = newUserIdLPw(s);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700507 Log.i(PackageManagerService.TAG, "New shared user " + name + ": id=" + s.userId);
508 // < 0 means we couldn't assign a userid; fall out and return
509 // s, which is currently null
510 if (s.userId >= 0) {
511 mSharedUsers.put(name, s);
512 }
513 }
514
515 return s;
516 }
517
Narayan Kamathdf6d6dc2014-04-28 14:18:34 +0100518 Collection<SharedUserSetting> getAllSharedUsersLPw() {
519 return mSharedUsers.values();
520 }
521
Svet Ganov354cd3c2015-12-17 11:35:04 -0800522 boolean disableSystemPackageLPw(String name, boolean replaced) {
Kenny Root447106f2011-03-23 11:00:15 -0700523 final PackageSetting p = mPackages.get(name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700524 if(p == null) {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700525 Log.w(PackageManagerService.TAG, "Package " + name + " is not an installed package");
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700526 return false;
527 }
Kenny Root447106f2011-03-23 11:00:15 -0700528 final PackageSetting dp = mDisabledSysPackages.get(name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700529 // always make sure the system package code and resource paths dont change
Svet Ganov354cd3c2015-12-17 11:35:04 -0800530 if (dp == null && p.pkg != null && p.pkg.isSystemApp() && !p.pkg.isUpdatedSystemApp()) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700531 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
532 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
533 }
534 mDisabledSysPackages.put(name, p);
535
Svet Ganov354cd3c2015-12-17 11:35:04 -0800536 if (replaced) {
537 // a little trick... when we install the new package, we don't
538 // want to modify the existing PackageSetting for the built-in
539 // version. so at this point we need a new PackageSetting that
540 // is okay to muck with.
541 PackageSetting newp = new PackageSetting(p);
542 replacePackageLPw(name, newp);
Svet Ganov354cd3c2015-12-17 11:35:04 -0800543 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700544 return true;
545 }
546 return false;
547 }
548
Kenny Root447106f2011-03-23 11:00:15 -0700549 PackageSetting enableSystemPackageLPw(String name) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700550 PackageSetting p = mDisabledSysPackages.get(name);
551 if(p == null) {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700552 Log.w(PackageManagerService.TAG, "Package " + name + " is not disabled");
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700553 return null;
554 }
555 // Reset flag in ApplicationInfo object
556 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
557 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
558 }
Kenny Root447106f2011-03-23 11:00:15 -0700559 PackageSetting ret = addPackageLPw(name, p.realName, p.codePath, p.resourcePath,
Narayan Kamathff110bd2014-07-04 18:30:45 +0100560 p.legacyNativeLibraryPathString, p.primaryCpuAbiString,
Narayan Kamath4903f642014-08-11 13:33:45 +0100561 p.secondaryCpuAbiString, p.secondaryCpuAbiString,
Svet Ganov354cd3c2015-12-17 11:35:04 -0800562 p.appId, p.versionCode, p.pkgFlags, p.pkgPrivateFlags,
563 p.parentPackageName, p.childPackageNames);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700564 mDisabledSysPackages.remove(name);
565 return ret;
566 }
567
Kenny Rootc52d6fd2012-05-07 23:04:52 -0700568 boolean isDisabledSystemPackageLPr(String name) {
569 return mDisabledSysPackages.containsKey(name);
570 }
571
572 void removeDisabledSystemPackageLPw(String name) {
573 mDisabledSysPackages.remove(name);
574 }
575
Kenny Root447106f2011-03-23 11:00:15 -0700576 PackageSetting addPackageLPw(String name, String realName, File codePath, File resourcePath,
Svet Ganovf4ff39c2016-02-04 14:27:05 -0800577 String legacyNativeLibraryPathString, String primaryCpuAbiString,
578 String secondaryCpuAbiString, String cpuAbiOverrideString, int uid, int vc, int
579 pkgFlags, int pkgPrivateFlags, String parentPackageName,
580 List<String> childPackageNames) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700581 PackageSetting p = mPackages.get(name);
582 if (p != null) {
Amith Yamasani13593602012-03-22 16:16:17 -0700583 if (p.appId == uid) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700584 return p;
585 }
586 PackageManagerService.reportSettingsProblem(Log.ERROR,
587 "Adding duplicate package, keeping first: " + name);
588 return null;
589 }
Narayan Kamathff110bd2014-07-04 18:30:45 +0100590 p = new PackageSetting(name, realName, codePath, resourcePath,
Narayan Kamath4903f642014-08-11 13:33:45 +0100591 legacyNativeLibraryPathString, primaryCpuAbiString, secondaryCpuAbiString,
Svet Ganov354cd3c2015-12-17 11:35:04 -0800592 cpuAbiOverrideString, vc, pkgFlags, pkgPrivateFlags, parentPackageName,
593 childPackageNames);
Amith Yamasani13593602012-03-22 16:16:17 -0700594 p.appId = uid;
Kenny Root447106f2011-03-23 11:00:15 -0700595 if (addUserIdLPw(uid, p, name)) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700596 mPackages.put(name, p);
597 return p;
598 }
599 return null;
600 }
601
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800602 SharedUserSetting addSharedUserLPw(String name, int uid, int pkgFlags, int pkgPrivateFlags) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700603 SharedUserSetting s = mSharedUsers.get(name);
604 if (s != null) {
605 if (s.userId == uid) {
606 return s;
607 }
608 PackageManagerService.reportSettingsProblem(Log.ERROR,
609 "Adding duplicate shared user, keeping first: " + name);
610 return null;
611 }
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800612 s = new SharedUserSetting(name, pkgFlags, pkgPrivateFlags);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700613 s.userId = uid;
Kenny Root447106f2011-03-23 11:00:15 -0700614 if (addUserIdLPw(uid, s, name)) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700615 mSharedUsers.put(name, s);
616 return s;
617 }
618 return null;
619 }
620
Christopher Tate86b391c2013-09-13 16:58:36 -0700621 void pruneSharedUsersLPw() {
622 ArrayList<String> removeStage = new ArrayList<String>();
623 for (Map.Entry<String,SharedUserSetting> entry : mSharedUsers.entrySet()) {
624 final SharedUserSetting sus = entry.getValue();
Todd Kennedy68f67152015-10-21 13:09:10 -0700625 if (sus == null) {
626 removeStage.add(entry.getKey());
627 continue;
628 }
629 // remove packages that are no longer installed
630 for (Iterator<PackageSetting> iter = sus.packages.iterator(); iter.hasNext();) {
631 PackageSetting ps = iter.next();
632 if (mPackages.get(ps.name) == null) {
633 iter.remove();
634 }
635 }
636 if (sus.packages.size() == 0) {
Christopher Tate86b391c2013-09-13 16:58:36 -0700637 removeStage.add(entry.getKey());
638 }
639 }
640 for (int i = 0; i < removeStage.size(); i++) {
641 mSharedUsers.remove(removeStage.get(i));
642 }
643 }
644
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700645 // Transfer ownership of permissions from one package to another.
Kenny Root447106f2011-03-23 11:00:15 -0700646 void transferPermissionsLPw(String origPkg, String newPkg) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700647 // Transfer ownership of permissions to the new package.
648 for (int i=0; i<2; i++) {
Jeff Sharkey9f837a92014-10-24 12:07:24 -0700649 ArrayMap<String, BasePermission> permissions =
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700650 i == 0 ? mPermissionTrees : mPermissions;
651 for (BasePermission bp : permissions.values()) {
652 if (origPkg.equals(bp.sourcePackage)) {
653 if (PackageManagerService.DEBUG_UPGRADE) Log.v(PackageManagerService.TAG,
654 "Moving permission " + bp.name
655 + " from pkg " + bp.sourcePackage
656 + " to " + newPkg);
657 bp.sourcePackage = newPkg;
658 bp.packageSetting = null;
659 bp.perm = null;
660 if (bp.pendingInfo != null) {
661 bp.pendingInfo.packageName = newPkg;
662 }
663 bp.uid = 0;
Jeff Sharkey00f39042015-03-23 16:51:22 -0700664 bp.setGids(null, false);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700665 }
666 }
667 }
668 }
Amith Yamasani483f3b02012-03-13 16:08:00 -0700669
Kenny Root447106f2011-03-23 11:00:15 -0700670 private PackageSetting getPackageLPw(String name, PackageSetting origPackage,
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700671 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Svetoslavc6d1c342015-02-26 14:44:43 -0800672 String legacyNativeLibraryPathString, String primaryCpuAbiString,
673 String secondaryCpuAbiString, int vc, int pkgFlags, int pkgPrivateFlags,
Svet Ganov354cd3c2015-12-17 11:35:04 -0800674 UserHandle installUser, boolean add, boolean allowInstall, String parentPackage,
675 List<String> childPackageNames) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700676 PackageSetting p = mPackages.get(name);
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700677 UserManagerService userManager = UserManagerService.getInstance();
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700678 if (p != null) {
Narayan Kamathff110bd2014-07-04 18:30:45 +0100679 p.primaryCpuAbiString = primaryCpuAbiString;
680 p.secondaryCpuAbiString = secondaryCpuAbiString;
Svet Ganovf4ff39c2016-02-04 14:27:05 -0800681 if (childPackageNames != null) {
682 p.childPackageNames = new ArrayList<>(childPackageNames);
683 }
Narayan Kamath4903f642014-08-11 13:33:45 +0100684
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700685 if (!p.codePath.equals(codePath)) {
686 // Check to see if its a disabled system app
687 if ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
688 // This is an updated system app with versions in both system
689 // and data partition. Just let the most recent version
690 // take precedence.
Amith Yamasani483f3b02012-03-13 16:08:00 -0700691 Slog.w(PackageManagerService.TAG, "Trying to update system app code path from "
692 + p.codePathString + " to " + codePath.toString());
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700693 } else {
694 // Just a change in the code path is not an issue, but
695 // let's log a message about it.
Amith Yamasani483f3b02012-03-13 16:08:00 -0700696 Slog.i(PackageManagerService.TAG, "Package " + name + " codePath changed from "
697 + p.codePath + " to " + codePath + "; Retaining data and using new");
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700698 /*
699 * Since we've changed paths, we need to prefer the new
700 * native library path over the one stored in the
701 * package settings since we might have moved from
702 * internal to external storage or vice versa.
703 */
Narayan Kamathff110bd2014-07-04 18:30:45 +0100704 p.legacyNativeLibraryPathString = legacyNativeLibraryPathString;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700705 }
706 }
707 if (p.sharedUser != sharedUser) {
708 PackageManagerService.reportSettingsProblem(Log.WARN,
709 "Package " + name + " shared user changed from "
710 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
711 + " to "
712 + (sharedUser != null ? sharedUser.name : "<nothing>")
713 + "; replacing with new");
714 p = null;
715 } else {
Christopher Tate9f088202013-10-22 15:36:01 -0700716 // If what we are scanning is a system (and possibly privileged) package,
717 // then make it so, regardless of whether it was previously installed only
718 // in the data partition.
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800719 p.pkgFlags |= pkgFlags & ApplicationInfo.FLAG_SYSTEM;
720 p.pkgPrivateFlags |= pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700721 }
722 }
723 if (p == null) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700724 if (origPackage != null) {
725 // We are consuming the data from an existing package.
726 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
Narayan Kamath4903f642014-08-11 13:33:45 +0100727 legacyNativeLibraryPathString, primaryCpuAbiString, secondaryCpuAbiString,
Svet Ganov354cd3c2015-12-17 11:35:04 -0800728 null /* cpuAbiOverrideString */, vc, pkgFlags, pkgPrivateFlags,
729 parentPackage, childPackageNames);
Amith Yamasani483f3b02012-03-13 16:08:00 -0700730 if (PackageManagerService.DEBUG_UPGRADE) Log.v(PackageManagerService.TAG, "Package "
731 + name + " is adopting original package " + origPackage.name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700732 // Note that we will retain the new package's signature so
733 // that we can keep its data.
734 PackageSignatures s = p.signatures;
735 p.copyFrom(origPackage);
736 p.signatures = s;
737 p.sharedUser = origPackage.sharedUser;
Amith Yamasani13593602012-03-22 16:16:17 -0700738 p.appId = origPackage.appId;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700739 p.origPackage = origPackage;
Svet Ganove7af1942015-08-04 11:13:44 -0700740 p.getPermissionsState().copyFrom(origPackage.getPermissionsState());
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700741 mRenamedPackages.put(name, origPackage.name);
742 name = origPackage.name;
743 // Update new package state.
744 p.setTimeStamp(codePath.lastModified());
745 } else {
746 p = new PackageSetting(name, realName, codePath, resourcePath,
Narayan Kamath4903f642014-08-11 13:33:45 +0100747 legacyNativeLibraryPathString, primaryCpuAbiString, secondaryCpuAbiString,
Svet Ganov354cd3c2015-12-17 11:35:04 -0800748 null /* cpuAbiOverrideString */, vc, pkgFlags, pkgPrivateFlags,
749 parentPackage, childPackageNames);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700750 p.setTimeStamp(codePath.lastModified());
751 p.sharedUser = sharedUser;
752 // If this is not a system app, it starts out stopped.
753 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Kenny Root447106f2011-03-23 11:00:15 -0700754 if (DEBUG_STOPPED) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700755 RuntimeException e = new RuntimeException("here");
756 e.fillInStackTrace();
757 Slog.i(PackageManagerService.TAG, "Stopping package " + name, e);
758 }
Amith Yamasani483f3b02012-03-13 16:08:00 -0700759 List<UserInfo> users = getAllUsers();
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700760 final int installUserId = installUser != null ? installUser.getIdentifier() : 0;
Amith Yamasanif031f232012-10-26 15:35:21 -0700761 if (users != null && allowInstall) {
Amith Yamasani483f3b02012-03-13 16:08:00 -0700762 for (UserInfo user : users) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700763 // By default we consider this app to be installed
764 // for the user if no user has been specified (which
765 // means to leave it at its original value, and the
766 // original default value is true), or we are being
767 // asked to install for all users, or this is the
768 // user we are installing for.
769 final boolean installed = installUser == null
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700770 || (installUserId == UserHandle.USER_ALL
771 && !isAdbInstallDisallowed(userManager, user.id))
772 || installUserId == user.id;
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700773 p.setUserState(user.id, COMPONENT_ENABLED_STATE_DEFAULT,
774 installed,
775 true, // stopped,
776 true, // notLaunched
Amith Yamasanie5bcff62014-07-19 15:44:09 -0700777 false, // hidden
Andrei Stingaceanu1e283912015-11-26 15:26:28 +0000778 false, // suspended
Kenny Guyc13053b2014-05-29 14:17:17 +0100779 null, null, null,
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -0800780 false, // blockUninstall
Christopher Tatef0d6cb32015-07-10 17:44:53 -0700781 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
Amith Yamasani483f3b02012-03-13 16:08:00 -0700782 writePackageRestrictionsLPr(user.id);
783 }
784 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700785 }
786 if (sharedUser != null) {
Amith Yamasani13593602012-03-22 16:16:17 -0700787 p.appId = sharedUser.userId;
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800788 } else {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700789 // Clone the setting here for disabled system packages
790 PackageSetting dis = mDisabledSysPackages.get(name);
791 if (dis != null) {
792 // For disabled packages a new setting is created
793 // from the existing user id. This still has to be
794 // added to list of user id's
795 // Copy signatures from previous setting
796 if (dis.signatures.mSignatures != null) {
797 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
798 }
Amith Yamasani13593602012-03-22 16:16:17 -0700799 p.appId = dis.appId;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700800 // Clone permissions
Svetoslavc6d1c342015-02-26 14:44:43 -0800801 p.getPermissionsState().copyFrom(dis.getPermissionsState());
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700802 // Clone component info
Amith Yamasani483f3b02012-03-13 16:08:00 -0700803 List<UserInfo> users = getAllUsers();
804 if (users != null) {
805 for (UserInfo user : users) {
806 int userId = user.id;
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700807 p.setDisabledComponentsCopy(
808 dis.getDisabledComponents(userId), userId);
809 p.setEnabledComponentsCopy(
810 dis.getEnabledComponents(userId), userId);
Amith Yamasani483f3b02012-03-13 16:08:00 -0700811 }
812 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700813 // Add new setting to list of user ids
Amith Yamasani13593602012-03-22 16:16:17 -0700814 addUserIdLPw(p.appId, p, name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700815 } else {
816 // Assign new user id
Amith Yamasani13593602012-03-22 16:16:17 -0700817 p.appId = newUserIdLPw(p);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700818 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700819 }
820 }
Amith Yamasani13593602012-03-22 16:16:17 -0700821 if (p.appId < 0) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700822 PackageManagerService.reportSettingsProblem(Log.WARN,
823 "Package " + name + " could not be assigned a valid uid");
824 return null;
825 }
826 if (add) {
827 // Finish adding new package by adding it and updating shared
828 // user preferences
Kenny Root447106f2011-03-23 11:00:15 -0700829 addPackageSettingLPw(p, name, sharedUser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700830 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700831 } else {
Amith Yamasanif031f232012-10-26 15:35:21 -0700832 if (installUser != null && allowInstall) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700833 // The caller has explicitly specified the user they want this
834 // package installed for, and the package already exists.
835 // Make sure it conforms to the new request.
836 List<UserInfo> users = getAllUsers();
837 if (users != null) {
838 for (UserInfo user : users) {
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700839 if ((installUser.getIdentifier() == UserHandle.USER_ALL
840 && !isAdbInstallDisallowed(userManager, user.id))
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700841 || installUser.getIdentifier() == user.id) {
842 boolean installed = p.getInstalled(user.id);
843 if (!installed) {
844 p.setInstalled(true, user.id);
845 writePackageRestrictionsLPr(user.id);
846 }
847 }
848 }
849 }
850 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700851 }
852 return p;
853 }
854
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700855 boolean isAdbInstallDisallowed(UserManagerService userManager, int userId) {
856 return userManager.hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES,
857 userId);
858 }
859
Kenny Root447106f2011-03-23 11:00:15 -0700860 void insertPackageSettingLPw(PackageSetting p, PackageParser.Package pkg) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700861 p.pkg = pkg;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700862 // pkg.mSetEnabled = p.getEnabled(userId);
863 // pkg.mSetStopped = p.getStopped(userId);
Jeff Sharkeyb9f36742015-04-08 21:02:14 -0700864 final String volumeUuid = pkg.applicationInfo.volumeUuid;
Jeff Sharkeyd7460572014-07-06 20:44:55 -0700865 final String codePath = pkg.applicationInfo.getCodePath();
866 final String resourcePath = pkg.applicationInfo.getResourcePath();
Jeff Sharkey84f12942014-07-10 17:48:11 -0700867 final String legacyNativeLibraryPath = pkg.applicationInfo.nativeLibraryRootDir;
Jeff Sharkeyb9f36742015-04-08 21:02:14 -0700868 // Update volume if needed
869 if (!Objects.equals(volumeUuid, p.volumeUuid)) {
870 Slog.w(PackageManagerService.TAG, "Volume for " + p.pkg.packageName +
871 " changing from " + p.volumeUuid + " to " + volumeUuid);
872 p.volumeUuid = volumeUuid;
873 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700874 // Update code path if needed
Jeff Sharkey84f12942014-07-10 17:48:11 -0700875 if (!Objects.equals(codePath, p.codePathString)) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -0700876 Slog.w(PackageManagerService.TAG, "Code path for " + p.pkg.packageName +
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700877 " changing from " + p.codePathString + " to " + codePath);
878 p.codePath = new File(codePath);
879 p.codePathString = codePath;
880 }
881 //Update resource path if needed
Jeff Sharkey84f12942014-07-10 17:48:11 -0700882 if (!Objects.equals(resourcePath, p.resourcePathString)) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -0700883 Slog.w(PackageManagerService.TAG, "Resource path for " + p.pkg.packageName +
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700884 " changing from " + p.resourcePathString + " to " + resourcePath);
885 p.resourcePath = new File(resourcePath);
886 p.resourcePathString = resourcePath;
887 }
Narayan Kamathff110bd2014-07-04 18:30:45 +0100888 // Update the native library paths if needed
Jeff Sharkey84f12942014-07-10 17:48:11 -0700889 if (!Objects.equals(legacyNativeLibraryPath, p.legacyNativeLibraryPathString)) {
890 p.legacyNativeLibraryPathString = legacyNativeLibraryPath;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700891 }
Narayan Kamathff110bd2014-07-04 18:30:45 +0100892
Narayan Kamath9e289d72014-04-10 09:26:59 +0000893 // Update the required Cpu Abi
Narayan Kamathff110bd2014-07-04 18:30:45 +0100894 p.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
895 p.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
Narayan Kamath4903f642014-08-11 13:33:45 +0100896 p.cpuAbiOverrideString = pkg.cpuAbiOverride;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700897 // Update version code if needed
Amith Yamasani483f3b02012-03-13 16:08:00 -0700898 if (pkg.mVersionCode != p.versionCode) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700899 p.versionCode = pkg.mVersionCode;
900 }
Amith Yamasani483f3b02012-03-13 16:08:00 -0700901 // Update signatures if needed.
902 if (p.signatures.mSignatures == null) {
903 p.signatures.assignSignatures(pkg.mSignatures);
904 }
Kenny Root5455f682012-09-09 14:52:10 -0700905 // Update flags if needed.
906 if (pkg.applicationInfo.flags != p.pkgFlags) {
907 p.pkgFlags = pkg.applicationInfo.flags;
908 }
Amith Yamasani483f3b02012-03-13 16:08:00 -0700909 // If this app defines a shared user id initialize
910 // the shared user signatures as well.
911 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
912 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
913 }
Kenny Root447106f2011-03-23 11:00:15 -0700914 addPackageSettingLPw(p, pkg.packageName, p.sharedUser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700915 }
916
917 // Utility method that adds a PackageSetting to mPackages and
Christopher Tate6038d152015-06-17 13:07:46 -0700918 // completes updating the shared user attributes and any restored
919 // app link verification state
Kenny Root447106f2011-03-23 11:00:15 -0700920 private void addPackageSettingLPw(PackageSetting p, String name,
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700921 SharedUserSetting sharedUser) {
922 mPackages.put(name, p);
923 if (sharedUser != null) {
924 if (p.sharedUser != null && p.sharedUser != sharedUser) {
925 PackageManagerService.reportSettingsProblem(Log.ERROR,
926 "Package " + p.name + " was user "
927 + p.sharedUser + " but is now " + sharedUser
928 + "; I am not changing its files so it will probably fail!");
Ben Gruverdd72c9e2013-08-06 12:34:17 -0700929 p.sharedUser.removePackage(p);
Amith Yamasani13593602012-03-22 16:16:17 -0700930 } else if (p.appId != sharedUser.userId) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700931 PackageManagerService.reportSettingsProblem(Log.ERROR,
Amith Yamasani13593602012-03-22 16:16:17 -0700932 "Package " + p.name + " was user id " + p.appId
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700933 + " but is now user " + sharedUser
934 + " with id " + sharedUser.userId
935 + "; I am not changing its files so it will probably fail!");
936 }
937
Ben Gruverdd72c9e2013-08-06 12:34:17 -0700938 sharedUser.addPackage(p);
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700939 p.sharedUser = sharedUser;
Amith Yamasani13593602012-03-22 16:16:17 -0700940 p.appId = sharedUser.userId;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700941 }
Svet Ganove7af1942015-08-04 11:13:44 -0700942
943 // If the we know about this user id, we have to update it as it
944 // has to point to the same PackageSetting instance as the package.
945 Object userIdPs = getUserIdLPr(p.appId);
946 if (sharedUser == null) {
947 if (userIdPs != null && userIdPs != p) {
948 replaceUserIdLPw(p.appId, p);
949 }
950 } else {
951 if (userIdPs != null && userIdPs != sharedUser) {
952 replaceUserIdLPw(p.appId, sharedUser);
953 }
954 }
955
Christopher Tate6038d152015-06-17 13:07:46 -0700956 IntentFilterVerificationInfo ivi = mRestoredIntentFilterVerifications.get(name);
957 if (ivi != null) {
958 if (DEBUG_DOMAIN_VERIFICATION) {
959 Slog.i(TAG, "Applying restored IVI for " + name + " : " + ivi.getStatusString());
960 }
961 mRestoredIntentFilterVerifications.remove(name);
962 p.setIntentFilterVerificationInfo(ivi);
963 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700964 }
965
966 /*
967 * Update the shared user setting when a package using
968 * specifying the shared user id is removed. The gids
969 * associated with each permission of the deleted package
970 * are removed from the shared user's gid list only if its
971 * not in use by other permissions of packages in the
972 * shared user setting.
973 */
Svetoslavc6d1c342015-02-26 14:44:43 -0800974 int updateSharedUserPermsLPw(PackageSetting deletedPs, int userId) {
Kenny Root447106f2011-03-23 11:00:15 -0700975 if ((deletedPs == null) || (deletedPs.pkg == null)) {
976 Slog.i(PackageManagerService.TAG,
977 "Trying to update info for null package. Just ignoring");
Svetoslavc6d1c342015-02-26 14:44:43 -0800978 return UserHandle.USER_NULL;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700979 }
Svetoslavc6d1c342015-02-26 14:44:43 -0800980
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700981 // No sharedUserId
982 if (deletedPs.sharedUser == null) {
Svetoslavc6d1c342015-02-26 14:44:43 -0800983 return UserHandle.USER_NULL;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700984 }
Svetoslavc6d1c342015-02-26 14:44:43 -0800985
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700986 SharedUserSetting sus = deletedPs.sharedUser;
Svetoslavc6d1c342015-02-26 14:44:43 -0800987
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700988 // Update permissions
Kenny Root447106f2011-03-23 11:00:15 -0700989 for (String eachPerm : deletedPs.pkg.requestedPermissions) {
Svetoslavc6d1c342015-02-26 14:44:43 -0800990 BasePermission bp = mPermissions.get(eachPerm);
991 if (bp == null) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700992 continue;
993 }
Svetoslavc6d1c342015-02-26 14:44:43 -0800994
Svetoslavc6d1c342015-02-26 14:44:43 -0800995 // Check if another package in the shared user needs the permission.
Svetoslav4a5f4a22015-07-07 18:18:15 -0700996 boolean used = false;
Svetoslavc6d1c342015-02-26 14:44:43 -0800997 for (PackageSetting pkg : sus.packages) {
998 if (pkg.pkg != null
999 && !pkg.pkg.packageName.equals(deletedPs.pkg.packageName)
1000 && pkg.pkg.requestedPermissions.contains(eachPerm)) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001001 used = true;
1002 break;
1003 }
1004 }
Svetoslav4a5f4a22015-07-07 18:18:15 -07001005 if (used) {
1006 continue;
1007 }
Svetoslavc6d1c342015-02-26 14:44:43 -08001008
Svetoslav4a5f4a22015-07-07 18:18:15 -07001009 PermissionsState permissionsState = sus.getPermissionsState();
1010 PackageSetting disabledPs = getDisabledSystemPkgLPr(deletedPs.pkg.packageName);
Svet Ganov8c7f7002015-05-07 10:48:44 -07001011
Svetoslav4a5f4a22015-07-07 18:18:15 -07001012 // If the package is shadowing is a disabled system package,
1013 // do not drop permissions that the shadowed package requests.
1014 if (disabledPs != null) {
1015 boolean reqByDisabledSysPkg = false;
1016 for (String permission : disabledPs.pkg.requestedPermissions) {
1017 if (permission.equals(eachPerm)) {
1018 reqByDisabledSysPkg = true;
1019 break;
1020 }
Svetoslavc6d1c342015-02-26 14:44:43 -08001021 }
Svetoslav4a5f4a22015-07-07 18:18:15 -07001022 if (reqByDisabledSysPkg) {
1023 continue;
Svetoslavc6d1c342015-02-26 14:44:43 -08001024 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001025 }
Svetoslav4a5f4a22015-07-07 18:18:15 -07001026
1027 // Try to revoke as an install permission which is for all users.
1028 // The package is gone - no need to keep flags for applying policy.
1029 permissionsState.updatePermissionFlags(bp, userId,
1030 PackageManager.MASK_PERMISSION_FLAGS, 0);
1031
1032 if (permissionsState.revokeInstallPermission(bp) ==
1033 PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED) {
1034 return UserHandle.USER_ALL;
1035 }
1036
1037 // Try to revoke as an install permission which is per user.
1038 if (permissionsState.revokeRuntimePermission(bp, userId) ==
1039 PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED) {
1040 return userId;
1041 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001042 }
Svetoslavc6d1c342015-02-26 14:44:43 -08001043
1044 return UserHandle.USER_NULL;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001045 }
1046
Kenny Root447106f2011-03-23 11:00:15 -07001047 int removePackageLPw(String name) {
1048 final PackageSetting p = mPackages.get(name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001049 if (p != null) {
1050 mPackages.remove(name);
1051 if (p.sharedUser != null) {
Ben Gruverdd72c9e2013-08-06 12:34:17 -07001052 p.sharedUser.removePackage(p);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001053 if (p.sharedUser.packages.size() == 0) {
1054 mSharedUsers.remove(p.sharedUser.name);
Kenny Root447106f2011-03-23 11:00:15 -07001055 removeUserIdLPw(p.sharedUser.userId);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001056 return p.sharedUser.userId;
1057 }
1058 } else {
Amith Yamasani13593602012-03-22 16:16:17 -07001059 removeUserIdLPw(p.appId);
1060 return p.appId;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001061 }
1062 }
1063 return -1;
1064 }
1065
Kenny Root447106f2011-03-23 11:00:15 -07001066 private void replacePackageLPw(String name, PackageSetting newp) {
1067 final PackageSetting p = mPackages.get(name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001068 if (p != null) {
1069 if (p.sharedUser != null) {
Ben Gruverdd72c9e2013-08-06 12:34:17 -07001070 p.sharedUser.removePackage(p);
1071 p.sharedUser.addPackage(newp);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001072 } else {
Amith Yamasani13593602012-03-22 16:16:17 -07001073 replaceUserIdLPw(p.appId, newp);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001074 }
1075 }
1076 mPackages.put(name, newp);
1077 }
1078
Kenny Root447106f2011-03-23 11:00:15 -07001079 private boolean addUserIdLPw(int uid, Object obj, Object name) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08001080 if (uid > Process.LAST_APPLICATION_UID) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001081 return false;
1082 }
1083
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08001084 if (uid >= Process.FIRST_APPLICATION_UID) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001085 int N = mUserIds.size();
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08001086 final int index = uid - Process.FIRST_APPLICATION_UID;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001087 while (index >= N) {
1088 mUserIds.add(null);
1089 N++;
1090 }
1091 if (mUserIds.get(index) != null) {
1092 PackageManagerService.reportSettingsProblem(Log.ERROR,
1093 "Adding duplicate user id: " + uid
1094 + " name=" + name);
1095 return false;
1096 }
1097 mUserIds.set(index, obj);
1098 } else {
1099 if (mOtherUserIds.get(uid) != null) {
1100 PackageManagerService.reportSettingsProblem(Log.ERROR,
1101 "Adding duplicate shared id: " + uid
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001102 + " name=" + name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001103 return false;
1104 }
1105 mOtherUserIds.put(uid, obj);
1106 }
1107 return true;
1108 }
1109
Kenny Root447106f2011-03-23 11:00:15 -07001110 public Object getUserIdLPr(int uid) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08001111 if (uid >= Process.FIRST_APPLICATION_UID) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001112 final int N = mUserIds.size();
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08001113 final int index = uid - Process.FIRST_APPLICATION_UID;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001114 return index < N ? mUserIds.get(index) : null;
1115 } else {
1116 return mOtherUserIds.get(uid);
1117 }
1118 }
1119
Kenny Root447106f2011-03-23 11:00:15 -07001120 private void removeUserIdLPw(int uid) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08001121 if (uid >= Process.FIRST_APPLICATION_UID) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001122 final int N = mUserIds.size();
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08001123 final int index = uid - Process.FIRST_APPLICATION_UID;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001124 if (index < N) mUserIds.set(index, null);
1125 } else {
1126 mOtherUserIds.remove(uid);
1127 }
Geremy Condra12c18382013-03-06 16:49:06 -08001128 setFirstAvailableUid(uid+1);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001129 }
1130
Kenny Root447106f2011-03-23 11:00:15 -07001131 private void replaceUserIdLPw(int uid, Object obj) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08001132 if (uid >= Process.FIRST_APPLICATION_UID) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001133 final int N = mUserIds.size();
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08001134 final int index = uid - Process.FIRST_APPLICATION_UID;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001135 if (index < N) mUserIds.set(index, obj);
1136 } else {
1137 mOtherUserIds.put(uid, obj);
1138 }
1139 }
1140
Dianne Hackborn63092712012-10-07 14:45:35 -07001141 PreferredIntentResolver editPreferredActivitiesLPw(int userId) {
1142 PreferredIntentResolver pir = mPreferredActivities.get(userId);
1143 if (pir == null) {
1144 pir = new PreferredIntentResolver();
1145 mPreferredActivities.put(userId, pir);
1146 }
1147 return pir;
1148 }
1149
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001150 PersistentPreferredIntentResolver editPersistentPreferredActivitiesLPw(int userId) {
1151 PersistentPreferredIntentResolver ppir = mPersistentPreferredActivities.get(userId);
1152 if (ppir == null) {
1153 ppir = new PersistentPreferredIntentResolver();
1154 mPersistentPreferredActivities.put(userId, ppir);
1155 }
1156 return ppir;
1157 }
1158
Nicolas Prevot81948992014-05-16 18:25:26 +01001159 CrossProfileIntentResolver editCrossProfileIntentResolverLPw(int userId) {
1160 CrossProfileIntentResolver cpir = mCrossProfileIntentResolvers.get(userId);
1161 if (cpir == null) {
1162 cpir = new CrossProfileIntentResolver();
1163 mCrossProfileIntentResolvers.put(userId, cpir);
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001164 }
Nicolas Prevot81948992014-05-16 18:25:26 +01001165 return cpir;
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001166 }
1167
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001168 /**
1169 * The following functions suppose that you have a lock for managing access to the
1170 * mIntentFiltersVerifications map.
1171 */
1172
1173 /* package protected */
1174 IntentFilterVerificationInfo getIntentFilterVerificationLPr(String packageName) {
1175 PackageSetting ps = mPackages.get(packageName);
1176 if (ps == null) {
Christopher Tate72c10a22015-06-12 18:31:24 -07001177 if (DEBUG_DOMAIN_VERIFICATION) {
1178 Slog.w(PackageManagerService.TAG, "No package known: " + packageName);
1179 }
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001180 return null;
1181 }
1182 return ps.getIntentFilterVerificationInfo();
1183 }
1184
1185 /* package protected */
Fabrice Di Meglio7d014ce2015-04-08 16:17:46 -07001186 IntentFilterVerificationInfo createIntentFilterVerificationIfNeededLPw(String packageName,
Fabrice Di Meglio07885952015-04-06 19:41:28 -07001187 ArrayList<String> domains) {
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001188 PackageSetting ps = mPackages.get(packageName);
1189 if (ps == null) {
Christopher Tate72c10a22015-06-12 18:31:24 -07001190 if (DEBUG_DOMAIN_VERIFICATION) {
1191 Slog.w(PackageManagerService.TAG, "No package known: " + packageName);
1192 }
Fabrice Di Meglio7d014ce2015-04-08 16:17:46 -07001193 return null;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001194 }
Fabrice Di Meglio7d014ce2015-04-08 16:17:46 -07001195 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
1196 if (ivi == null) {
1197 ivi = new IntentFilterVerificationInfo(packageName, domains);
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001198 ps.setIntentFilterVerificationInfo(ivi);
Christopher Tate72c10a22015-06-12 18:31:24 -07001199 if (DEBUG_DOMAIN_VERIFICATION) {
1200 Slog.d(PackageManagerService.TAG,
1201 "Creating new IntentFilterVerificationInfo for pkg: " + packageName);
1202 }
Fabrice Di Meglio1de3f0d2015-04-29 19:42:41 -07001203 } else {
1204 ivi.setDomains(domains);
Christopher Tate72c10a22015-06-12 18:31:24 -07001205 if (DEBUG_DOMAIN_VERIFICATION) {
1206 Slog.d(PackageManagerService.TAG,
1207 "Setting domains to existing IntentFilterVerificationInfo for pkg: " +
1208 packageName + " and with domains: " + ivi.getDomainsString());
1209 }
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001210 }
Fabrice Di Meglio7d014ce2015-04-08 16:17:46 -07001211 return ivi;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001212 }
1213
1214 int getIntentFilterVerificationStatusLPr(String packageName, int userId) {
1215 PackageSetting ps = mPackages.get(packageName);
1216 if (ps == null) {
Christopher Tate72c10a22015-06-12 18:31:24 -07001217 if (DEBUG_DOMAIN_VERIFICATION) {
1218 Slog.w(PackageManagerService.TAG, "No package known: " + packageName);
1219 }
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001220 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1221 }
Christopher Tated85a6642015-07-17 15:39:08 -07001222 return (int)(ps.getDomainVerificationStatusForUser(userId) >> 32);
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001223 }
1224
Christopher Tatef0d6cb32015-07-10 17:44:53 -07001225 boolean updateIntentFilterVerificationStatusLPw(String packageName, final int status, int userId) {
Fabrice Di Meglio07885952015-04-06 19:41:28 -07001226 // Update the status for the current package
1227 PackageSetting current = mPackages.get(packageName);
1228 if (current == null) {
Christopher Tate72c10a22015-06-12 18:31:24 -07001229 if (DEBUG_DOMAIN_VERIFICATION) {
1230 Slog.w(PackageManagerService.TAG, "No package known: " + packageName);
1231 }
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001232 return false;
1233 }
Christopher Tate050aee22015-07-01 16:50:43 -07001234
Christopher Tatef0d6cb32015-07-10 17:44:53 -07001235 final int alwaysGeneration;
1236 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
1237 alwaysGeneration = mNextAppLinkGeneration.get(userId) + 1;
1238 mNextAppLinkGeneration.put(userId, alwaysGeneration);
1239 } else {
1240 alwaysGeneration = 0;
1241 }
1242
1243 current.setDomainVerificationStatusForUser(status, alwaysGeneration, userId);
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001244 return true;
1245 }
1246
1247 /**
Fabrice Di Meglio07885952015-04-06 19:41:28 -07001248 * Used for Settings App and PackageManagerService dump. Should be read only.
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001249 */
1250 List<IntentFilterVerificationInfo> getIntentFilterVerificationsLPr(
1251 String packageName) {
1252 if (packageName == null) {
1253 return Collections.<IntentFilterVerificationInfo>emptyList();
1254 }
1255 ArrayList<IntentFilterVerificationInfo> result = new ArrayList<>();
1256 for (PackageSetting ps : mPackages.values()) {
1257 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
1258 if (ivi == null || TextUtils.isEmpty(ivi.getPackageName()) ||
1259 !ivi.getPackageName().equalsIgnoreCase(packageName)) {
1260 continue;
1261 }
1262 result.add(ivi);
1263 }
1264 return result;
1265 }
1266
Fabrice Di Meglio1f09b8c2015-05-06 18:51:21 -07001267 boolean removeIntentFilterVerificationLPw(String packageName, int userId) {
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001268 PackageSetting ps = mPackages.get(packageName);
1269 if (ps == null) {
Christopher Tate72c10a22015-06-12 18:31:24 -07001270 if (DEBUG_DOMAIN_VERIFICATION) {
1271 Slog.w(PackageManagerService.TAG, "No package known: " + packageName);
1272 }
Fabrice Di Meglio1f09b8c2015-05-06 18:51:21 -07001273 return false;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001274 }
1275 ps.clearDomainVerificationStatusForUser(userId);
Fabrice Di Meglio1f09b8c2015-05-06 18:51:21 -07001276 return true;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001277 }
1278
Fabrice Di Meglio1f09b8c2015-05-06 18:51:21 -07001279 boolean removeIntentFilterVerificationLPw(String packageName, int[] userIds) {
1280 boolean result = false;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001281 for (int userId : userIds) {
Fabrice Di Meglio1f09b8c2015-05-06 18:51:21 -07001282 result |= removeIntentFilterVerificationLPw(packageName, userId);
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001283 }
Fabrice Di Meglio1f09b8c2015-05-06 18:51:21 -07001284 return result;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001285 }
1286
Christopher Tatedb3fe812015-06-24 16:15:48 -07001287 boolean setDefaultBrowserPackageNameLPw(String packageName, int userId) {
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001288 if (userId == UserHandle.USER_ALL) {
1289 return false;
1290 }
1291 mDefaultBrowserApp.put(userId, packageName);
1292 writePackageRestrictionsLPr(userId);
1293 return true;
1294 }
1295
1296 String getDefaultBrowserPackageNameLPw(int userId) {
1297 return (userId == UserHandle.USER_ALL) ? null : mDefaultBrowserApp.get(userId);
1298 }
1299
Amith Yamasani483f3b02012-03-13 16:08:00 -07001300 private File getUserPackagesStateFile(int userId) {
Svetoslavc6d1c342015-02-26 14:44:43 -08001301 // TODO: Implement a cleaner solution when adding tests.
1302 // This instead of Environment.getUserSystemDirectory(userId) to support testing.
1303 File userDir = new File(new File(mSystemDir, "users"), Integer.toString(userId));
1304 return new File(userDir, "package-restrictions.xml");
1305 }
1306
1307 private File getUserRuntimePermissionsFile(int userId) {
1308 // TODO: Implement a cleaner solution when adding tests.
1309 // This instead of Environment.getUserSystemDirectory(userId) to support testing.
1310 File userDir = new File(new File(mSystemDir, "users"), Integer.toString(userId));
1311 return new File(userDir, RUNTIME_PERMISSIONS_FILE_NAME);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001312 }
1313
1314 private File getUserPackagesStateBackupFile(int userId) {
Amith Yamasani61f57372012-08-31 12:12:28 -07001315 return new File(Environment.getUserSystemDirectory(userId),
1316 "package-restrictions-backup.xml");
Amith Yamasani483f3b02012-03-13 16:08:00 -07001317 }
1318
1319 void writeAllUsersPackageRestrictionsLPr() {
1320 List<UserInfo> users = getAllUsers();
1321 if (users == null) return;
1322
1323 for (UserInfo user : users) {
1324 writePackageRestrictionsLPr(user.id);
1325 }
1326 }
1327
Svetoslavc6d1c342015-02-26 14:44:43 -08001328 void writeAllRuntimePermissionsLPr() {
1329 for (int userId : UserManagerService.getInstance().getUserIds()) {
1330 mRuntimePermissionsPersistence.writePermissionsForUserAsyncLPr(userId);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001331 }
1332 }
1333
Svet Ganovba3ba812015-06-26 10:54:06 -07001334 boolean areDefaultRuntimePermissionsGrantedLPr(int userId) {
1335 return mRuntimePermissionsPersistence
1336 .areDefaultRuntimPermissionsGrantedLPr(userId);
1337 }
1338
1339 void onDefaultRuntimePermissionsGrantedLPr(int userId) {
1340 mRuntimePermissionsPersistence
1341 .onDefaultRuntimePermissionsGrantedLPr(userId);
1342 }
1343
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07001344 public VersionInfo findOrCreateVersion(String volumeUuid) {
1345 VersionInfo ver = mVersion.get(volumeUuid);
1346 if (ver == null) {
1347 ver = new VersionInfo();
1348 ver.forceCurrent();
1349 mVersion.put(volumeUuid, ver);
1350 }
1351 return ver;
Kenny Rootc1c0d3c2014-04-24 13:36:40 -07001352 }
1353
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07001354 public VersionInfo getInternalVersion() {
1355 return mVersion.get(StorageManager.UUID_PRIVATE_INTERNAL);
Kenny Rootc1c0d3c2014-04-24 13:36:40 -07001356 }
1357
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07001358 public VersionInfo getExternalVersion() {
1359 return mVersion.get(StorageManager.UUID_PRIMARY_PHYSICAL);
Kenny Rootc1c0d3c2014-04-24 13:36:40 -07001360 }
1361
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07001362 public void onVolumeForgotten(String fsUuid) {
1363 mVersion.remove(fsUuid);
Kenny Rootc1c0d3c2014-04-24 13:36:40 -07001364 }
1365
Christopher Tatee012a232015-04-01 17:18:50 -07001366 /**
1367 * Applies the preferred activity state described by the given XML. This code
1368 * also supports the restore-from-backup code path.
1369 *
1370 * @see PreferredActivityBackupHelper
1371 */
1372 void readPreferredActivitiesLPw(XmlPullParser parser, int userId)
Dianne Hackborn63092712012-10-07 14:45:35 -07001373 throws XmlPullParserException, IOException {
1374 int outerDepth = parser.getDepth();
1375 int type;
1376 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1377 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1378 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1379 continue;
1380 }
1381
1382 String tagName = parser.getName();
1383 if (tagName.equals(TAG_ITEM)) {
1384 PreferredActivity pa = new PreferredActivity(parser);
1385 if (pa.mPref.getParseError() == null) {
1386 editPreferredActivitiesLPw(userId).addFilter(pa);
1387 } else {
1388 PackageManagerService.reportSettingsProblem(Log.WARN,
1389 "Error in package manager settings: <preferred-activity> "
1390 + pa.mPref.getParseError() + " at "
1391 + parser.getPositionDescription());
1392 }
1393 } else {
1394 PackageManagerService.reportSettingsProblem(Log.WARN,
1395 "Unknown element under <preferred-activities>: " + parser.getName());
1396 XmlUtils.skipCurrentTag(parser);
1397 }
1398 }
1399 }
1400
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001401 private void readPersistentPreferredActivitiesLPw(XmlPullParser parser, int userId)
1402 throws XmlPullParserException, IOException {
1403 int outerDepth = parser.getDepth();
1404 int type;
1405 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1406 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1407 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1408 continue;
1409 }
1410 String tagName = parser.getName();
1411 if (tagName.equals(TAG_ITEM)) {
1412 PersistentPreferredActivity ppa = new PersistentPreferredActivity(parser);
1413 editPersistentPreferredActivitiesLPw(userId).addFilter(ppa);
1414 } else {
1415 PackageManagerService.reportSettingsProblem(Log.WARN,
Sander Alewijnseaf597622014-03-20 18:44:57 +00001416 "Unknown element under <" + TAG_PERSISTENT_PREFERRED_ACTIVITIES + ">: "
1417 + parser.getName());
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001418 XmlUtils.skipCurrentTag(parser);
1419 }
1420 }
1421 }
1422
Nicolas Prevot81948992014-05-16 18:25:26 +01001423 private void readCrossProfileIntentFiltersLPw(XmlPullParser parser, int userId)
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001424 throws XmlPullParserException, IOException {
1425 int outerDepth = parser.getDepth();
1426 int type;
1427 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1428 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1429 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1430 continue;
1431 }
Christopher Tate6038d152015-06-17 13:07:46 -07001432 final String tagName = parser.getName();
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001433 if (tagName.equals(TAG_ITEM)) {
Nicolas Prevot81948992014-05-16 18:25:26 +01001434 CrossProfileIntentFilter cpif = new CrossProfileIntentFilter(parser);
1435 editCrossProfileIntentResolverLPw(userId).addFilter(cpif);
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001436 } else {
Nicolas Prevot81948992014-05-16 18:25:26 +01001437 String msg = "Unknown element under " + TAG_CROSS_PROFILE_INTENT_FILTERS + ": " +
Christopher Tate6038d152015-06-17 13:07:46 -07001438 tagName;
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001439 PackageManagerService.reportSettingsProblem(Log.WARN, msg);
1440 XmlUtils.skipCurrentTag(parser);
1441 }
1442 }
1443 }
1444
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001445 private void readDomainVerificationLPw(XmlPullParser parser, PackageSettingBase packageSetting)
1446 throws XmlPullParserException, IOException {
1447 IntentFilterVerificationInfo ivi = new IntentFilterVerificationInfo(parser);
1448 packageSetting.setIntentFilterVerificationInfo(ivi);
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001449 Log.d(TAG, "Read domain verification for package: " + ivi.getPackageName());
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001450 }
1451
Christopher Tate6038d152015-06-17 13:07:46 -07001452 private void readRestoredIntentFilterVerifications(XmlPullParser parser)
1453 throws XmlPullParserException, IOException {
1454 int outerDepth = parser.getDepth();
1455 int type;
1456 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1457 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1458 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1459 continue;
1460 }
1461 final String tagName = parser.getName();
1462 if (tagName.equals(TAG_DOMAIN_VERIFICATION)) {
1463 IntentFilterVerificationInfo ivi = new IntentFilterVerificationInfo(parser);
1464 if (DEBUG_DOMAIN_VERIFICATION) {
1465 Slog.i(TAG, "Restored IVI for " + ivi.getPackageName()
1466 + " status=" + ivi.getStatusString());
1467 }
1468 mRestoredIntentFilterVerifications.put(ivi.getPackageName(), ivi);
1469 } else {
1470 Slog.w(TAG, "Unknown element: " + tagName);
1471 XmlUtils.skipCurrentTag(parser);
1472 }
1473 }
1474 }
1475
1476 void readDefaultAppsLPw(XmlPullParser parser, int userId)
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001477 throws XmlPullParserException, IOException {
1478 int outerDepth = parser.getDepth();
1479 int type;
1480 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1481 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1482 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1483 continue;
1484 }
1485 String tagName = parser.getName();
1486 if (tagName.equals(TAG_DEFAULT_BROWSER)) {
1487 String packageName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
1488 mDefaultBrowserApp.put(userId, packageName);
1489 } else {
1490 String msg = "Unknown element under " + TAG_DEFAULT_APPS + ": " +
1491 parser.getName();
1492 PackageManagerService.reportSettingsProblem(Log.WARN, msg);
1493 XmlUtils.skipCurrentTag(parser);
1494 }
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001495 }
1496 }
1497
Amith Yamasani483f3b02012-03-13 16:08:00 -07001498 void readPackageRestrictionsLPr(int userId) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001499 if (DEBUG_MU) {
1500 Log.i(TAG, "Reading package restrictions for user=" + userId);
1501 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07001502 FileInputStream str = null;
1503 File userPackagesStateFile = getUserPackagesStateFile(userId);
1504 File backupFile = getUserPackagesStateBackupFile(userId);
1505 if (backupFile.exists()) {
1506 try {
1507 str = new FileInputStream(backupFile);
1508 mReadMessages.append("Reading from backup stopped packages file\n");
1509 PackageManagerService.reportSettingsProblem(Log.INFO,
1510 "Need to read from backup stopped packages file");
1511 if (userPackagesStateFile.exists()) {
1512 // If both the backup and normal file exist, we
1513 // ignore the normal one since it might have been
1514 // corrupted.
1515 Slog.w(PackageManagerService.TAG, "Cleaning up stopped packages file "
1516 + userPackagesStateFile);
1517 userPackagesStateFile.delete();
1518 }
1519 } catch (java.io.IOException e) {
1520 // We'll try for the normal settings file.
1521 }
1522 }
1523
1524 try {
1525 if (str == null) {
1526 if (!userPackagesStateFile.exists()) {
1527 mReadMessages.append("No stopped packages file found\n");
1528 PackageManagerService.reportSettingsProblem(Log.INFO,
1529 "No stopped packages file; "
1530 + "assuming all started");
1531 // At first boot, make sure no packages are stopped.
1532 // We usually want to have third party apps initialize
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001533 // in the stopped state, but not at first boot. Also
1534 // consider all applications to be installed.
Amith Yamasani483f3b02012-03-13 16:08:00 -07001535 for (PackageSetting pkg : mPackages.values()) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001536 pkg.setUserState(userId, COMPONENT_ENABLED_STATE_DEFAULT,
1537 true, // installed
1538 false, // stopped
1539 false, // notLaunched
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001540 false, // hidden
Andrei Stingaceanu1e283912015-11-26 15:26:28 +00001541 false, // suspended
Kenny Guyc13053b2014-05-29 14:17:17 +01001542 null, null, null,
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001543 false, // blockUninstall
Christopher Tatef0d6cb32015-07-10 17:44:53 -07001544 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001545 }
1546 return;
1547 }
1548 str = new FileInputStream(userPackagesStateFile);
1549 }
1550 final XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001551 parser.setInput(str, StandardCharsets.UTF_8.name());
Amith Yamasani483f3b02012-03-13 16:08:00 -07001552
1553 int type;
1554 while ((type=parser.next()) != XmlPullParser.START_TAG
1555 && type != XmlPullParser.END_DOCUMENT) {
1556 ;
1557 }
1558
1559 if (type != XmlPullParser.START_TAG) {
1560 mReadMessages.append("No start tag found in package restrictions file\n");
1561 PackageManagerService.reportSettingsProblem(Log.WARN,
1562 "No start tag found in package manager stopped packages");
1563 return;
1564 }
1565
Christopher Tatef0d6cb32015-07-10 17:44:53 -07001566 int maxAppLinkGeneration = 0;
1567
Amith Yamasani483f3b02012-03-13 16:08:00 -07001568 int outerDepth = parser.getDepth();
1569 PackageSetting ps = null;
1570 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1571 && (type != XmlPullParser.END_TAG
1572 || parser.getDepth() > outerDepth)) {
1573 if (type == XmlPullParser.END_TAG
1574 || type == XmlPullParser.TEXT) {
1575 continue;
1576 }
1577
1578 String tagName = parser.getName();
1579 if (tagName.equals(TAG_PACKAGE)) {
1580 String name = parser.getAttributeValue(null, ATTR_NAME);
1581 ps = mPackages.get(name);
1582 if (ps == null) {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001583 Slog.w(PackageManagerService.TAG, "No package known for stopped package "
Amith Yamasani483f3b02012-03-13 16:08:00 -07001584 + name);
1585 XmlUtils.skipCurrentTag(parser);
1586 continue;
1587 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001588 final String enabledStr = parser.getAttributeValue(null, ATTR_ENABLED);
1589 final int enabled = enabledStr == null
1590 ? COMPONENT_ENABLED_STATE_DEFAULT : Integer.parseInt(enabledStr);
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07001591 final String enabledCaller = parser.getAttributeValue(null,
1592 ATTR_ENABLED_CALLER);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001593 final String installedStr = parser.getAttributeValue(null, ATTR_INSTALLED);
1594 final boolean installed = installedStr == null
1595 ? true : Boolean.parseBoolean(installedStr);
1596 final String stoppedStr = parser.getAttributeValue(null, ATTR_STOPPED);
1597 final boolean stopped = stoppedStr == null
1598 ? false : Boolean.parseBoolean(stoppedStr);
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001599 // For backwards compatibility with the previous name of "blocked", which
1600 // now means hidden, read the old attribute as well.
Amith Yamasani655d0e22013-06-12 14:19:10 -07001601 final String blockedStr = parser.getAttributeValue(null, ATTR_BLOCKED);
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001602 boolean hidden = blockedStr == null
Amith Yamasani655d0e22013-06-12 14:19:10 -07001603 ? false : Boolean.parseBoolean(blockedStr);
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001604 final String hiddenStr = parser.getAttributeValue(null, ATTR_HIDDEN);
1605 hidden = hiddenStr == null
1606 ? hidden : Boolean.parseBoolean(hiddenStr);
Andrei Stingaceanu1e283912015-11-26 15:26:28 +00001607 final String suspendedStr = parser.getAttributeValue(null, ATTR_SUSPENDED);
1608 final boolean suspended = suspendedStr == null
1609 ? false : Boolean.parseBoolean(suspendedStr);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001610 final String notLaunchedStr = parser.getAttributeValue(null, ATTR_NOT_LAUNCHED);
1611 final boolean notLaunched = stoppedStr == null
1612 ? false : Boolean.parseBoolean(notLaunchedStr);
Kenny Guyc13053b2014-05-29 14:17:17 +01001613 final String blockUninstallStr = parser.getAttributeValue(null,
1614 ATTR_BLOCK_UNINSTALL);
1615 final boolean blockUninstall = blockUninstallStr == null
1616 ? false : Boolean.parseBoolean(blockUninstallStr);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001617
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001618 final String verifStateStr =
1619 parser.getAttributeValue(null, ATTR_DOMAIN_VERIFICATON_STATE);
1620 final int verifState = (verifStateStr == null) ?
1621 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED :
1622 Integer.parseInt(verifStateStr);
1623
Christopher Tatef0d6cb32015-07-10 17:44:53 -07001624 final String linkGenStr = parser.getAttributeValue(null, ATTR_APP_LINK_GENERATION);
1625 final int linkGeneration = linkGenStr == null ? 0 : Integer.parseInt(linkGenStr);
1626 if (linkGeneration > maxAppLinkGeneration) {
1627 maxAppLinkGeneration = linkGeneration;
1628 }
1629
Jeff Sharkey9f837a92014-10-24 12:07:24 -07001630 ArraySet<String> enabledComponents = null;
1631 ArraySet<String> disabledComponents = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001632
1633 int packageDepth = parser.getDepth();
1634 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1635 && (type != XmlPullParser.END_TAG
1636 || parser.getDepth() > packageDepth)) {
1637 if (type == XmlPullParser.END_TAG
1638 || type == XmlPullParser.TEXT) {
1639 continue;
1640 }
1641 tagName = parser.getName();
1642 if (tagName.equals(TAG_ENABLED_COMPONENTS)) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001643 enabledComponents = readComponentsLPr(parser);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001644 } else if (tagName.equals(TAG_DISABLED_COMPONENTS)) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001645 disabledComponents = readComponentsLPr(parser);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001646 }
1647 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001648
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001649 ps.setUserState(userId, enabled, installed, stopped, notLaunched, hidden,
Andrei Stingaceanu1e283912015-11-26 15:26:28 +00001650 suspended, enabledCaller, enabledComponents, disabledComponents,
1651 blockUninstall, verifState, linkGeneration);
Dianne Hackborn63092712012-10-07 14:45:35 -07001652 } else if (tagName.equals("preferred-activities")) {
1653 readPreferredActivitiesLPw(parser, userId);
Sander Alewijnseaf597622014-03-20 18:44:57 +00001654 } else if (tagName.equals(TAG_PERSISTENT_PREFERRED_ACTIVITIES)) {
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001655 readPersistentPreferredActivitiesLPw(parser, userId);
Nicolas Prevot29762c32014-07-29 18:51:32 +01001656 } else if (tagName.equals(TAG_CROSS_PROFILE_INTENT_FILTERS)) {
Nicolas Prevot81948992014-05-16 18:25:26 +01001657 readCrossProfileIntentFiltersLPw(parser, userId);
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001658 } else if (tagName.equals(TAG_DEFAULT_APPS)) {
1659 readDefaultAppsLPw(parser, userId);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001660 } else {
1661 Slog.w(PackageManagerService.TAG, "Unknown element under <stopped-packages>: "
1662 + parser.getName());
1663 XmlUtils.skipCurrentTag(parser);
1664 }
1665 }
1666
1667 str.close();
1668
Christopher Tatef0d6cb32015-07-10 17:44:53 -07001669 mNextAppLinkGeneration.put(userId, maxAppLinkGeneration + 1);
1670
Amith Yamasani483f3b02012-03-13 16:08:00 -07001671 } catch (XmlPullParserException e) {
1672 mReadMessages.append("Error reading: " + e.toString());
1673 PackageManagerService.reportSettingsProblem(Log.ERROR,
1674 "Error reading stopped packages: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07001675 Slog.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages",
1676 e);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001677
1678 } catch (java.io.IOException e) {
1679 mReadMessages.append("Error reading: " + e.toString());
1680 PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07001681 Slog.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages",
1682 e);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001683 }
1684 }
1685
Jeff Sharkey9f837a92014-10-24 12:07:24 -07001686 private ArraySet<String> readComponentsLPr(XmlPullParser parser)
Amith Yamasani483f3b02012-03-13 16:08:00 -07001687 throws IOException, XmlPullParserException {
Jeff Sharkey9f837a92014-10-24 12:07:24 -07001688 ArraySet<String> components = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001689 int type;
1690 int outerDepth = parser.getDepth();
1691 String tagName;
1692 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1693 && (type != XmlPullParser.END_TAG
1694 || parser.getDepth() > outerDepth)) {
1695 if (type == XmlPullParser.END_TAG
1696 || type == XmlPullParser.TEXT) {
1697 continue;
1698 }
1699 tagName = parser.getName();
1700 if (tagName.equals(TAG_ITEM)) {
1701 String componentName = parser.getAttributeValue(null, ATTR_NAME);
1702 if (componentName != null) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001703 if (components == null) {
Jeff Sharkey9f837a92014-10-24 12:07:24 -07001704 components = new ArraySet<String>();
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001705 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07001706 components.add(componentName);
1707 }
1708 }
1709 }
1710 return components;
1711 }
1712
Christopher Tatee012a232015-04-01 17:18:50 -07001713 /**
1714 * Record the state of preferred activity configuration into XML. This is used both
1715 * for recording packages.xml internally and for supporting backup/restore of the
1716 * preferred activity configuration.
1717 */
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08001718 void writePreferredActivitiesLPr(XmlSerializer serializer, int userId, boolean full)
Dianne Hackborn63092712012-10-07 14:45:35 -07001719 throws IllegalArgumentException, IllegalStateException, IOException {
1720 serializer.startTag(null, "preferred-activities");
1721 PreferredIntentResolver pir = mPreferredActivities.get(userId);
1722 if (pir != null) {
1723 for (final PreferredActivity pa : pir.filterSet()) {
1724 serializer.startTag(null, TAG_ITEM);
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08001725 pa.writeToXml(serializer, full);
Dianne Hackborn63092712012-10-07 14:45:35 -07001726 serializer.endTag(null, TAG_ITEM);
1727 }
1728 }
1729 serializer.endTag(null, "preferred-activities");
1730 }
1731
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001732 void writePersistentPreferredActivitiesLPr(XmlSerializer serializer, int userId)
1733 throws IllegalArgumentException, IllegalStateException, IOException {
Sander Alewijnseaf597622014-03-20 18:44:57 +00001734 serializer.startTag(null, TAG_PERSISTENT_PREFERRED_ACTIVITIES);
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001735 PersistentPreferredIntentResolver ppir = mPersistentPreferredActivities.get(userId);
1736 if (ppir != null) {
1737 for (final PersistentPreferredActivity ppa : ppir.filterSet()) {
1738 serializer.startTag(null, TAG_ITEM);
1739 ppa.writeToXml(serializer);
1740 serializer.endTag(null, TAG_ITEM);
1741 }
1742 }
Sander Alewijnseaf597622014-03-20 18:44:57 +00001743 serializer.endTag(null, TAG_PERSISTENT_PREFERRED_ACTIVITIES);
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001744 }
1745
Nicolas Prevot81948992014-05-16 18:25:26 +01001746 void writeCrossProfileIntentFiltersLPr(XmlSerializer serializer, int userId)
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001747 throws IllegalArgumentException, IllegalStateException, IOException {
Nicolas Prevot81948992014-05-16 18:25:26 +01001748 serializer.startTag(null, TAG_CROSS_PROFILE_INTENT_FILTERS);
1749 CrossProfileIntentResolver cpir = mCrossProfileIntentResolvers.get(userId);
1750 if (cpir != null) {
1751 for (final CrossProfileIntentFilter cpif : cpir.filterSet()) {
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001752 serializer.startTag(null, TAG_ITEM);
Nicolas Prevot81948992014-05-16 18:25:26 +01001753 cpif.writeToXml(serializer);
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001754 serializer.endTag(null, TAG_ITEM);
1755 }
1756 }
Nicolas Prevot81948992014-05-16 18:25:26 +01001757 serializer.endTag(null, TAG_CROSS_PROFILE_INTENT_FILTERS);
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001758 }
1759
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001760 void writeDomainVerificationsLPr(XmlSerializer serializer,
1761 IntentFilterVerificationInfo verificationInfo)
1762 throws IllegalArgumentException, IllegalStateException, IOException {
1763 if (verificationInfo != null && verificationInfo.getPackageName() != null) {
1764 serializer.startTag(null, TAG_DOMAIN_VERIFICATION);
1765 verificationInfo.writeToXml(serializer);
Christopher Tate72c10a22015-06-12 18:31:24 -07001766 if (DEBUG_DOMAIN_VERIFICATION) {
1767 Slog.d(TAG, "Wrote domain verification for package: "
1768 + verificationInfo.getPackageName());
1769 }
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001770 serializer.endTag(null, TAG_DOMAIN_VERIFICATION);
1771 }
1772 }
1773
Christopher Tate6038d152015-06-17 13:07:46 -07001774 // Specifically for backup/restore
1775 void writeAllDomainVerificationsLPr(XmlSerializer serializer, int userId)
1776 throws IllegalArgumentException, IllegalStateException, IOException {
1777 serializer.startTag(null, TAG_ALL_INTENT_FILTER_VERIFICATION);
1778 final int N = mPackages.size();
1779 for (int i = 0; i < N; i++) {
1780 PackageSetting ps = mPackages.valueAt(i);
1781 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
1782 if (ivi != null) {
1783 writeDomainVerificationsLPr(serializer, ivi);
1784 }
1785 }
1786 serializer.endTag(null, TAG_ALL_INTENT_FILTER_VERIFICATION);
1787 }
1788
1789 // Specifically for backup/restore
1790 void readAllDomainVerificationsLPr(XmlPullParser parser, int userId)
1791 throws XmlPullParserException, IOException {
1792 mRestoredIntentFilterVerifications.clear();
1793
1794 int outerDepth = parser.getDepth();
1795 int type;
1796 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1797 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1798 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1799 continue;
1800 }
1801
1802 String tagName = parser.getName();
1803 if (tagName.equals(TAG_DOMAIN_VERIFICATION)) {
1804 IntentFilterVerificationInfo ivi = new IntentFilterVerificationInfo(parser);
1805 final String pkgName = ivi.getPackageName();
1806 final PackageSetting ps = mPackages.get(pkgName);
1807 if (ps != null) {
1808 // known/existing package; update in place
1809 ps.setIntentFilterVerificationInfo(ivi);
1810 if (DEBUG_DOMAIN_VERIFICATION) {
1811 Slog.d(TAG, "Restored IVI for existing app " + pkgName
1812 + " status=" + ivi.getStatusString());
1813 }
1814 } else {
1815 mRestoredIntentFilterVerifications.put(pkgName, ivi);
1816 if (DEBUG_DOMAIN_VERIFICATION) {
1817 Slog.d(TAG, "Restored IVI for pending app " + pkgName
1818 + " status=" + ivi.getStatusString());
1819 }
1820 }
1821 } else {
1822 PackageManagerService.reportSettingsProblem(Log.WARN,
1823 "Unknown element under <all-intent-filter-verification>: "
1824 + parser.getName());
1825 XmlUtils.skipCurrentTag(parser);
1826 }
1827 }
1828 }
1829
Christopher Tatee9fd1fa2015-09-15 16:43:07 -07001830 // Specifically for backup/restore
1831 public void processRestoredPermissionGrantLPr(String pkgName, String permission,
1832 boolean isGranted, int restoredFlagSet, int userId)
1833 throws IOException, XmlPullParserException {
1834 mRuntimePermissionsPersistence.rememberRestoredUserGrantLPr(
1835 pkgName, permission, isGranted, restoredFlagSet, userId);
1836 }
1837
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001838 void writeDefaultAppsLPr(XmlSerializer serializer, int userId)
1839 throws IllegalArgumentException, IllegalStateException, IOException {
1840 serializer.startTag(null, TAG_DEFAULT_APPS);
1841 String packageName = mDefaultBrowserApp.get(userId);
1842 if (!TextUtils.isEmpty(packageName)) {
1843 serializer.startTag(null, TAG_DEFAULT_BROWSER);
1844 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
1845 serializer.endTag(null, TAG_DEFAULT_BROWSER);
1846 }
1847 serializer.endTag(null, TAG_DEFAULT_APPS);
1848 }
1849
Amith Yamasani483f3b02012-03-13 16:08:00 -07001850 void writePackageRestrictionsLPr(int userId) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001851 if (DEBUG_MU) {
1852 Log.i(TAG, "Writing package restrictions for user=" + userId);
1853 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001854 // Keep the old stopped packages around until we know the new ones have
1855 // been successfully written.
Amith Yamasani483f3b02012-03-13 16:08:00 -07001856 File userPackagesStateFile = getUserPackagesStateFile(userId);
1857 File backupFile = getUserPackagesStateBackupFile(userId);
1858 new File(userPackagesStateFile.getParent()).mkdirs();
1859 if (userPackagesStateFile.exists()) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001860 // Presence of backup settings file indicates that we failed
1861 // to persist packages earlier. So preserve the older
1862 // backup for future reference since the current packages
1863 // might have been corrupted.
Amith Yamasani483f3b02012-03-13 16:08:00 -07001864 if (!backupFile.exists()) {
1865 if (!userPackagesStateFile.renameTo(backupFile)) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07001866 Slog.wtf(PackageManagerService.TAG,
1867 "Unable to backup user packages state file, "
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001868 + "current changes will be lost at reboot");
1869 return;
1870 }
1871 } else {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001872 userPackagesStateFile.delete();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001873 Slog.w(PackageManagerService.TAG, "Preserving older stopped packages backup");
1874 }
1875 }
1876
1877 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001878 final FileOutputStream fstr = new FileOutputStream(userPackagesStateFile);
Kenny Root447106f2011-03-23 11:00:15 -07001879 final BufferedOutputStream str = new BufferedOutputStream(fstr);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001880
Kenny Root447106f2011-03-23 11:00:15 -07001881 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001882 serializer.setOutput(str, StandardCharsets.UTF_8.name());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001883 serializer.startDocument(null, true);
1884 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1885
Amith Yamasani483f3b02012-03-13 16:08:00 -07001886 serializer.startTag(null, TAG_PACKAGE_RESTRICTIONS);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001887
Kenny Root447106f2011-03-23 11:00:15 -07001888 for (final PackageSetting pkg : mPackages.values()) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001889 PackageUserState ustate = pkg.readUserState(userId);
1890 if (ustate.stopped || ustate.notLaunched || !ustate.installed
1891 || ustate.enabled != COMPONENT_ENABLED_STATE_DEFAULT
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001892 || ustate.hidden
Andrei Stingaceanu1e283912015-11-26 15:26:28 +00001893 || ustate.suspended
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001894 || (ustate.enabledComponents != null
1895 && ustate.enabledComponents.size() > 0)
1896 || (ustate.disabledComponents != null
Kenny Guyc13053b2014-05-29 14:17:17 +01001897 && ustate.disabledComponents.size() > 0)
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001898 || ustate.blockUninstall
1899 || (ustate.domainVerificationStatus !=
1900 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED)) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001901 serializer.startTag(null, TAG_PACKAGE);
1902 serializer.attribute(null, ATTR_NAME, pkg.name);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001903 if (DEBUG_MU) Log.i(TAG, " pkg=" + pkg.name + ", state=" + ustate.enabled);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001904
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001905 if (!ustate.installed) {
1906 serializer.attribute(null, ATTR_INSTALLED, "false");
1907 }
1908 if (ustate.stopped) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001909 serializer.attribute(null, ATTR_STOPPED, "true");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001910 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001911 if (ustate.notLaunched) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001912 serializer.attribute(null, ATTR_NOT_LAUNCHED, "true");
1913 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001914 if (ustate.hidden) {
1915 serializer.attribute(null, ATTR_HIDDEN, "true");
Amith Yamasani655d0e22013-06-12 14:19:10 -07001916 }
Andrei Stingaceanu1e283912015-11-26 15:26:28 +00001917 if (ustate.suspended) {
1918 serializer.attribute(null, ATTR_SUSPENDED, "true");
1919 }
Kenny Guyc13053b2014-05-29 14:17:17 +01001920 if (ustate.blockUninstall) {
1921 serializer.attribute(null, ATTR_BLOCK_UNINSTALL, "true");
1922 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001923 if (ustate.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
1924 serializer.attribute(null, ATTR_ENABLED,
1925 Integer.toString(ustate.enabled));
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07001926 if (ustate.lastDisableAppCaller != null) {
1927 serializer.attribute(null, ATTR_ENABLED_CALLER,
1928 ustate.lastDisableAppCaller);
1929 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07001930 }
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001931 if (ustate.domainVerificationStatus !=
1932 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
1933 serializer.attribute(null, ATTR_DOMAIN_VERIFICATON_STATE,
1934 Integer.toString(ustate.domainVerificationStatus));
1935 }
Christopher Tatef0d6cb32015-07-10 17:44:53 -07001936 if (ustate.appLinkGeneration != 0) {
1937 serializer.attribute(null, ATTR_APP_LINK_GENERATION,
1938 Integer.toString(ustate.appLinkGeneration));
1939 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001940 if (ustate.enabledComponents != null
1941 && ustate.enabledComponents.size() > 0) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001942 serializer.startTag(null, TAG_ENABLED_COMPONENTS);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001943 for (final String name : ustate.enabledComponents) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001944 serializer.startTag(null, TAG_ITEM);
1945 serializer.attribute(null, ATTR_NAME, name);
1946 serializer.endTag(null, TAG_ITEM);
1947 }
1948 serializer.endTag(null, TAG_ENABLED_COMPONENTS);
1949 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001950 if (ustate.disabledComponents != null
1951 && ustate.disabledComponents.size() > 0) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001952 serializer.startTag(null, TAG_DISABLED_COMPONENTS);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001953 for (final String name : ustate.disabledComponents) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001954 serializer.startTag(null, TAG_ITEM);
1955 serializer.attribute(null, ATTR_NAME, name);
1956 serializer.endTag(null, TAG_ITEM);
1957 }
1958 serializer.endTag(null, TAG_DISABLED_COMPONENTS);
1959 }
Svetoslavc6d1c342015-02-26 14:44:43 -08001960
Amith Yamasani483f3b02012-03-13 16:08:00 -07001961 serializer.endTag(null, TAG_PACKAGE);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001962 }
1963 }
1964
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08001965 writePreferredActivitiesLPr(serializer, userId, true);
Sander Alewijnsef475ca32014-02-17 15:13:58 +00001966 writePersistentPreferredActivitiesLPr(serializer, userId);
Nicolas Prevot81948992014-05-16 18:25:26 +01001967 writeCrossProfileIntentFiltersLPr(serializer, userId);
Fabrice Di Meglio62271722015-04-10 17:24:02 -07001968 writeDefaultAppsLPr(serializer, userId);
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00001969
Amith Yamasani483f3b02012-03-13 16:08:00 -07001970 serializer.endTag(null, TAG_PACKAGE_RESTRICTIONS);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001971
1972 serializer.endDocument();
1973
1974 str.flush();
1975 FileUtils.sync(fstr);
1976 str.close();
1977
1978 // New settings successfully written, old ones are no longer
1979 // needed.
Amith Yamasani483f3b02012-03-13 16:08:00 -07001980 backupFile.delete();
1981 FileUtils.setPermissions(userPackagesStateFile.toString(),
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001982 FileUtils.S_IRUSR|FileUtils.S_IWUSR
Nick Kralevich70522ad2012-01-06 13:58:01 -08001983 |FileUtils.S_IRGRP|FileUtils.S_IWGRP,
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001984 -1, -1);
1985
1986 // Done, all is good!
1987 return;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001988 } catch(java.io.IOException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07001989 Slog.wtf(PackageManagerService.TAG,
Amith Yamasani483f3b02012-03-13 16:08:00 -07001990 "Unable to write package manager user packages state, "
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001991 + " current changes will be lost at reboot", e);
1992 }
1993
1994 // Clean up partially written files
Amith Yamasani483f3b02012-03-13 16:08:00 -07001995 if (userPackagesStateFile.exists()) {
1996 if (!userPackagesStateFile.delete()) {
1997 Log.i(PackageManagerService.TAG, "Failed to clean up mangled file: "
1998 + mStoppedPackagesFilename);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001999 }
2000 }
2001 }
2002
Svetoslavc6d1c342015-02-26 14:44:43 -08002003 void readInstallPermissionsLPr(XmlPullParser parser,
2004 PermissionsState permissionsState) throws IOException, XmlPullParserException {
2005 int outerDepth = parser.getDepth();
2006 int type;
2007 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2008 && (type != XmlPullParser.END_TAG
2009 || parser.getDepth() > outerDepth)) {
2010 if (type == XmlPullParser.END_TAG
2011 || type == XmlPullParser.TEXT) {
2012 continue;
2013 }
2014 String tagName = parser.getName();
2015 if (tagName.equals(TAG_ITEM)) {
2016 String name = parser.getAttributeValue(null, ATTR_NAME);
2017
2018 BasePermission bp = mPermissions.get(name);
2019 if (bp == null) {
2020 Slog.w(PackageManagerService.TAG, "Unknown permission: " + name);
2021 XmlUtils.skipCurrentTag(parser);
2022 continue;
2023 }
2024
Svet Ganov8c7f7002015-05-07 10:48:44 -07002025 String grantedStr = parser.getAttributeValue(null, ATTR_GRANTED);
2026 final boolean granted = grantedStr == null
2027 || Boolean.parseBoolean(grantedStr);
2028
2029 String flagsStr = parser.getAttributeValue(null, ATTR_FLAGS);
2030 final int flags = (flagsStr != null)
2031 ? Integer.parseInt(flagsStr, 16) : 0;
2032
2033 if (granted) {
2034 if (permissionsState.grantInstallPermission(bp) ==
2035 PermissionsState.PERMISSION_OPERATION_FAILURE) {
2036 Slog.w(PackageManagerService.TAG, "Permission already added: " + name);
2037 XmlUtils.skipCurrentTag(parser);
2038 } else {
2039 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
2040 PackageManager.MASK_PERMISSION_FLAGS, flags);
2041 }
2042 } else {
2043 if (permissionsState.revokeInstallPermission(bp) ==
2044 PermissionsState.PERMISSION_OPERATION_FAILURE) {
2045 Slog.w(PackageManagerService.TAG, "Permission already added: " + name);
2046 XmlUtils.skipCurrentTag(parser);
2047 } else {
2048 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
2049 PackageManager.MASK_PERMISSION_FLAGS, flags);
2050 }
Svetoslavc6d1c342015-02-26 14:44:43 -08002051 }
2052 } else {
2053 Slog.w(PackageManagerService.TAG, "Unknown element under <permissions>: "
2054 + parser.getName());
2055 XmlUtils.skipCurrentTag(parser);
2056 }
2057 }
2058 }
2059
Svet Ganov8c7f7002015-05-07 10:48:44 -07002060 void writePermissionsLPr(XmlSerializer serializer, List<PermissionState> permissionStates)
Svetoslavc6d1c342015-02-26 14:44:43 -08002061 throws IOException {
Svet Ganov8c7f7002015-05-07 10:48:44 -07002062 if (permissionStates.isEmpty()) {
Svetoslavc6d1c342015-02-26 14:44:43 -08002063 return;
2064 }
2065
2066 serializer.startTag(null, TAG_PERMISSIONS);
2067
Svet Ganov8c7f7002015-05-07 10:48:44 -07002068 for (PermissionState permissionState : permissionStates) {
Svetoslavc6d1c342015-02-26 14:44:43 -08002069 serializer.startTag(null, TAG_ITEM);
Svet Ganov8c7f7002015-05-07 10:48:44 -07002070 serializer.attribute(null, ATTR_NAME, permissionState.getName());
2071 serializer.attribute(null, ATTR_GRANTED, String.valueOf(permissionState.isGranted()));
2072 serializer.attribute(null, ATTR_FLAGS, Integer.toHexString(permissionState.getFlags()));
Svetoslavc6d1c342015-02-26 14:44:43 -08002073 serializer.endTag(null, TAG_ITEM);
2074 }
2075
2076 serializer.endTag(null, TAG_PERMISSIONS);
2077 }
2078
Svet Ganov354cd3c2015-12-17 11:35:04 -08002079 void writeChildPackagesLPw(XmlSerializer serializer, List<String> childPackageNames)
2080 throws IOException {
2081 if (childPackageNames == null) {
2082 return;
2083 }
2084 final int childCount = childPackageNames.size();
2085 for (int i = 0; i < childCount; i++) {
2086 String childPackageName = childPackageNames.get(i);
2087 serializer.startTag(null, TAG_CHILD_PACKAGE);
2088 serializer.attribute(null, ATTR_NAME, childPackageName);
2089 serializer.endTag(null, TAG_CHILD_PACKAGE);
2090 }
2091 }
2092
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002093 // Note: assumed "stopped" field is already cleared in all packages.
Amith Yamasani483f3b02012-03-13 16:08:00 -07002094 // Legacy reader, used to read in the old file format after an upgrade. Not used after that.
Kenny Root447106f2011-03-23 11:00:15 -07002095 void readStoppedLPw() {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002096 FileInputStream str = null;
2097 if (mBackupStoppedPackagesFilename.exists()) {
2098 try {
2099 str = new FileInputStream(mBackupStoppedPackagesFilename);
2100 mReadMessages.append("Reading from backup stopped packages file\n");
Amith Yamasani483f3b02012-03-13 16:08:00 -07002101 PackageManagerService.reportSettingsProblem(Log.INFO,
2102 "Need to read from backup stopped packages file");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002103 if (mSettingsFilename.exists()) {
2104 // If both the backup and normal file exist, we
2105 // ignore the normal one since it might have been
2106 // corrupted.
2107 Slog.w(PackageManagerService.TAG, "Cleaning up stopped packages file "
2108 + mStoppedPackagesFilename);
2109 mStoppedPackagesFilename.delete();
2110 }
2111 } catch (java.io.IOException e) {
2112 // We'll try for the normal settings file.
2113 }
2114 }
2115
2116 try {
2117 if (str == null) {
2118 if (!mStoppedPackagesFilename.exists()) {
2119 mReadMessages.append("No stopped packages file found\n");
Amith Yamasani483f3b02012-03-13 16:08:00 -07002120 PackageManagerService.reportSettingsProblem(Log.INFO,
2121 "No stopped packages file file; assuming all started");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002122 // At first boot, make sure no packages are stopped.
2123 // We usually want to have third party apps initialize
2124 // in the stopped state, but not at first boot.
2125 for (PackageSetting pkg : mPackages.values()) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002126 pkg.setStopped(false, 0);
2127 pkg.setNotLaunched(false, 0);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002128 }
2129 return;
2130 }
2131 str = new FileInputStream(mStoppedPackagesFilename);
2132 }
Kenny Root447106f2011-03-23 11:00:15 -07002133 final XmlPullParser parser = Xml.newPullParser();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002134 parser.setInput(str, null);
2135
2136 int type;
2137 while ((type=parser.next()) != XmlPullParser.START_TAG
2138 && type != XmlPullParser.END_DOCUMENT) {
2139 ;
2140 }
2141
2142 if (type != XmlPullParser.START_TAG) {
2143 mReadMessages.append("No start tag found in stopped packages file\n");
2144 PackageManagerService.reportSettingsProblem(Log.WARN,
2145 "No start tag found in package manager stopped packages");
2146 return;
2147 }
2148
2149 int outerDepth = parser.getDepth();
2150 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2151 && (type != XmlPullParser.END_TAG
2152 || parser.getDepth() > outerDepth)) {
2153 if (type == XmlPullParser.END_TAG
2154 || type == XmlPullParser.TEXT) {
2155 continue;
2156 }
2157
2158 String tagName = parser.getName();
Amith Yamasani483f3b02012-03-13 16:08:00 -07002159 if (tagName.equals(TAG_PACKAGE)) {
2160 String name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002161 PackageSetting ps = mPackages.get(name);
2162 if (ps != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002163 ps.setStopped(true, 0);
2164 if ("1".equals(parser.getAttributeValue(null, ATTR_NOT_LAUNCHED))) {
2165 ps.setNotLaunched(true, 0);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002166 }
2167 } else {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002168 Slog.w(PackageManagerService.TAG,
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07002169 "No package known for stopped package " + name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002170 }
2171 XmlUtils.skipCurrentTag(parser);
2172 } else {
2173 Slog.w(PackageManagerService.TAG, "Unknown element under <stopped-packages>: "
2174 + parser.getName());
2175 XmlUtils.skipCurrentTag(parser);
2176 }
2177 }
2178
2179 str.close();
2180
Amith Yamasani483f3b02012-03-13 16:08:00 -07002181 } catch (XmlPullParserException e) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002182 mReadMessages.append("Error reading: " + e.toString());
Amith Yamasani483f3b02012-03-13 16:08:00 -07002183 PackageManagerService.reportSettingsProblem(Log.ERROR,
2184 "Error reading stopped packages: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07002185 Slog.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages",
2186 e);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002187
Amith Yamasani483f3b02012-03-13 16:08:00 -07002188 } catch (java.io.IOException e) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002189 mReadMessages.append("Error reading: " + e.toString());
2190 PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07002191 Slog.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages",
2192 e);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002193
2194 }
2195 }
2196
Kenny Root447106f2011-03-23 11:00:15 -07002197 void writeLPr() {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002198 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
2199
2200 // Keep the old settings around until we know the new ones have
2201 // been successfully written.
2202 if (mSettingsFilename.exists()) {
2203 // Presence of backup settings file indicates that we failed
2204 // to persist settings earlier. So preserve the older
2205 // backup for future reference since the current settings
2206 // might have been corrupted.
2207 if (!mBackupSettingsFilename.exists()) {
2208 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002209 Slog.wtf(PackageManagerService.TAG,
2210 "Unable to backup package manager settings, "
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002211 + " current changes will be lost at reboot");
2212 return;
2213 }
2214 } else {
2215 mSettingsFilename.delete();
2216 Slog.w(PackageManagerService.TAG, "Preserving older settings backup");
2217 }
2218 }
2219
2220 mPastSignatures.clear();
2221
2222 try {
2223 FileOutputStream fstr = new FileOutputStream(mSettingsFilename);
2224 BufferedOutputStream str = new BufferedOutputStream(fstr);
2225
2226 //XmlSerializer serializer = XmlUtils.serializerInstance();
2227 XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002228 serializer.setOutput(str, StandardCharsets.UTF_8.name());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002229 serializer.startDocument(null, true);
2230 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2231
2232 serializer.startTag(null, "packages");
2233
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07002234 for (int i = 0; i < mVersion.size(); i++) {
2235 final String volumeUuid = mVersion.keyAt(i);
2236 final VersionInfo ver = mVersion.valueAt(i);
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07002237
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07002238 serializer.startTag(null, TAG_VERSION);
2239 XmlUtils.writeStringAttribute(serializer, ATTR_VOLUME_UUID, volumeUuid);
2240 XmlUtils.writeIntAttribute(serializer, ATTR_SDK_VERSION, ver.sdkVersion);
2241 XmlUtils.writeIntAttribute(serializer, ATTR_DATABASE_VERSION, ver.databaseVersion);
2242 XmlUtils.writeStringAttribute(serializer, ATTR_FINGERPRINT, ver.fingerprint);
2243 serializer.endTag(null, TAG_VERSION);
2244 }
Kenny Rootc1c0d3c2014-04-24 13:36:40 -07002245
Kenny Root0aaa0d92011-09-12 16:42:55 -07002246 if (mVerifierDeviceIdentity != null) {
2247 serializer.startTag(null, "verifier");
2248 serializer.attribute(null, "device", mVerifierDeviceIdentity.toString());
2249 serializer.endTag(null, "verifier");
2250 }
2251
Jeff Sharkeyf5385772012-05-11 14:04:41 -07002252 if (mReadExternalStorageEnforced != null) {
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07002253 serializer.startTag(null, TAG_READ_EXTERNAL_STORAGE);
2254 serializer.attribute(
Jeff Sharkey5d32e772012-04-12 15:59:23 -07002255 null, ATTR_ENFORCEMENT, mReadExternalStorageEnforced ? "1" : "0");
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07002256 serializer.endTag(null, TAG_READ_EXTERNAL_STORAGE);
2257 }
2258
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002259 serializer.startTag(null, "permission-trees");
2260 for (BasePermission bp : mPermissionTrees.values()) {
Kenny Root447106f2011-03-23 11:00:15 -07002261 writePermissionLPr(serializer, bp);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002262 }
2263 serializer.endTag(null, "permission-trees");
2264
2265 serializer.startTag(null, "permissions");
2266 for (BasePermission bp : mPermissions.values()) {
Kenny Root447106f2011-03-23 11:00:15 -07002267 writePermissionLPr(serializer, bp);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002268 }
2269 serializer.endTag(null, "permissions");
2270
Kenny Root447106f2011-03-23 11:00:15 -07002271 for (final PackageSetting pkg : mPackages.values()) {
2272 writePackageLPr(serializer, pkg);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002273 }
2274
Kenny Root447106f2011-03-23 11:00:15 -07002275 for (final PackageSetting pkg : mDisabledSysPackages.values()) {
2276 writeDisabledSysPackageLPr(serializer, pkg);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002277 }
2278
Kenny Root447106f2011-03-23 11:00:15 -07002279 for (final SharedUserSetting usr : mSharedUsers.values()) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002280 serializer.startTag(null, "shared-user");
Amith Yamasani483f3b02012-03-13 16:08:00 -07002281 serializer.attribute(null, ATTR_NAME, usr.name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002282 serializer.attribute(null, "userId",
2283 Integer.toString(usr.userId));
2284 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
Svet Ganov8c7f7002015-05-07 10:48:44 -07002285 writePermissionsLPr(serializer, usr.getPermissionsState()
2286 .getInstallPermissionStates());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002287 serializer.endTag(null, "shared-user");
2288 }
2289
2290 if (mPackagesToBeCleaned.size() > 0) {
Jeff Sharkey752cd922012-09-23 16:25:12 -07002291 for (PackageCleanItem item : mPackagesToBeCleaned) {
2292 final String userStr = Integer.toString(item.userId);
2293 serializer.startTag(null, "cleaning-package");
2294 serializer.attribute(null, ATTR_NAME, item.packageName);
2295 serializer.attribute(null, ATTR_CODE, item.andCode ? "true" : "false");
2296 serializer.attribute(null, ATTR_USER, userStr);
2297 serializer.endTag(null, "cleaning-package");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002298 }
2299 }
Svetoslavc6d1c342015-02-26 14:44:43 -08002300
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002301 if (mRenamedPackages.size() > 0) {
Andy McFadden2f362292012-01-20 14:43:38 -08002302 for (Map.Entry<String, String> e : mRenamedPackages.entrySet()) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002303 serializer.startTag(null, "renamed-package");
2304 serializer.attribute(null, "new", e.getKey());
2305 serializer.attribute(null, "old", e.getValue());
2306 serializer.endTag(null, "renamed-package");
2307 }
2308 }
Svetoslavc6d1c342015-02-26 14:44:43 -08002309
Christopher Tate6038d152015-06-17 13:07:46 -07002310 final int numIVIs = mRestoredIntentFilterVerifications.size();
2311 if (numIVIs > 0) {
2312 if (DEBUG_DOMAIN_VERIFICATION) {
2313 Slog.i(TAG, "Writing restored-ivi entries to packages.xml");
2314 }
2315 serializer.startTag(null, "restored-ivi");
2316 for (int i = 0; i < numIVIs; i++) {
2317 IntentFilterVerificationInfo ivi = mRestoredIntentFilterVerifications.valueAt(i);
2318 writeDomainVerificationsLPr(serializer, ivi);
2319 }
2320 serializer.endTag(null, "restored-ivi");
2321 } else {
2322 if (DEBUG_DOMAIN_VERIFICATION) {
2323 Slog.i(TAG, " no restored IVI entries to write");
2324 }
2325 }
2326
dcashman55b10782014-04-09 14:20:38 -07002327 mKeySetManagerService.writeKeySetManagerServiceLPr(serializer);
Geremy Condraf1bcca82013-01-07 22:35:24 -08002328
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002329 serializer.endTag(null, "packages");
2330
2331 serializer.endDocument();
2332
2333 str.flush();
2334 FileUtils.sync(fstr);
2335 str.close();
2336
2337 // New settings successfully written, old ones are no longer
2338 // needed.
2339 mBackupSettingsFilename.delete();
2340 FileUtils.setPermissions(mSettingsFilename.toString(),
2341 FileUtils.S_IRUSR|FileUtils.S_IWUSR
Nick Kralevich70522ad2012-01-06 13:58:01 -08002342 |FileUtils.S_IRGRP|FileUtils.S_IWGRP,
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002343 -1, -1);
2344
Jeff Sharkey91edde22015-05-20 12:04:42 -07002345 writePackageListLPr();
Amith Yamasani483f3b02012-03-13 16:08:00 -07002346 writeAllUsersPackageRestrictionsLPr();
Svetoslavc6d1c342015-02-26 14:44:43 -08002347 writeAllRuntimePermissionsLPr();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002348 return;
2349
2350 } catch(XmlPullParserException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002351 Slog.wtf(PackageManagerService.TAG, "Unable to write package manager settings, "
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002352 + "current changes will be lost at reboot", e);
2353 } catch(java.io.IOException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002354 Slog.wtf(PackageManagerService.TAG, "Unable to write package manager settings, "
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002355 + "current changes will be lost at reboot", e);
2356 }
2357 // Clean up partially written files
2358 if (mSettingsFilename.exists()) {
2359 if (!mSettingsFilename.delete()) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002360 Slog.wtf(PackageManagerService.TAG, "Failed to clean up mangled file: "
Amith Yamasani483f3b02012-03-13 16:08:00 -07002361 + mSettingsFilename);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002362 }
2363 }
2364 //Debug.stopMethodTracing();
2365 }
2366
Jeff Sharkey91edde22015-05-20 12:04:42 -07002367 void writePackageListLPr() {
2368 writePackageListLPr(-1);
2369 }
2370
2371 void writePackageListLPr(int creatingUserId) {
2372 // Only derive GIDs for active users (not dying)
2373 final List<UserInfo> users = UserManagerService.getInstance().getUsers(true);
2374 int[] userIds = new int[users.size()];
2375 for (int i = 0; i < userIds.length; i++) {
2376 userIds[i] = users.get(i).id;
2377 }
2378 if (creatingUserId != -1) {
2379 userIds = ArrayUtils.appendInt(userIds, creatingUserId);
2380 }
2381
2382 // Write package list file now, use a JournaledFile.
2383 File tempFile = new File(mPackageListFilename.getAbsolutePath() + ".tmp");
2384 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
2385
2386 final File writeTarget = journal.chooseForWrite();
Fyodor Kupolovb69056b2015-12-18 15:20:00 -08002387 FileOutputStream fstr;
2388 BufferedWriter writer = null;
Jeff Sharkey91edde22015-05-20 12:04:42 -07002389 try {
2390 fstr = new FileOutputStream(writeTarget);
Fyodor Kupolovb69056b2015-12-18 15:20:00 -08002391 writer = new BufferedWriter(new OutputStreamWriter(fstr, Charset.defaultCharset()));
Jeff Sharkey91edde22015-05-20 12:04:42 -07002392 FileUtils.setPermissions(fstr.getFD(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
2393
2394 StringBuilder sb = new StringBuilder();
2395 for (final PackageSetting pkg : mPackages.values()) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002396 if (pkg.pkg == null || pkg.pkg.applicationInfo == null
2397 || pkg.pkg.applicationInfo.dataDir == null) {
Jeff Sharkey91edde22015-05-20 12:04:42 -07002398 Slog.w(TAG, "Skipping " + pkg + " due to missing metadata");
2399 continue;
2400 }
2401
2402 final ApplicationInfo ai = pkg.pkg.applicationInfo;
Jeff Sharkeye84bdd32016-02-08 12:16:00 -07002403 final String dataPath = ai.dataDir;
Jeff Sharkey91edde22015-05-20 12:04:42 -07002404 final boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
2405 final int[] gids = pkg.getPermissionsState().computeGids(userIds);
2406
2407 // Avoid any application that has a space in its path.
Fyodor Kupolovb69056b2015-12-18 15:20:00 -08002408 if (dataPath.indexOf(' ') >= 0)
Jeff Sharkey91edde22015-05-20 12:04:42 -07002409 continue;
2410
2411 // we store on each line the following information for now:
2412 //
2413 // pkgName - package name
2414 // userId - application-specific user id
2415 // debugFlag - 0 or 1 if the package is debuggable.
2416 // dataPath - path to package's data path
2417 // seinfo - seinfo label for the app (assigned at install time)
2418 // gids - supplementary gids this app launches with
2419 //
2420 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
2421 //
2422 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
2423 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
William Robertsdc06bb02015-07-24 10:05:06 -07002424 // frameworks/base/libs/packagelistparser
Jeff Sharkey91edde22015-05-20 12:04:42 -07002425 // system/core/run-as/run-as.c
Jeff Sharkey91edde22015-05-20 12:04:42 -07002426 //
2427 sb.setLength(0);
2428 sb.append(ai.packageName);
2429 sb.append(" ");
Fyodor Kupolovb69056b2015-12-18 15:20:00 -08002430 sb.append(ai.uid);
Jeff Sharkey91edde22015-05-20 12:04:42 -07002431 sb.append(isDebug ? " 1 " : " 0 ");
2432 sb.append(dataPath);
2433 sb.append(" ");
2434 sb.append(ai.seinfo);
2435 sb.append(" ");
2436 if (gids != null && gids.length > 0) {
2437 sb.append(gids[0]);
2438 for (int i = 1; i < gids.length; i++) {
2439 sb.append(",");
2440 sb.append(gids[i]);
2441 }
2442 } else {
2443 sb.append("none");
2444 }
2445 sb.append("\n");
Fyodor Kupolovb69056b2015-12-18 15:20:00 -08002446 writer.append(sb);
Jeff Sharkey91edde22015-05-20 12:04:42 -07002447 }
Fyodor Kupolovb69056b2015-12-18 15:20:00 -08002448 writer.flush();
Jeff Sharkey91edde22015-05-20 12:04:42 -07002449 FileUtils.sync(fstr);
Fyodor Kupolovb69056b2015-12-18 15:20:00 -08002450 writer.close();
Jeff Sharkey91edde22015-05-20 12:04:42 -07002451 journal.commit();
2452 } catch (Exception e) {
2453 Slog.wtf(TAG, "Failed to write packages.list", e);
Fyodor Kupolovb69056b2015-12-18 15:20:00 -08002454 IoUtils.closeQuietly(writer);
Jeff Sharkey91edde22015-05-20 12:04:42 -07002455 journal.rollback();
2456 }
2457 }
2458
Kenny Root447106f2011-03-23 11:00:15 -07002459 void writeDisabledSysPackageLPr(XmlSerializer serializer, final PackageSetting pkg)
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002460 throws java.io.IOException {
2461 serializer.startTag(null, "updated-package");
Amith Yamasani483f3b02012-03-13 16:08:00 -07002462 serializer.attribute(null, ATTR_NAME, pkg.name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002463 if (pkg.realName != null) {
2464 serializer.attribute(null, "realName", pkg.realName);
2465 }
2466 serializer.attribute(null, "codePath", pkg.codePathString);
2467 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
2468 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
2469 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
2470 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
2471 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
2472 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
2473 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002474 if (pkg.legacyNativeLibraryPathString != null) {
2475 serializer.attribute(null, "nativeLibraryPath", pkg.legacyNativeLibraryPathString);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002476 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002477 if (pkg.primaryCpuAbiString != null) {
2478 serializer.attribute(null, "primaryCpuAbi", pkg.primaryCpuAbiString);
Narayan Kamath9e289d72014-04-10 09:26:59 +00002479 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002480 if (pkg.secondaryCpuAbiString != null) {
2481 serializer.attribute(null, "secondaryCpuAbi", pkg.secondaryCpuAbiString);
2482 }
Narayan Kamath4903f642014-08-11 13:33:45 +01002483 if (pkg.cpuAbiOverrideString != null) {
2484 serializer.attribute(null, "cpuAbiOverride", pkg.cpuAbiOverrideString);
2485 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002486
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002487 if (pkg.sharedUser == null) {
Amith Yamasani13593602012-03-22 16:16:17 -07002488 serializer.attribute(null, "userId", Integer.toString(pkg.appId));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002489 } else {
Amith Yamasani13593602012-03-22 16:16:17 -07002490 serializer.attribute(null, "sharedUserId", Integer.toString(pkg.appId));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002491 }
Svetoslavc6d1c342015-02-26 14:44:43 -08002492
Svet Ganov354cd3c2015-12-17 11:35:04 -08002493 if (pkg.parentPackageName != null) {
2494 serializer.attribute(null, "parentPackageName", pkg.parentPackageName);
2495 }
2496
2497 writeChildPackagesLPw(serializer, pkg.childPackageNames);
2498
Svetoslavc6d1c342015-02-26 14:44:43 -08002499 // If this is a shared user, the permissions will be written there.
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002500 if (pkg.sharedUser == null) {
Svet Ganov8c7f7002015-05-07 10:48:44 -07002501 writePermissionsLPr(serializer, pkg.getPermissionsState()
2502 .getInstallPermissionStates());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002503 }
Svetoslavc6d1c342015-02-26 14:44:43 -08002504
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002505 serializer.endTag(null, "updated-package");
2506 }
2507
Kenny Root447106f2011-03-23 11:00:15 -07002508 void writePackageLPr(XmlSerializer serializer, final PackageSetting pkg)
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002509 throws java.io.IOException {
2510 serializer.startTag(null, "package");
Amith Yamasani483f3b02012-03-13 16:08:00 -07002511 serializer.attribute(null, ATTR_NAME, pkg.name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002512 if (pkg.realName != null) {
2513 serializer.attribute(null, "realName", pkg.realName);
2514 }
2515 serializer.attribute(null, "codePath", pkg.codePathString);
2516 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
2517 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
2518 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002519
2520 if (pkg.legacyNativeLibraryPathString != null) {
2521 serializer.attribute(null, "nativeLibraryPath", pkg.legacyNativeLibraryPathString);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002522 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002523 if (pkg.primaryCpuAbiString != null) {
2524 serializer.attribute(null, "primaryCpuAbi", pkg.primaryCpuAbiString);
Narayan Kamath9e289d72014-04-10 09:26:59 +00002525 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002526 if (pkg.secondaryCpuAbiString != null) {
2527 serializer.attribute(null, "secondaryCpuAbi", pkg.secondaryCpuAbiString);
2528 }
Narayan Kamath4903f642014-08-11 13:33:45 +01002529 if (pkg.cpuAbiOverrideString != null) {
2530 serializer.attribute(null, "cpuAbiOverride", pkg.cpuAbiOverrideString);
2531 }
Narayan Kamathff110bd2014-07-04 18:30:45 +01002532
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002533 serializer.attribute(null, "publicFlags", Integer.toString(pkg.pkgFlags));
2534 serializer.attribute(null, "privateFlags", Integer.toString(pkg.pkgPrivateFlags));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002535 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
2536 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
2537 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
2538 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
2539 if (pkg.sharedUser == null) {
Amith Yamasani13593602012-03-22 16:16:17 -07002540 serializer.attribute(null, "userId", Integer.toString(pkg.appId));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002541 } else {
Amith Yamasani13593602012-03-22 16:16:17 -07002542 serializer.attribute(null, "sharedUserId", Integer.toString(pkg.appId));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002543 }
2544 if (pkg.uidError) {
2545 serializer.attribute(null, "uidError", "true");
2546 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002547 if (pkg.installStatus == PackageSettingBase.PKG_INSTALL_INCOMPLETE) {
2548 serializer.attribute(null, "installStatus", "false");
2549 }
2550 if (pkg.installerPackageName != null) {
2551 serializer.attribute(null, "installer", pkg.installerPackageName);
2552 }
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07002553 if (pkg.volumeUuid != null) {
2554 serializer.attribute(null, "volumeUuid", pkg.volumeUuid);
2555 }
Svet Ganov354cd3c2015-12-17 11:35:04 -08002556
2557 if (pkg.parentPackageName != null) {
2558 serializer.attribute(null, "parentPackageName", pkg.parentPackageName);
2559 }
2560
2561 writeChildPackagesLPw(serializer, pkg.childPackageNames);
2562
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002563 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
Svet Ganov8c7f7002015-05-07 10:48:44 -07002564
2565 writePermissionsLPr(serializer, pkg.getPermissionsState()
2566 .getInstallPermissionStates());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002567
dcashman8c04fac2015-03-23 11:39:42 -07002568 writeSigningKeySetLPr(serializer, pkg.keySetData);
dcashman55b10782014-04-09 14:20:38 -07002569 writeUpgradeKeySetsLPr(serializer, pkg.keySetData);
Geremy Condraf1bcca82013-01-07 22:35:24 -08002570 writeKeySetAliasesLPr(serializer, pkg.keySetData);
Fabrice Di Meglio62271722015-04-10 17:24:02 -07002571 writeDomainVerificationsLPr(serializer, pkg.verificationInfo);
Geremy Condraf1bcca82013-01-07 22:35:24 -08002572
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002573 serializer.endTag(null, "package");
2574 }
2575
dcashman8c04fac2015-03-23 11:39:42 -07002576 void writeSigningKeySetLPr(XmlSerializer serializer,
Geremy Condraf1bcca82013-01-07 22:35:24 -08002577 PackageKeySetData data) throws IOException {
dcashman8c04fac2015-03-23 11:39:42 -07002578 serializer.startTag(null, "proper-signing-keyset");
2579 serializer.attribute(null, "identifier",
2580 Long.toString(data.getProperSigningKeySet()));
2581 serializer.endTag(null, "proper-signing-keyset");
dcashman55b10782014-04-09 14:20:38 -07002582 }
2583
2584 void writeUpgradeKeySetsLPr(XmlSerializer serializer,
2585 PackageKeySetData data) throws IOException {
dcashman8c04fac2015-03-23 11:39:42 -07002586 long properSigning = data.getProperSigningKeySet();
dcashman55b10782014-04-09 14:20:38 -07002587 if (data.isUsingUpgradeKeySets()) {
2588 for (long id : data.getUpgradeKeySets()) {
2589 serializer.startTag(null, "upgrade-keyset");
2590 serializer.attribute(null, "identifier", Long.toString(id));
2591 serializer.endTag(null, "upgrade-keyset");
2592 }
Geremy Condraf1bcca82013-01-07 22:35:24 -08002593 }
2594 }
2595
2596 void writeKeySetAliasesLPr(XmlSerializer serializer,
2597 PackageKeySetData data) throws IOException {
2598 for (Map.Entry<String, Long> e: data.getAliases().entrySet()) {
2599 serializer.startTag(null, "defined-keyset");
2600 serializer.attribute(null, "alias", e.getKey());
2601 serializer.attribute(null, "identifier", Long.toString(e.getValue()));
2602 serializer.endTag(null, "defined-keyset");
2603 }
2604 }
2605
Kenny Root447106f2011-03-23 11:00:15 -07002606 void writePermissionLPr(XmlSerializer serializer, BasePermission bp)
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002607 throws XmlPullParserException, java.io.IOException {
2608 if (bp.type != BasePermission.TYPE_BUILTIN && bp.sourcePackage != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002609 serializer.startTag(null, TAG_ITEM);
2610 serializer.attribute(null, ATTR_NAME, bp.name);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002611 serializer.attribute(null, "package", bp.sourcePackage);
2612 if (bp.protectionLevel != PermissionInfo.PROTECTION_NORMAL) {
2613 serializer.attribute(null, "protection", Integer.toString(bp.protectionLevel));
2614 }
2615 if (PackageManagerService.DEBUG_SETTINGS)
2616 Log.v(PackageManagerService.TAG, "Writing perm: name=" + bp.name + " type="
2617 + bp.type);
2618 if (bp.type == BasePermission.TYPE_DYNAMIC) {
Kenny Root447106f2011-03-23 11:00:15 -07002619 final PermissionInfo pi = bp.perm != null ? bp.perm.info : bp.pendingInfo;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002620 if (pi != null) {
2621 serializer.attribute(null, "type", "dynamic");
2622 if (pi.icon != 0) {
2623 serializer.attribute(null, "icon", Integer.toString(pi.icon));
2624 }
2625 if (pi.nonLocalizedLabel != null) {
2626 serializer.attribute(null, "label", pi.nonLocalizedLabel.toString());
2627 }
2628 }
2629 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07002630 serializer.endTag(null, TAG_ITEM);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002631 }
2632 }
2633
Kenny Root447106f2011-03-23 11:00:15 -07002634 ArrayList<PackageSetting> getListOfIncompleteInstallPackagesLPr() {
Jeff Sharkey9f837a92014-10-24 12:07:24 -07002635 final ArraySet<String> kList = new ArraySet<String>(mPackages.keySet());
Kenny Root447106f2011-03-23 11:00:15 -07002636 final Iterator<String> its = kList.iterator();
2637 final ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002638 while (its.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07002639 final String key = its.next();
2640 final PackageSetting ps = mPackages.get(key);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002641 if (ps.getInstallStatus() == PackageSettingBase.PKG_INSTALL_INCOMPLETE) {
2642 ret.add(ps);
2643 }
2644 }
2645 return ret;
2646 }
2647
Jeff Sharkey752cd922012-09-23 16:25:12 -07002648 void addPackageToCleanLPw(PackageCleanItem pkg) {
2649 if (!mPackagesToBeCleaned.contains(pkg)) {
2650 mPackagesToBeCleaned.add(pkg);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002651 }
2652 }
2653
Xiaohui Chen594f2082015-08-18 11:04:20 -07002654 boolean readLPw(@NonNull List<UserInfo> users) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002655 FileInputStream str = null;
2656 if (mBackupSettingsFilename.exists()) {
2657 try {
2658 str = new FileInputStream(mBackupSettingsFilename);
2659 mReadMessages.append("Reading from backup settings file\n");
2660 PackageManagerService.reportSettingsProblem(Log.INFO,
2661 "Need to read from backup settings file");
2662 if (mSettingsFilename.exists()) {
2663 // If both the backup and settings file exist, we
2664 // ignore the settings since it might have been
2665 // corrupted.
2666 Slog.w(PackageManagerService.TAG, "Cleaning up settings file "
2667 + mSettingsFilename);
2668 mSettingsFilename.delete();
2669 }
2670 } catch (java.io.IOException e) {
2671 // We'll try for the normal settings file.
2672 }
2673 }
2674
Kenny Root447106f2011-03-23 11:00:15 -07002675 mPendingPackages.clear();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002676 mPastSignatures.clear();
dcashman8c04fac2015-03-23 11:39:42 -07002677 mKeySetRefs.clear();
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002678
2679 try {
2680 if (str == null) {
2681 if (!mSettingsFilename.exists()) {
2682 mReadMessages.append("No settings file found\n");
2683 PackageManagerService.reportSettingsProblem(Log.INFO,
2684 "No settings file; creating initial state");
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07002685 // It's enough to just touch version details to create them
2686 // with default values
2687 findOrCreateVersion(StorageManager.UUID_PRIVATE_INTERNAL);
2688 findOrCreateVersion(StorageManager.UUID_PRIMARY_PHYSICAL);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002689 return false;
2690 }
2691 str = new FileInputStream(mSettingsFilename);
2692 }
2693 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002694 parser.setInput(str, StandardCharsets.UTF_8.name());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002695
2696 int type;
2697 while ((type = parser.next()) != XmlPullParser.START_TAG
2698 && type != XmlPullParser.END_DOCUMENT) {
2699 ;
2700 }
2701
2702 if (type != XmlPullParser.START_TAG) {
2703 mReadMessages.append("No start tag found in settings file\n");
2704 PackageManagerService.reportSettingsProblem(Log.WARN,
2705 "No start tag found in package manager settings");
Dianne Hackborn8d051722014-10-01 14:59:58 -07002706 Slog.wtf(PackageManagerService.TAG,
Dianne Hackborn58f42a52011-10-10 13:46:34 -07002707 "No start tag found in package manager settings");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002708 return false;
2709 }
2710
2711 int outerDepth = parser.getDepth();
2712 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2713 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2714 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2715 continue;
2716 }
2717
2718 String tagName = parser.getName();
2719 if (tagName.equals("package")) {
Kenny Root447106f2011-03-23 11:00:15 -07002720 readPackageLPw(parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002721 } else if (tagName.equals("permissions")) {
Kenny Root447106f2011-03-23 11:00:15 -07002722 readPermissionsLPw(mPermissions, parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002723 } else if (tagName.equals("permission-trees")) {
Kenny Root447106f2011-03-23 11:00:15 -07002724 readPermissionsLPw(mPermissionTrees, parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002725 } else if (tagName.equals("shared-user")) {
Kenny Root447106f2011-03-23 11:00:15 -07002726 readSharedUserLPw(parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002727 } else if (tagName.equals("preferred-packages")) {
2728 // no longer used.
2729 } else if (tagName.equals("preferred-activities")) {
Dianne Hackborn63092712012-10-07 14:45:35 -07002730 // Upgrading from old single-user implementation;
2731 // these are the preferred activities for user 0.
2732 readPreferredActivitiesLPw(parser, 0);
Sander Alewijnseaf597622014-03-20 18:44:57 +00002733 } else if (tagName.equals(TAG_PERSISTENT_PREFERRED_ACTIVITIES)) {
Sander Alewijnsef475ca32014-02-17 15:13:58 +00002734 // TODO: check whether this is okay! as it is very
2735 // similar to how preferred-activities are treated
2736 readPersistentPreferredActivitiesLPw(parser, 0);
Nicolas Prevot29762c32014-07-29 18:51:32 +01002737 } else if (tagName.equals(TAG_CROSS_PROFILE_INTENT_FILTERS)) {
Nicolas Prevot10fa67c2014-03-24 13:44:38 +00002738 // TODO: check whether this is okay! as it is very
2739 // similar to how preferred-activities are treated
Nicolas Prevot81948992014-05-16 18:25:26 +01002740 readCrossProfileIntentFiltersLPw(parser, 0);
Fabrice Di Meglio62271722015-04-10 17:24:02 -07002741 } else if (tagName.equals(TAG_DEFAULT_BROWSER)) {
2742 readDefaultAppsLPw(parser, 0);
2743 } else if (tagName.equals("updated-package")) {
Kenny Root447106f2011-03-23 11:00:15 -07002744 readDisabledSysPackageLPw(parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002745 } else if (tagName.equals("cleaning-package")) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002746 String name = parser.getAttributeValue(null, ATTR_NAME);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002747 String userStr = parser.getAttributeValue(null, ATTR_USER);
2748 String codeStr = parser.getAttributeValue(null, ATTR_CODE);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002749 if (name != null) {
Xiaohui Chen594f2082015-08-18 11:04:20 -07002750 int userId = UserHandle.USER_SYSTEM;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002751 boolean andCode = true;
2752 try {
2753 if (userStr != null) {
Jeff Sharkey752cd922012-09-23 16:25:12 -07002754 userId = Integer.parseInt(userStr);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002755 }
2756 } catch (NumberFormatException e) {
2757 }
2758 if (codeStr != null) {
2759 andCode = Boolean.parseBoolean(codeStr);
2760 }
Jeff Sharkey752cd922012-09-23 16:25:12 -07002761 addPackageToCleanLPw(new PackageCleanItem(userId, name, andCode));
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002762 }
2763 } else if (tagName.equals("renamed-package")) {
2764 String nname = parser.getAttributeValue(null, "new");
2765 String oname = parser.getAttributeValue(null, "old");
2766 if (nname != null && oname != null) {
2767 mRenamedPackages.put(nname, oname);
2768 }
Christopher Tate6038d152015-06-17 13:07:46 -07002769 } else if (tagName.equals("restored-ivi")) {
2770 readRestoredIntentFilterVerifications(parser);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002771 } else if (tagName.equals("last-platform-version")) {
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07002772 // Upgrade from older XML schema
2773 final VersionInfo internal = findOrCreateVersion(
2774 StorageManager.UUID_PRIVATE_INTERNAL);
2775 final VersionInfo external = findOrCreateVersion(
2776 StorageManager.UUID_PRIMARY_PHYSICAL);
Svet Ganovadc1cf42015-06-15 16:36:24 -07002777
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07002778 internal.sdkVersion = XmlUtils.readIntAttribute(parser, "internal", 0);
2779 external.sdkVersion = XmlUtils.readIntAttribute(parser, "external", 0);
2780 internal.fingerprint = external.fingerprint =
2781 XmlUtils.readStringAttribute(parser, "fingerprint");
2782
Kenny Rootc1c0d3c2014-04-24 13:36:40 -07002783 } else if (tagName.equals("database-version")) {
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07002784 // Upgrade from older XML schema
2785 final VersionInfo internal = findOrCreateVersion(
2786 StorageManager.UUID_PRIVATE_INTERNAL);
2787 final VersionInfo external = findOrCreateVersion(
2788 StorageManager.UUID_PRIMARY_PHYSICAL);
2789
2790 internal.databaseVersion = XmlUtils.readIntAttribute(parser, "internal", 0);
2791 external.databaseVersion = XmlUtils.readIntAttribute(parser, "external", 0);
2792
Kenny Root0aaa0d92011-09-12 16:42:55 -07002793 } else if (tagName.equals("verifier")) {
2794 final String deviceIdentity = parser.getAttributeValue(null, "device");
2795 try {
2796 mVerifierDeviceIdentity = VerifierDeviceIdentity.parse(deviceIdentity);
2797 } catch (IllegalArgumentException e) {
2798 Slog.w(PackageManagerService.TAG, "Discard invalid verifier device id: "
2799 + e.getMessage());
2800 }
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07002801 } else if (TAG_READ_EXTERNAL_STORAGE.equals(tagName)) {
2802 final String enforcement = parser.getAttributeValue(null, ATTR_ENFORCEMENT);
Jeff Sharkey5d32e772012-04-12 15:59:23 -07002803 mReadExternalStorageEnforced = "1".equals(enforcement);
Geremy Condraf1bcca82013-01-07 22:35:24 -08002804 } else if (tagName.equals("keyset-settings")) {
dcashman8c04fac2015-03-23 11:39:42 -07002805 mKeySetManagerService.readKeySetsLPw(parser, mKeySetRefs);
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07002806 } else if (TAG_VERSION.equals(tagName)) {
2807 final String volumeUuid = XmlUtils.readStringAttribute(parser,
2808 ATTR_VOLUME_UUID);
2809 final VersionInfo ver = findOrCreateVersion(volumeUuid);
2810 ver.sdkVersion = XmlUtils.readIntAttribute(parser, ATTR_SDK_VERSION);
2811 ver.databaseVersion = XmlUtils.readIntAttribute(parser, ATTR_SDK_VERSION);
2812 ver.fingerprint = XmlUtils.readStringAttribute(parser, ATTR_FINGERPRINT);
2813
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002814 } else {
2815 Slog.w(PackageManagerService.TAG, "Unknown element under <packages>: "
2816 + parser.getName());
2817 XmlUtils.skipCurrentTag(parser);
2818 }
2819 }
2820
2821 str.close();
2822
2823 } catch (XmlPullParserException e) {
2824 mReadMessages.append("Error reading: " + e.toString());
2825 PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07002826 Slog.wtf(PackageManagerService.TAG, "Error reading package manager settings", e);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002827
2828 } catch (java.io.IOException e) {
2829 mReadMessages.append("Error reading: " + e.toString());
2830 PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborn8d051722014-10-01 14:59:58 -07002831 Slog.wtf(PackageManagerService.TAG, "Error reading package manager settings", e);
Amith Yamasani258848d2012-08-10 17:06:33 -07002832 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002833
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07002834 // If the build is setup to drop runtime permissions
2835 // on update drop the files before loading them.
2836 if (PackageManagerService.CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE) {
2837 final VersionInfo internal = getInternalVersion();
2838 if (!Build.FINGERPRINT.equals(internal.fingerprint)) {
Xiaohui Chen594f2082015-08-18 11:04:20 -07002839 for (UserInfo user : users) {
2840 mRuntimePermissionsPersistence.deleteUserRuntimePermissionsFile(user.id);
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07002841 }
2842 }
2843 }
2844
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002845 final int N = mPendingPackages.size();
dcashman8c04fac2015-03-23 11:39:42 -07002846
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002847 for (int i = 0; i < N; i++) {
2848 final PendingPackage pp = mPendingPackages.get(i);
Kenny Root447106f2011-03-23 11:00:15 -07002849 Object idObj = getUserIdLPr(pp.sharedId);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002850 if (idObj != null && idObj instanceof SharedUserSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002851 PackageSetting p = getPackageLPw(pp.name, null, pp.realName,
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002852 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
Narayan Kamathff110bd2014-07-04 18:30:45 +01002853 pp.legacyNativeLibraryPathString, pp.primaryCpuAbiString,
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002854 pp.secondaryCpuAbiString, pp.versionCode, pp.pkgFlags, pp.pkgPrivateFlags,
Svet Ganov354cd3c2015-12-17 11:35:04 -08002855 null, true /* add */, false /* allowInstall */, pp.parentPackageName,
2856 pp.childPackageNames);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002857 if (p == null) {
2858 PackageManagerService.reportSettingsProblem(Log.WARN,
2859 "Unable to create application package for " + pp.name);
2860 continue;
2861 }
2862 p.copyFrom(pp);
2863 } else if (idObj != null) {
2864 String msg = "Bad package setting: package " + pp.name + " has shared uid "
2865 + pp.sharedId + " that is not a shared uid\n";
2866 mReadMessages.append(msg);
2867 PackageManagerService.reportSettingsProblem(Log.ERROR, msg);
2868 } else {
2869 String msg = "Bad package setting: package " + pp.name + " has shared uid "
2870 + pp.sharedId + " that is not defined\n";
2871 mReadMessages.append(msg);
2872 PackageManagerService.reportSettingsProblem(Log.ERROR, msg);
2873 }
2874 }
2875 mPendingPackages.clear();
2876
Amith Yamasanif031f232012-10-26 15:35:21 -07002877 if (mBackupStoppedPackagesFilename.exists()
2878 || mStoppedPackagesFilename.exists()) {
2879 // Read old file
2880 readStoppedLPw();
2881 mBackupStoppedPackagesFilename.delete();
2882 mStoppedPackagesFilename.delete();
2883 // Migrate to new file format
Xiaohui Chen594f2082015-08-18 11:04:20 -07002884 writePackageRestrictionsLPr(UserHandle.USER_SYSTEM);
Amith Yamasanif031f232012-10-26 15:35:21 -07002885 } else {
Xiaohui Chen594f2082015-08-18 11:04:20 -07002886 for (UserInfo user : users) {
2887 readPackageRestrictionsLPr(user.id);
Amith Yamasanif031f232012-10-26 15:35:21 -07002888 }
2889 }
2890
Xiaohui Chen594f2082015-08-18 11:04:20 -07002891 for (UserInfo user : users) {
2892 mRuntimePermissionsPersistence.readStateForUserSyncLPr(user.id);
Svet Ganovadc1cf42015-06-15 16:36:24 -07002893 }
2894
Kenny Root1d1b4892011-04-08 14:25:24 -07002895 /*
2896 * Make sure all the updated system packages have their shared users
2897 * associated with them.
2898 */
2899 final Iterator<PackageSetting> disabledIt = mDisabledSysPackages.values().iterator();
2900 while (disabledIt.hasNext()) {
2901 final PackageSetting disabledPs = disabledIt.next();
Amith Yamasani13593602012-03-22 16:16:17 -07002902 final Object id = getUserIdLPr(disabledPs.appId);
Kenny Root1d1b4892011-04-08 14:25:24 -07002903 if (id != null && id instanceof SharedUserSetting) {
2904 disabledPs.sharedUser = (SharedUserSetting) id;
2905 }
2906 }
2907
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002908 mReadMessages.append("Read completed successfully: " + mPackages.size() + " packages, "
2909 + mSharedUsers.size() + " shared uids\n");
2910
2911 return true;
2912 }
2913
Christopher Tatedb3fe812015-06-24 16:15:48 -07002914 void applyDefaultPreferredAppsLPw(PackageManagerService service, int userId) {
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002915 // First pull data from any pre-installed apps.
2916 for (PackageSetting ps : mPackages.values()) {
2917 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0 && ps.pkg != null
2918 && ps.pkg.preferredActivityFilters != null) {
2919 ArrayList<PackageParser.ActivityIntentInfo> intents
2920 = ps.pkg.preferredActivityFilters;
2921 for (int i=0; i<intents.size(); i++) {
2922 PackageParser.ActivityIntentInfo aii = intents.get(i);
2923 applyDefaultPreferredActivityLPw(service, aii, new ComponentName(
2924 ps.name, aii.activity.className), userId);
2925 }
2926 }
2927 }
2928
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07002929 // Read preferred apps from .../etc/preferred-apps directory.
2930 File preferredDir = new File(Environment.getRootDirectory(), "etc/preferred-apps");
2931 if (!preferredDir.exists() || !preferredDir.isDirectory()) {
2932 return;
2933 }
2934 if (!preferredDir.canRead()) {
2935 Slog.w(TAG, "Directory " + preferredDir + " cannot be read");
2936 return;
2937 }
2938
2939 // Iterate over the files in the directory and scan .xml files
2940 for (File f : preferredDir.listFiles()) {
2941 if (!f.getPath().endsWith(".xml")) {
2942 Slog.i(TAG, "Non-xml file " + f + " in " + preferredDir + " directory, ignoring");
2943 continue;
2944 }
2945 if (!f.canRead()) {
2946 Slog.w(TAG, "Preferred apps file " + f + " cannot be read");
2947 continue;
2948 }
2949
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08002950 if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Reading default preferred " + f);
Fyodor Kupolovb35b34c2015-12-17 14:16:51 -08002951 InputStream str = null;
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07002952 try {
Fyodor Kupolovb35b34c2015-12-17 14:16:51 -08002953 str = new BufferedInputStream(new FileInputStream(f));
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07002954 XmlPullParser parser = Xml.newPullParser();
2955 parser.setInput(str, null);
2956
2957 int type;
2958 while ((type = parser.next()) != XmlPullParser.START_TAG
2959 && type != XmlPullParser.END_DOCUMENT) {
2960 ;
2961 }
2962
2963 if (type != XmlPullParser.START_TAG) {
2964 Slog.w(TAG, "Preferred apps file " + f + " does not have start tag");
2965 continue;
2966 }
2967 if (!"preferred-activities".equals(parser.getName())) {
2968 Slog.w(TAG, "Preferred apps file " + f
2969 + " does not start with 'preferred-activities'");
2970 continue;
2971 }
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08002972 readDefaultPreferredActivitiesLPw(service, parser, userId);
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07002973 } catch (XmlPullParserException e) {
2974 Slog.w(TAG, "Error reading apps file " + f, e);
2975 } catch (IOException e) {
2976 Slog.w(TAG, "Error reading apps file " + f, e);
2977 } finally {
2978 if (str != null) {
2979 try {
2980 str.close();
2981 } catch (IOException e) {
2982 }
2983 }
2984 }
2985 }
2986 }
2987
Dianne Hackbornb09491f2013-07-22 15:30:11 -07002988 private void applyDefaultPreferredActivityLPw(PackageManagerService service,
2989 IntentFilter tmpPa, ComponentName cn, int userId) {
2990 // The initial preferences only specify the target activity
2991 // component and intent-filter, not the set of matches. So we
2992 // now need to query for the matches to build the correct
2993 // preferred activity entry.
2994 if (PackageManagerService.DEBUG_PREFERRED) {
2995 Log.d(TAG, "Processing preferred:");
2996 tmpPa.dump(new LogPrinter(Log.DEBUG, TAG), " ");
2997 }
2998 Intent intent = new Intent();
2999 int flags = 0;
3000 intent.setAction(tmpPa.getAction(0));
3001 for (int i=0; i<tmpPa.countCategories(); i++) {
3002 String cat = tmpPa.getCategory(i);
3003 if (cat.equals(Intent.CATEGORY_DEFAULT)) {
Jeff Sharkey2a90f6732016-01-06 12:26:11 -07003004 flags |= MATCH_DEFAULT_ONLY;
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003005 } else {
3006 intent.addCategory(cat);
3007 }
3008 }
3009
3010 boolean doNonData = true;
Christopher Tate2298ef22013-11-04 17:02:10 -08003011 boolean hasSchemes = false;
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003012
3013 for (int ischeme=0; ischeme<tmpPa.countDataSchemes(); ischeme++) {
3014 boolean doScheme = true;
3015 String scheme = tmpPa.getDataScheme(ischeme);
Christopher Tate2298ef22013-11-04 17:02:10 -08003016 if (scheme != null && !scheme.isEmpty()) {
3017 hasSchemes = true;
3018 }
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003019 for (int issp=0; issp<tmpPa.countDataSchemeSpecificParts(); issp++) {
3020 Uri.Builder builder = new Uri.Builder();
3021 builder.scheme(scheme);
3022 PatternMatcher ssp = tmpPa.getDataSchemeSpecificPart(issp);
3023 builder.opaquePart(ssp.getPath());
3024 Intent finalIntent = new Intent(intent);
3025 finalIntent.setData(builder.build());
3026 applyDefaultPreferredActivityLPw(service, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003027 scheme, ssp, null, null, userId);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003028 doScheme = false;
3029 }
3030 for (int iauth=0; iauth<tmpPa.countDataAuthorities(); iauth++) {
3031 boolean doAuth = true;
3032 IntentFilter.AuthorityEntry auth = tmpPa.getDataAuthority(iauth);
3033 for (int ipath=0; ipath<tmpPa.countDataPaths(); ipath++) {
3034 Uri.Builder builder = new Uri.Builder();
3035 builder.scheme(scheme);
3036 if (auth.getHost() != null) {
3037 builder.authority(auth.getHost());
3038 }
3039 PatternMatcher path = tmpPa.getDataPath(ipath);
3040 builder.path(path.getPath());
3041 Intent finalIntent = new Intent(intent);
3042 finalIntent.setData(builder.build());
3043 applyDefaultPreferredActivityLPw(service, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003044 scheme, null, auth, path, userId);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003045 doAuth = doScheme = false;
3046 }
3047 if (doAuth) {
3048 Uri.Builder builder = new Uri.Builder();
3049 builder.scheme(scheme);
3050 if (auth.getHost() != null) {
3051 builder.authority(auth.getHost());
3052 }
3053 Intent finalIntent = new Intent(intent);
3054 finalIntent.setData(builder.build());
3055 applyDefaultPreferredActivityLPw(service, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003056 scheme, null, auth, null, userId);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003057 doScheme = false;
3058 }
3059 }
3060 if (doScheme) {
3061 Uri.Builder builder = new Uri.Builder();
3062 builder.scheme(scheme);
3063 Intent finalIntent = new Intent(intent);
3064 finalIntent.setData(builder.build());
3065 applyDefaultPreferredActivityLPw(service, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003066 scheme, null, null, null, userId);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003067 }
3068 doNonData = false;
3069 }
3070
3071 for (int idata=0; idata<tmpPa.countDataTypes(); idata++) {
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003072 String mimeType = tmpPa.getDataType(idata);
Christopher Tate2298ef22013-11-04 17:02:10 -08003073 if (hasSchemes) {
3074 Uri.Builder builder = new Uri.Builder();
3075 for (int ischeme=0; ischeme<tmpPa.countDataSchemes(); ischeme++) {
3076 String scheme = tmpPa.getDataScheme(ischeme);
3077 if (scheme != null && !scheme.isEmpty()) {
3078 Intent finalIntent = new Intent(intent);
3079 builder.scheme(scheme);
3080 finalIntent.setDataAndType(builder.build(), mimeType);
3081 applyDefaultPreferredActivityLPw(service, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003082 scheme, null, null, null, userId);
Christopher Tate2298ef22013-11-04 17:02:10 -08003083 }
3084 }
3085 } else {
3086 Intent finalIntent = new Intent(intent);
3087 finalIntent.setType(mimeType);
3088 applyDefaultPreferredActivityLPw(service, finalIntent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003089 null, null, null, null, userId);
Christopher Tate2298ef22013-11-04 17:02:10 -08003090 }
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003091 doNonData = false;
3092 }
3093
3094 if (doNonData) {
3095 applyDefaultPreferredActivityLPw(service, intent, flags, cn,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003096 null, null, null, null, userId);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003097 }
3098 }
3099
3100 private void applyDefaultPreferredActivityLPw(PackageManagerService service,
3101 Intent intent, int flags, ComponentName cn, String scheme, PatternMatcher ssp,
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003102 IntentFilter.AuthorityEntry auth, PatternMatcher path, int userId) {
Svetoslav Ganov5fd83dc2016-01-20 17:27:48 -08003103 flags = service.updateFlagsForResolve(flags, userId, intent);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003104 List<ResolveInfo> ri = service.mActivities.queryIntent(intent,
3105 intent.getType(), flags, 0);
3106 if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Queried " + intent
3107 + " results: " + ri);
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07003108 int systemMatch = 0;
3109 int thirdPartyMatch = 0;
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003110 if (ri != null && ri.size() > 1) {
3111 boolean haveAct = false;
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003112 ComponentName haveNonSys = null;
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003113 ComponentName[] set = new ComponentName[ri.size()];
3114 for (int i=0; i<ri.size(); i++) {
3115 ActivityInfo ai = ri.get(i).activityInfo;
3116 set[i] = new ComponentName(ai.packageName, ai.name);
3117 if ((ai.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07003118 if (ri.get(i).match >= thirdPartyMatch) {
3119 // Keep track of the best match we find of all third
3120 // party apps, for use later to determine if we actually
3121 // want to set a preferred app for this intent.
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003122 if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Result "
3123 + ai.packageName + "/" + ai.name + ": non-system!");
3124 haveNonSys = set[i];
3125 break;
3126 }
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003127 } else if (cn.getPackageName().equals(ai.packageName)
3128 && cn.getClassName().equals(ai.name)) {
3129 if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Result "
3130 + ai.packageName + "/" + ai.name + ": default!");
3131 haveAct = true;
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07003132 systemMatch = ri.get(i).match;
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003133 } else {
3134 if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Result "
3135 + ai.packageName + "/" + ai.name + ": skipped");
3136 }
3137 }
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07003138 if (haveNonSys != null && thirdPartyMatch < systemMatch) {
3139 // If we have a matching third party app, but its match is not as
3140 // good as the built-in system app, then we don't want to actually
3141 // consider it a match because presumably the built-in app is still
3142 // the thing we want users to see by default.
3143 haveNonSys = null;
3144 }
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003145 if (haveAct && haveNonSys == null) {
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003146 IntentFilter filter = new IntentFilter();
3147 if (intent.getAction() != null) {
3148 filter.addAction(intent.getAction());
3149 }
Erin Dahlgren707a59d2013-10-24 15:13:39 -07003150 if (intent.getCategories() != null) {
3151 for (String cat : intent.getCategories()) {
3152 filter.addCategory(cat);
3153 }
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003154 }
Jeff Sharkey2a90f6732016-01-06 12:26:11 -07003155 if ((flags & MATCH_DEFAULT_ONLY) != 0) {
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003156 filter.addCategory(Intent.CATEGORY_DEFAULT);
3157 }
3158 if (scheme != null) {
3159 filter.addDataScheme(scheme);
3160 }
3161 if (ssp != null) {
3162 filter.addDataSchemeSpecificPart(ssp.getPath(), ssp.getType());
3163 }
3164 if (auth != null) {
3165 filter.addDataAuthority(auth);
3166 }
3167 if (path != null) {
3168 filter.addDataPath(path);
3169 }
Erin Dahlgren707a59d2013-10-24 15:13:39 -07003170 if (intent.getType() != null) {
3171 try {
3172 filter.addDataType(intent.getType());
3173 } catch (IntentFilter.MalformedMimeTypeException ex) {
3174 Slog.w(TAG, "Malformed mimetype " + intent.getType() + " for " + cn);
3175 }
3176 }
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07003177 PreferredActivity pa = new PreferredActivity(filter, systemMatch, set, cn, true);
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003178 editPreferredActivitiesLPw(userId).addFilter(pa);
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003179 } else if (haveNonSys == null) {
3180 StringBuilder sb = new StringBuilder();
3181 sb.append("No component ");
3182 sb.append(cn.flattenToShortString());
3183 sb.append(" found setting preferred ");
3184 sb.append(intent);
3185 sb.append("; possible matches are ");
3186 for (int i=0; i<set.length; i++) {
3187 if (i > 0) sb.append(", ");
3188 sb.append(set[i].flattenToShortString());
3189 }
3190 Slog.w(TAG, sb.toString());
3191 } else {
3192 Slog.i(TAG, "Not setting preferred " + intent + "; found third party match "
3193 + haveNonSys.flattenToShortString());
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003194 }
Dianne Hackborneeb2c7e2014-09-23 16:45:39 -07003195 } else {
3196 Slog.w(TAG, "No potential matches found for " + intent + " while setting preferred "
3197 + cn.flattenToShortString());
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003198 }
3199 }
3200
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08003201 private void readDefaultPreferredActivitiesLPw(PackageManagerService service,
3202 XmlPullParser parser, int userId)
3203 throws XmlPullParserException, IOException {
3204 int outerDepth = parser.getDepth();
3205 int type;
3206 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3207 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3208 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3209 continue;
3210 }
3211
3212 String tagName = parser.getName();
3213 if (tagName.equals(TAG_ITEM)) {
3214 PreferredActivity tmpPa = new PreferredActivity(parser);
3215 if (tmpPa.mPref.getParseError() == null) {
Dianne Hackbornb09491f2013-07-22 15:30:11 -07003216 applyDefaultPreferredActivityLPw(service, tmpPa, tmpPa.mPref.mComponent,
3217 userId);
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08003218 } else {
3219 PackageManagerService.reportSettingsProblem(Log.WARN,
3220 "Error in package manager settings: <preferred-activity> "
3221 + tmpPa.mPref.getParseError() + " at "
3222 + parser.getPositionDescription());
3223 }
3224 } else {
3225 PackageManagerService.reportSettingsProblem(Log.WARN,
3226 "Unknown element under <preferred-activities>: " + parser.getName());
3227 XmlUtils.skipCurrentTag(parser);
3228 }
3229 }
3230 }
3231
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003232 private int readInt(XmlPullParser parser, String ns, String name, int defValue) {
3233 String v = parser.getAttributeValue(ns, name);
3234 try {
3235 if (v == null) {
3236 return defValue;
3237 }
3238 return Integer.parseInt(v);
3239 } catch (NumberFormatException e) {
3240 PackageManagerService.reportSettingsProblem(Log.WARN,
3241 "Error in package manager settings: attribute " + name
3242 + " has bad integer value " + v + " at "
3243 + parser.getPositionDescription());
3244 }
3245 return defValue;
3246 }
3247
Jeff Sharkey9f837a92014-10-24 12:07:24 -07003248 private void readPermissionsLPw(ArrayMap<String, BasePermission> out, XmlPullParser parser)
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003249 throws IOException, XmlPullParserException {
3250 int outerDepth = parser.getDepth();
3251 int type;
3252 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3253 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3254 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3255 continue;
3256 }
3257
Kenny Root447106f2011-03-23 11:00:15 -07003258 final String tagName = parser.getName();
Amith Yamasani483f3b02012-03-13 16:08:00 -07003259 if (tagName.equals(TAG_ITEM)) {
3260 final String name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Root447106f2011-03-23 11:00:15 -07003261 final String sourcePackage = parser.getAttributeValue(null, "package");
3262 final String ptype = parser.getAttributeValue(null, "type");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003263 if (name != null && sourcePackage != null) {
Kenny Root447106f2011-03-23 11:00:15 -07003264 final boolean dynamic = "dynamic".equals(ptype);
Svetoslavc6d1c342015-02-26 14:44:43 -08003265 final BasePermission bp = new BasePermission(name.intern(), sourcePackage,
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003266 dynamic ? BasePermission.TYPE_DYNAMIC : BasePermission.TYPE_NORMAL);
3267 bp.protectionLevel = readInt(parser, null, "protection",
3268 PermissionInfo.PROTECTION_NORMAL);
Dianne Hackborne639da72012-02-21 15:11:13 -08003269 bp.protectionLevel = PermissionInfo.fixProtectionLevel(bp.protectionLevel);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003270 if (dynamic) {
3271 PermissionInfo pi = new PermissionInfo();
3272 pi.packageName = sourcePackage.intern();
3273 pi.name = name.intern();
3274 pi.icon = readInt(parser, null, "icon", 0);
3275 pi.nonLocalizedLabel = parser.getAttributeValue(null, "label");
3276 pi.protectionLevel = bp.protectionLevel;
3277 bp.pendingInfo = pi;
3278 }
3279 out.put(bp.name, bp);
3280 } else {
3281 PackageManagerService.reportSettingsProblem(Log.WARN,
3282 "Error in package manager settings: permissions has" + " no name at "
3283 + parser.getPositionDescription());
3284 }
3285 } else {
3286 PackageManagerService.reportSettingsProblem(Log.WARN,
3287 "Unknown element reading permissions: " + parser.getName() + " at "
3288 + parser.getPositionDescription());
3289 }
3290 XmlUtils.skipCurrentTag(parser);
3291 }
3292 }
3293
Kenny Root447106f2011-03-23 11:00:15 -07003294 private void readDisabledSysPackageLPw(XmlPullParser parser) throws XmlPullParserException,
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003295 IOException {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003296 String name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003297 String realName = parser.getAttributeValue(null, "realName");
3298 String codePathStr = parser.getAttributeValue(null, "codePath");
3299 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Narayan Kamathff110bd2014-07-04 18:30:45 +01003300
3301 String legacyCpuAbiStr = parser.getAttributeValue(null, "requiredCpuAbi");
3302 String legacyNativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
3303
Svet Ganov354cd3c2015-12-17 11:35:04 -08003304 String parentPackageName = parser.getAttributeValue(null, "parentPackageName");
3305
Narayan Kamathff110bd2014-07-04 18:30:45 +01003306 String primaryCpuAbiStr = parser.getAttributeValue(null, "primaryCpuAbi");
3307 String secondaryCpuAbiStr = parser.getAttributeValue(null, "secondaryCpuAbi");
Narayan Kamath4903f642014-08-11 13:33:45 +01003308 String cpuAbiOverrideStr = parser.getAttributeValue(null, "cpuAbiOverride");
Narayan Kamathff110bd2014-07-04 18:30:45 +01003309
3310 if (primaryCpuAbiStr == null && legacyCpuAbiStr != null) {
3311 primaryCpuAbiStr = legacyCpuAbiStr;
3312 }
Narayan Kamath9e289d72014-04-10 09:26:59 +00003313
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003314 if (resourcePathStr == null) {
3315 resourcePathStr = codePathStr;
3316 }
3317 String version = parser.getAttributeValue(null, "version");
3318 int versionCode = 0;
3319 if (version != null) {
3320 try {
3321 versionCode = Integer.parseInt(version);
3322 } catch (NumberFormatException e) {
3323 }
3324 }
3325
3326 int pkgFlags = 0;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003327 int pkgPrivateFlags = 0;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003328 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Christopher Tate628946a2013-10-18 18:11:05 -07003329 final File codePathFile = new File(codePathStr);
3330 if (PackageManagerService.locationIsPrivileged(codePathFile)) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003331 pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
Christopher Tate628946a2013-10-18 18:11:05 -07003332 }
3333 PackageSetting ps = new PackageSetting(name, realName, codePathFile,
Narayan Kamathff110bd2014-07-04 18:30:45 +01003334 new File(resourcePathStr), legacyNativeLibraryPathStr, primaryCpuAbiStr,
Svet Ganov354cd3c2015-12-17 11:35:04 -08003335 secondaryCpuAbiStr, cpuAbiOverrideStr, versionCode, pkgFlags, pkgPrivateFlags,
3336 parentPackageName, null);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003337 String timeStampStr = parser.getAttributeValue(null, "ft");
3338 if (timeStampStr != null) {
3339 try {
3340 long timeStamp = Long.parseLong(timeStampStr, 16);
3341 ps.setTimeStamp(timeStamp);
3342 } catch (NumberFormatException e) {
3343 }
3344 } else {
3345 timeStampStr = parser.getAttributeValue(null, "ts");
3346 if (timeStampStr != null) {
3347 try {
3348 long timeStamp = Long.parseLong(timeStampStr);
3349 ps.setTimeStamp(timeStamp);
3350 } catch (NumberFormatException e) {
3351 }
3352 }
3353 }
3354 timeStampStr = parser.getAttributeValue(null, "it");
3355 if (timeStampStr != null) {
3356 try {
3357 ps.firstInstallTime = Long.parseLong(timeStampStr, 16);
3358 } catch (NumberFormatException e) {
3359 }
3360 }
3361 timeStampStr = parser.getAttributeValue(null, "ut");
3362 if (timeStampStr != null) {
3363 try {
3364 ps.lastUpdateTime = Long.parseLong(timeStampStr, 16);
3365 } catch (NumberFormatException e) {
3366 }
3367 }
3368 String idStr = parser.getAttributeValue(null, "userId");
Amith Yamasani13593602012-03-22 16:16:17 -07003369 ps.appId = idStr != null ? Integer.parseInt(idStr) : 0;
3370 if (ps.appId <= 0) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003371 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
Amith Yamasani13593602012-03-22 16:16:17 -07003372 ps.appId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003373 }
Svetoslavc6d1c342015-02-26 14:44:43 -08003374
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003375 int outerDepth = parser.getDepth();
3376 int type;
3377 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3378 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3379 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3380 continue;
3381 }
3382
Svetoslavc6d1c342015-02-26 14:44:43 -08003383 if (parser.getName().equals(TAG_PERMISSIONS)) {
3384 readInstallPermissionsLPr(parser, ps.getPermissionsState());
Svet Ganov354cd3c2015-12-17 11:35:04 -08003385 } else if (parser.getName().equals(TAG_CHILD_PACKAGE)) {
3386 String childPackageName = parser.getAttributeValue(null, ATTR_NAME);
3387 if (ps.childPackageNames == null) {
3388 ps.childPackageNames = new ArrayList<>();
3389 }
3390 ps.childPackageNames.add(childPackageName);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003391 } else {
3392 PackageManagerService.reportSettingsProblem(Log.WARN,
3393 "Unknown element under <updated-package>: " + parser.getName());
3394 XmlUtils.skipCurrentTag(parser);
3395 }
3396 }
Christopher Tate628946a2013-10-18 18:11:05 -07003397
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003398 mDisabledSysPackages.put(name, ps);
3399 }
3400
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003401 private static int PRE_M_APP_INFO_FLAG_HIDDEN = 1<<27;
3402 private static int PRE_M_APP_INFO_FLAG_CANT_SAVE_STATE = 1<<28;
3403 private static int PRE_M_APP_INFO_FLAG_FORWARD_LOCK = 1<<29;
3404 private static int PRE_M_APP_INFO_FLAG_PRIVILEGED = 1<<30;
3405
Kenny Root447106f2011-03-23 11:00:15 -07003406 private void readPackageLPw(XmlPullParser parser) throws XmlPullParserException, IOException {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003407 String name = null;
3408 String realName = null;
3409 String idStr = null;
3410 String sharedIdStr = null;
3411 String codePathStr = null;
3412 String resourcePathStr = null;
Narayan Kamathff110bd2014-07-04 18:30:45 +01003413 String legacyCpuAbiString = null;
3414 String legacyNativeLibraryPathStr = null;
3415 String primaryCpuAbiString = null;
3416 String secondaryCpuAbiString = null;
Narayan Kamath4903f642014-08-11 13:33:45 +01003417 String cpuAbiOverrideString = null;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003418 String systemStr = null;
3419 String installerPackageName = null;
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07003420 String volumeUuid = null;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003421 String uidError = null;
3422 int pkgFlags = 0;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003423 int pkgPrivateFlags = 0;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003424 long timeStamp = 0;
3425 long firstInstallTime = 0;
3426 long lastUpdateTime = 0;
3427 PackageSettingBase packageSetting = null;
3428 String version = null;
3429 int versionCode = 0;
Svet Ganov354cd3c2015-12-17 11:35:04 -08003430 String parentPackageName;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003431 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003432 name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003433 realName = parser.getAttributeValue(null, "realName");
3434 idStr = parser.getAttributeValue(null, "userId");
3435 uidError = parser.getAttributeValue(null, "uidError");
3436 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
3437 codePathStr = parser.getAttributeValue(null, "codePath");
3438 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Narayan Kamath9e289d72014-04-10 09:26:59 +00003439
Narayan Kamathff110bd2014-07-04 18:30:45 +01003440 legacyCpuAbiString = parser.getAttributeValue(null, "requiredCpuAbi");
3441
Svet Ganov354cd3c2015-12-17 11:35:04 -08003442 parentPackageName = parser.getAttributeValue(null, "parentPackageName");
3443
Narayan Kamathff110bd2014-07-04 18:30:45 +01003444 legacyNativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
3445 primaryCpuAbiString = parser.getAttributeValue(null, "primaryCpuAbi");
3446 secondaryCpuAbiString = parser.getAttributeValue(null, "secondaryCpuAbi");
Narayan Kamath4903f642014-08-11 13:33:45 +01003447 cpuAbiOverrideString = parser.getAttributeValue(null, "cpuAbiOverride");
Narayan Kamathff110bd2014-07-04 18:30:45 +01003448
3449 if (primaryCpuAbiString == null && legacyCpuAbiString != null) {
3450 primaryCpuAbiString = legacyCpuAbiString;
3451 }
Svetoslavc6d1c342015-02-26 14:44:43 -08003452
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003453 version = parser.getAttributeValue(null, "version");
3454 if (version != null) {
3455 try {
3456 versionCode = Integer.parseInt(version);
3457 } catch (NumberFormatException e) {
3458 }
3459 }
3460 installerPackageName = parser.getAttributeValue(null, "installer");
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07003461 volumeUuid = parser.getAttributeValue(null, "volumeUuid");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003462
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003463 systemStr = parser.getAttributeValue(null, "publicFlags");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003464 if (systemStr != null) {
3465 try {
3466 pkgFlags = Integer.parseInt(systemStr);
3467 } catch (NumberFormatException e) {
3468 }
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003469 systemStr = parser.getAttributeValue(null, "privateFlags");
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003470 if (systemStr != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003471 try {
3472 pkgPrivateFlags = Integer.parseInt(systemStr);
3473 } catch (NumberFormatException e) {
3474 }
3475 }
3476 } else {
3477 // Pre-M -- both public and private flags were stored in one "flags" field.
3478 systemStr = parser.getAttributeValue(null, "flags");
3479 if (systemStr != null) {
3480 try {
3481 pkgFlags = Integer.parseInt(systemStr);
3482 } catch (NumberFormatException e) {
3483 }
3484 if ((pkgFlags & PRE_M_APP_INFO_FLAG_HIDDEN) != 0) {
3485 pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_HIDDEN;
3486 }
3487 if ((pkgFlags & PRE_M_APP_INFO_FLAG_CANT_SAVE_STATE) != 0) {
3488 pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE;
3489 }
3490 if ((pkgFlags & PRE_M_APP_INFO_FLAG_FORWARD_LOCK) != 0) {
3491 pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_FORWARD_LOCK;
3492 }
3493 if ((pkgFlags & PRE_M_APP_INFO_FLAG_PRIVILEGED) != 0) {
3494 pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
3495 }
3496 pkgFlags &= ~(PRE_M_APP_INFO_FLAG_HIDDEN
3497 | PRE_M_APP_INFO_FLAG_CANT_SAVE_STATE
3498 | PRE_M_APP_INFO_FLAG_FORWARD_LOCK
3499 | PRE_M_APP_INFO_FLAG_PRIVILEGED);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003500 } else {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003501 // For backward compatibility
3502 systemStr = parser.getAttributeValue(null, "system");
3503 if (systemStr != null) {
3504 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM
3505 : 0;
3506 } else {
3507 // Old settings that don't specify system... just treat
3508 // them as system, good enough.
3509 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
3510 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003511 }
3512 }
3513 String timeStampStr = parser.getAttributeValue(null, "ft");
3514 if (timeStampStr != null) {
3515 try {
3516 timeStamp = Long.parseLong(timeStampStr, 16);
3517 } catch (NumberFormatException e) {
3518 }
3519 } else {
3520 timeStampStr = parser.getAttributeValue(null, "ts");
3521 if (timeStampStr != null) {
3522 try {
3523 timeStamp = Long.parseLong(timeStampStr);
3524 } catch (NumberFormatException e) {
3525 }
3526 }
3527 }
3528 timeStampStr = parser.getAttributeValue(null, "it");
3529 if (timeStampStr != null) {
3530 try {
3531 firstInstallTime = Long.parseLong(timeStampStr, 16);
3532 } catch (NumberFormatException e) {
3533 }
3534 }
3535 timeStampStr = parser.getAttributeValue(null, "ut");
3536 if (timeStampStr != null) {
3537 try {
3538 lastUpdateTime = Long.parseLong(timeStampStr, 16);
3539 } catch (NumberFormatException e) {
3540 }
3541 }
3542 if (PackageManagerService.DEBUG_SETTINGS)
3543 Log.v(PackageManagerService.TAG, "Reading package: " + name + " userId=" + idStr
3544 + " sharedUserId=" + sharedIdStr);
3545 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
3546 if (resourcePathStr == null) {
3547 resourcePathStr = codePathStr;
3548 }
3549 if (realName != null) {
3550 realName = realName.intern();
3551 }
3552 if (name == null) {
3553 PackageManagerService.reportSettingsProblem(Log.WARN,
3554 "Error in package manager settings: <package> has no name at "
3555 + parser.getPositionDescription());
3556 } else if (codePathStr == null) {
3557 PackageManagerService.reportSettingsProblem(Log.WARN,
3558 "Error in package manager settings: <package> has no codePath at "
3559 + parser.getPositionDescription());
3560 } else if (userId > 0) {
Kenny Root447106f2011-03-23 11:00:15 -07003561 packageSetting = addPackageLPw(name.intern(), realName, new File(codePathStr),
Narayan Kamathff110bd2014-07-04 18:30:45 +01003562 new File(resourcePathStr), legacyNativeLibraryPathStr, primaryCpuAbiString,
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003563 secondaryCpuAbiString, cpuAbiOverrideString, userId, versionCode, pkgFlags,
Svet Ganov354cd3c2015-12-17 11:35:04 -08003564 pkgPrivateFlags, parentPackageName, null);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003565 if (PackageManagerService.DEBUG_SETTINGS)
3566 Log.i(PackageManagerService.TAG, "Reading package " + name + ": userId="
3567 + userId + " pkg=" + packageSetting);
3568 if (packageSetting == null) {
3569 PackageManagerService.reportSettingsProblem(Log.ERROR, "Failure adding uid "
3570 + userId + " while parsing settings at "
3571 + parser.getPositionDescription());
3572 } else {
3573 packageSetting.setTimeStamp(timeStamp);
3574 packageSetting.firstInstallTime = firstInstallTime;
3575 packageSetting.lastUpdateTime = lastUpdateTime;
3576 }
3577 } else if (sharedIdStr != null) {
3578 userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
3579 if (userId > 0) {
3580 packageSetting = new PendingPackage(name.intern(), realName, new File(
Narayan Kamathff110bd2014-07-04 18:30:45 +01003581 codePathStr), new File(resourcePathStr), legacyNativeLibraryPathStr,
Narayan Kamath4903f642014-08-11 13:33:45 +01003582 primaryCpuAbiString, secondaryCpuAbiString, cpuAbiOverrideString,
Svet Ganov354cd3c2015-12-17 11:35:04 -08003583 userId, versionCode, pkgFlags, pkgPrivateFlags, parentPackageName,
3584 null);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003585 packageSetting.setTimeStamp(timeStamp);
3586 packageSetting.firstInstallTime = firstInstallTime;
3587 packageSetting.lastUpdateTime = lastUpdateTime;
3588 mPendingPackages.add((PendingPackage) packageSetting);
3589 if (PackageManagerService.DEBUG_SETTINGS)
3590 Log.i(PackageManagerService.TAG, "Reading package " + name
3591 + ": sharedUserId=" + userId + " pkg=" + packageSetting);
3592 } else {
3593 PackageManagerService.reportSettingsProblem(Log.WARN,
3594 "Error in package manager settings: package " + name
3595 + " has bad sharedId " + sharedIdStr + " at "
3596 + parser.getPositionDescription());
3597 }
3598 } else {
3599 PackageManagerService.reportSettingsProblem(Log.WARN,
3600 "Error in package manager settings: package " + name + " has bad userId "
3601 + idStr + " at " + parser.getPositionDescription());
3602 }
3603 } catch (NumberFormatException e) {
3604 PackageManagerService.reportSettingsProblem(Log.WARN,
3605 "Error in package manager settings: package " + name + " has bad userId "
3606 + idStr + " at " + parser.getPositionDescription());
3607 }
3608 if (packageSetting != null) {
3609 packageSetting.uidError = "true".equals(uidError);
3610 packageSetting.installerPackageName = installerPackageName;
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07003611 packageSetting.volumeUuid = volumeUuid;
Narayan Kamathff110bd2014-07-04 18:30:45 +01003612 packageSetting.legacyNativeLibraryPathString = legacyNativeLibraryPathStr;
3613 packageSetting.primaryCpuAbiString = primaryCpuAbiString;
3614 packageSetting.secondaryCpuAbiString = secondaryCpuAbiString;
Amith Yamasani483f3b02012-03-13 16:08:00 -07003615 // Handle legacy string here for single-user mode
3616 final String enabledStr = parser.getAttributeValue(null, ATTR_ENABLED);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003617 if (enabledStr != null) {
Dianne Hackbornb8f40002011-07-19 15:17:43 -07003618 try {
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07003619 packageSetting.setEnabled(Integer.parseInt(enabledStr), 0 /* userId */, null);
Dianne Hackbornb8f40002011-07-19 15:17:43 -07003620 } catch (NumberFormatException e) {
3621 if (enabledStr.equalsIgnoreCase("true")) {
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07003622 packageSetting.setEnabled(COMPONENT_ENABLED_STATE_ENABLED, 0, null);
Dianne Hackbornb8f40002011-07-19 15:17:43 -07003623 } else if (enabledStr.equalsIgnoreCase("false")) {
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07003624 packageSetting.setEnabled(COMPONENT_ENABLED_STATE_DISABLED, 0, null);
Dianne Hackbornb8f40002011-07-19 15:17:43 -07003625 } else if (enabledStr.equalsIgnoreCase("default")) {
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07003626 packageSetting.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 0, null);
Dianne Hackbornb8f40002011-07-19 15:17:43 -07003627 } else {
3628 PackageManagerService.reportSettingsProblem(Log.WARN,
3629 "Error in package manager settings: package " + name
3630 + " has bad enabled value: " + idStr + " at "
3631 + parser.getPositionDescription());
3632 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003633 }
3634 } else {
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07003635 packageSetting.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 0, null);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003636 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003637
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003638 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
3639 if (installStatusStr != null) {
3640 if (installStatusStr.equalsIgnoreCase("false")) {
3641 packageSetting.installStatus = PackageSettingBase.PKG_INSTALL_INCOMPLETE;
3642 } else {
3643 packageSetting.installStatus = PackageSettingBase.PKG_INSTALL_COMPLETE;
3644 }
3645 }
Svet Ganov354cd3c2015-12-17 11:35:04 -08003646
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003647 int outerDepth = parser.getDepth();
3648 int type;
3649 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3650 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3651 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3652 continue;
3653 }
3654
3655 String tagName = parser.getName();
Amith Yamasani483f3b02012-03-13 16:08:00 -07003656 // Legacy
3657 if (tagName.equals(TAG_DISABLED_COMPONENTS)) {
3658 readDisabledComponentsLPw(packageSetting, parser, 0);
3659 } else if (tagName.equals(TAG_ENABLED_COMPONENTS)) {
3660 readEnabledComponentsLPw(packageSetting, parser, 0);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003661 } else if (tagName.equals("sigs")) {
3662 packageSetting.signatures.readXml(parser, mPastSignatures);
Svetoslavc6d1c342015-02-26 14:44:43 -08003663 } else if (tagName.equals(TAG_PERMISSIONS)) {
3664 readInstallPermissionsLPr(parser,
3665 packageSetting.getPermissionsState());
Svetoslavcf959f62015-03-26 20:53:34 -07003666 packageSetting.installPermissionsFixed = true;
dcashman3a0dbfb2014-07-07 13:53:36 -07003667 } else if (tagName.equals("proper-signing-keyset")) {
3668 long id = Long.parseLong(parser.getAttributeValue(null, "identifier"));
dcashman8c04fac2015-03-23 11:39:42 -07003669 Integer refCt = mKeySetRefs.get(id);
3670 if (refCt != null) {
3671 mKeySetRefs.put(id, refCt + 1);
3672 } else {
3673 mKeySetRefs.put(id, 1);
3674 }
dcashman3a0dbfb2014-07-07 13:53:36 -07003675 packageSetting.keySetData.setProperSigningKeySet(id);
Geremy Condraf1bcca82013-01-07 22:35:24 -08003676 } else if (tagName.equals("signing-keyset")) {
dcashman8c04fac2015-03-23 11:39:42 -07003677 // from v1 of keysetmanagerservice - no longer used
dcashman55b10782014-04-09 14:20:38 -07003678 } else if (tagName.equals("upgrade-keyset")) {
3679 long id = Long.parseLong(parser.getAttributeValue(null, "identifier"));
3680 packageSetting.keySetData.addUpgradeKeySetById(id);
Geremy Condraf1bcca82013-01-07 22:35:24 -08003681 } else if (tagName.equals("defined-keyset")) {
3682 long id = Long.parseLong(parser.getAttributeValue(null, "identifier"));
3683 String alias = parser.getAttributeValue(null, "alias");
dcashman8c04fac2015-03-23 11:39:42 -07003684 Integer refCt = mKeySetRefs.get(id);
3685 if (refCt != null) {
3686 mKeySetRefs.put(id, refCt + 1);
3687 } else {
3688 mKeySetRefs.put(id, 1);
3689 }
Geremy Condraf1bcca82013-01-07 22:35:24 -08003690 packageSetting.keySetData.addDefinedKeySet(id, alias);
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08003691 } else if (tagName.equals(TAG_DOMAIN_VERIFICATION)) {
3692 readDomainVerificationLPw(parser, packageSetting);
Svet Ganov354cd3c2015-12-17 11:35:04 -08003693 } else if (tagName.equals(TAG_CHILD_PACKAGE)) {
3694 String childPackageName = parser.getAttributeValue(null, ATTR_NAME);
3695 if (packageSetting.childPackageNames == null) {
3696 packageSetting.childPackageNames = new ArrayList<>();
3697 }
3698 packageSetting.childPackageNames.add(childPackageName);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003699 } else {
3700 PackageManagerService.reportSettingsProblem(Log.WARN,
3701 "Unknown element under <package>: " + parser.getName());
3702 XmlUtils.skipCurrentTag(parser);
3703 }
3704 }
3705 } else {
3706 XmlUtils.skipCurrentTag(parser);
3707 }
3708 }
3709
Amith Yamasani483f3b02012-03-13 16:08:00 -07003710 private void readDisabledComponentsLPw(PackageSettingBase packageSetting, XmlPullParser parser,
3711 int userId) throws IOException, XmlPullParserException {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003712 int outerDepth = parser.getDepth();
3713 int type;
3714 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3715 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3716 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3717 continue;
3718 }
3719
3720 String tagName = parser.getName();
Amith Yamasani483f3b02012-03-13 16:08:00 -07003721 if (tagName.equals(TAG_ITEM)) {
3722 String name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003723 if (name != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003724 packageSetting.addDisabledComponent(name.intern(), userId);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003725 } else {
3726 PackageManagerService.reportSettingsProblem(Log.WARN,
3727 "Error in package manager settings: <disabled-components> has"
3728 + " no name at " + parser.getPositionDescription());
3729 }
3730 } else {
3731 PackageManagerService.reportSettingsProblem(Log.WARN,
3732 "Unknown element under <disabled-components>: " + parser.getName());
3733 }
3734 XmlUtils.skipCurrentTag(parser);
3735 }
3736 }
3737
Amith Yamasani483f3b02012-03-13 16:08:00 -07003738 private void readEnabledComponentsLPw(PackageSettingBase packageSetting, XmlPullParser parser,
3739 int userId) throws IOException, XmlPullParserException {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003740 int outerDepth = parser.getDepth();
3741 int type;
3742 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3743 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3744 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3745 continue;
3746 }
3747
3748 String tagName = parser.getName();
Amith Yamasani483f3b02012-03-13 16:08:00 -07003749 if (tagName.equals(TAG_ITEM)) {
3750 String name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003751 if (name != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003752 packageSetting.addEnabledComponent(name.intern(), userId);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003753 } else {
3754 PackageManagerService.reportSettingsProblem(Log.WARN,
3755 "Error in package manager settings: <enabled-components> has"
3756 + " no name at " + parser.getPositionDescription());
3757 }
3758 } else {
3759 PackageManagerService.reportSettingsProblem(Log.WARN,
3760 "Unknown element under <enabled-components>: " + parser.getName());
3761 }
3762 XmlUtils.skipCurrentTag(parser);
3763 }
3764 }
3765
Amith Yamasani483f3b02012-03-13 16:08:00 -07003766 private void readSharedUserLPw(XmlPullParser parser) throws XmlPullParserException,IOException {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003767 String name = null;
3768 String idStr = null;
3769 int pkgFlags = 0;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003770 int pkgPrivateFlags = 0;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003771 SharedUserSetting su = null;
3772 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003773 name = parser.getAttributeValue(null, ATTR_NAME);
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003774 idStr = parser.getAttributeValue(null, "userId");
3775 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
3776 if ("true".equals(parser.getAttributeValue(null, "system"))) {
3777 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
3778 }
3779 if (name == null) {
3780 PackageManagerService.reportSettingsProblem(Log.WARN,
3781 "Error in package manager settings: <shared-user> has no name at "
3782 + parser.getPositionDescription());
3783 } else if (userId == 0) {
3784 PackageManagerService.reportSettingsProblem(Log.WARN,
3785 "Error in package manager settings: shared-user " + name
3786 + " has bad userId " + idStr + " at "
3787 + parser.getPositionDescription());
3788 } else {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003789 if ((su = addSharedUserLPw(name.intern(), userId, pkgFlags, pkgPrivateFlags))
3790 == null) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003791 PackageManagerService
3792 .reportSettingsProblem(Log.ERROR, "Occurred while parsing settings at "
3793 + parser.getPositionDescription());
3794 }
3795 }
3796 } catch (NumberFormatException e) {
3797 PackageManagerService.reportSettingsProblem(Log.WARN,
3798 "Error in package manager settings: package " + name + " has bad userId "
3799 + idStr + " at " + parser.getPositionDescription());
3800 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003801
3802 if (su != null) {
3803 int outerDepth = parser.getDepth();
3804 int type;
3805 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3806 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3807 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3808 continue;
3809 }
3810
3811 String tagName = parser.getName();
3812 if (tagName.equals("sigs")) {
3813 su.signatures.readXml(parser, mPastSignatures);
3814 } else if (tagName.equals("perms")) {
Svetoslavc6d1c342015-02-26 14:44:43 -08003815 readInstallPermissionsLPr(parser, su.getPermissionsState());
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003816 } else {
3817 PackageManagerService.reportSettingsProblem(Log.WARN,
3818 "Unknown element under <shared-user>: " + parser.getName());
3819 XmlUtils.skipCurrentTag(parser);
3820 }
3821 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003822 } else {
3823 XmlUtils.skipCurrentTag(parser);
3824 }
3825 }
3826
Fyodor Kupolovd8327bd2015-11-30 17:42:43 -08003827 void createNewUserLI(@NonNull PackageManagerService service, @NonNull Installer installer,
3828 int userHandle) {
3829 String[] volumeUuids;
3830 String[] names;
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -07003831 int[] appIds;
Fyodor Kupolovd8327bd2015-11-30 17:42:43 -08003832 String[] seinfos;
Janis Danisevskisf3409742016-01-12 14:46:33 +00003833 int[] targetSdkVersions;
Fyodor Kupolovd8327bd2015-11-30 17:42:43 -08003834 int packagesCount;
3835 synchronized (mPackages) {
3836 Collection<PackageSetting> packages = mPackages.values();
3837 packagesCount = packages.size();
3838 volumeUuids = new String[packagesCount];
3839 names = new String[packagesCount];
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -07003840 appIds = new int[packagesCount];
Fyodor Kupolovd8327bd2015-11-30 17:42:43 -08003841 seinfos = new String[packagesCount];
Janis Danisevskisf3409742016-01-12 14:46:33 +00003842 targetSdkVersions = new int[packagesCount];
Fyodor Kupolovd8327bd2015-11-30 17:42:43 -08003843 Iterator<PackageSetting> packagesIterator = packages.iterator();
3844 for (int i = 0; i < packagesCount; i++) {
3845 PackageSetting ps = packagesIterator.next();
3846 if (ps.pkg == null || ps.pkg.applicationInfo == null) {
3847 continue;
3848 }
3849 // Only system apps are initially installed.
3850 ps.setInstalled(ps.isSystem(), userHandle);
3851 // Need to create a data directory for all apps under this user. Accumulate all
3852 // required args and call the installer after mPackages lock has been released
3853 volumeUuids[i] = ps.volumeUuid;
3854 names[i] = ps.name;
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -07003855 appIds[i] = ps.appId;
Fyodor Kupolovd8327bd2015-11-30 17:42:43 -08003856 seinfos[i] = ps.pkg.applicationInfo.seinfo;
Janis Danisevskisf3409742016-01-12 14:46:33 +00003857 targetSdkVersions[i] = ps.pkg.applicationInfo.targetSdkVersion;
Fyodor Kupolovd8327bd2015-11-30 17:42:43 -08003858 }
3859 }
3860 for (int i = 0; i < packagesCount; i++) {
3861 if (names[i] == null) {
Amith Yamasani41cd5772014-07-10 15:26:00 -07003862 continue;
3863 }
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -07003864 // TODO: triage flags!
Jeff Sharkey47f71082016-02-01 17:03:54 -07003865 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -07003866 try {
3867 installer.createAppData(volumeUuids[i], names[i], userHandle, flags, appIds[i],
Janis Danisevskisf3409742016-01-12 14:46:33 +00003868 seinfos[i], targetSdkVersions[i]);
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -07003869 } catch (InstallerException e) {
3870 Slog.w(TAG, "Failed to prepare app data", e);
3871 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003872 }
Fyodor Kupolovd8327bd2015-11-30 17:42:43 -08003873 synchronized (mPackages) {
3874 applyDefaultPreferredAppsLPw(service, userHandle);
3875 writePackageRestrictionsLPr(userHandle);
3876 writePackageListLPr(userHandle);
3877 }
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003878 }
3879
Alexandra Gherghina539a7ef2014-07-07 12:27:54 +01003880 void removeUserLPw(int userId) {
Dianne Hackborn63092712012-10-07 14:45:35 -07003881 Set<Entry<String, PackageSetting>> entries = mPackages.entrySet();
3882 for (Entry<String, PackageSetting> entry : entries) {
3883 entry.getValue().removeUser(userId);
3884 }
3885 mPreferredActivities.remove(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07003886 File file = getUserPackagesStateFile(userId);
3887 file.delete();
3888 file = getUserPackagesStateBackupFile(userId);
3889 file.delete();
Nicolas Prevote7024042014-07-08 15:47:17 +01003890 removeCrossProfileIntentFiltersLPw(userId);
Svetoslavc6d1c342015-02-26 14:44:43 -08003891
3892 mRuntimePermissionsPersistence.onUserRemoved(userId);
Jeff Sharkey91edde22015-05-20 12:04:42 -07003893
3894 writePackageListLPr();
Nicolas Prevota0f48852014-05-27 11:21:11 +01003895 }
3896
Nicolas Prevote7024042014-07-08 15:47:17 +01003897 void removeCrossProfileIntentFiltersLPw(int userId) {
3898 synchronized (mCrossProfileIntentResolvers) {
3899 // userId is the source user
3900 if (mCrossProfileIntentResolvers.get(userId) != null) {
3901 mCrossProfileIntentResolvers.remove(userId);
3902 writePackageRestrictionsLPr(userId);
Nicolas Prevota0f48852014-05-27 11:21:11 +01003903 }
Nicolas Prevote7024042014-07-08 15:47:17 +01003904 // userId is the target user
3905 int count = mCrossProfileIntentResolvers.size();
3906 for (int i = 0; i < count; i++) {
3907 int sourceUserId = mCrossProfileIntentResolvers.keyAt(i);
3908 CrossProfileIntentResolver cpir = mCrossProfileIntentResolvers.get(sourceUserId);
3909 boolean needsWriting = false;
Jeff Sharkey9f837a92014-10-24 12:07:24 -07003910 ArraySet<CrossProfileIntentFilter> cpifs =
3911 new ArraySet<CrossProfileIntentFilter>(cpir.filterSet());
Nicolas Prevote7024042014-07-08 15:47:17 +01003912 for (CrossProfileIntentFilter cpif : cpifs) {
3913 if (cpif.getTargetUserId() == userId) {
3914 needsWriting = true;
3915 cpir.removeFilter(cpif);
3916 }
3917 }
3918 if (needsWriting) {
3919 writePackageRestrictionsLPr(sourceUserId);
3920 }
Nicolas Prevota0f48852014-05-27 11:21:11 +01003921 }
3922 }
Amith Yamasani13593602012-03-22 16:16:17 -07003923 }
3924
Geremy Condra12c18382013-03-06 16:49:06 -08003925 // This should be called (at least) whenever an application is removed
3926 private void setFirstAvailableUid(int uid) {
3927 if (uid > mFirstAvailableUid) {
3928 mFirstAvailableUid = uid;
3929 }
3930 }
3931
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003932 // Returns -1 if we could not find an available UserId to assign
Kenny Root447106f2011-03-23 11:00:15 -07003933 private int newUserIdLPw(Object obj) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003934 // Let's be stupidly inefficient for now...
3935 final int N = mUserIds.size();
Geremy Condra12c18382013-03-06 16:49:06 -08003936 for (int i = mFirstAvailableUid; i < N; i++) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003937 if (mUserIds.get(i) == null) {
3938 mUserIds.set(i, obj);
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003939 return Process.FIRST_APPLICATION_UID + i;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003940 }
3941 }
3942
3943 // None left?
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003944 if (N > (Process.LAST_APPLICATION_UID-Process.FIRST_APPLICATION_UID)) {
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003945 return -1;
3946 }
3947
3948 mUserIds.add(obj);
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003949 return Process.FIRST_APPLICATION_UID + N;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003950 }
3951
Kenny Root0aaa0d92011-09-12 16:42:55 -07003952 public VerifierDeviceIdentity getVerifierDeviceIdentityLPw() {
3953 if (mVerifierDeviceIdentity == null) {
3954 mVerifierDeviceIdentity = VerifierDeviceIdentity.generate();
3955
3956 writeLPr();
3957 }
3958
3959 return mVerifierDeviceIdentity;
3960 }
3961
Svet Ganov354cd3c2015-12-17 11:35:04 -08003962 public boolean hasOtherDisabledSystemPkgWithChildLPr(String parentPackageName,
3963 String childPackageName) {
3964 final int packageCount = mDisabledSysPackages.size();
3965 for (int i = 0; i < packageCount; i++) {
3966 PackageSetting disabledPs = mDisabledSysPackages.valueAt(i);
3967 if (disabledPs.childPackageNames == null || disabledPs.childPackageNames.isEmpty()) {
3968 continue;
3969 }
3970 if (disabledPs.name.equals(parentPackageName)) {
3971 continue;
3972 }
3973 final int childCount = disabledPs.childPackageNames.size();
3974 for (int j = 0; j < childCount; j++) {
3975 String currChildPackageName = disabledPs.childPackageNames.get(j);
3976 if (currChildPackageName.equals(childPackageName)) {
3977 return true;
3978 }
3979 }
3980 }
3981 return false;
3982 }
3983
Kenny Root447106f2011-03-23 11:00:15 -07003984 public PackageSetting getDisabledSystemPkgLPr(String name) {
3985 PackageSetting ps = mDisabledSysPackages.get(name);
3986 return ps;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003987 }
3988
Jeff Sharkey9f837a92014-10-24 12:07:24 -07003989 private String compToString(ArraySet<String> cmp) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003990 return cmp != null ? Arrays.toString(cmp.toArray()) : "[]";
3991 }
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003992
Jeff Sharkey5217cac2015-12-20 15:34:01 -07003993 boolean isEnabledAndMatchLPr(ComponentInfo componentInfo, int flags, int userId) {
Jeff Sharkey2bd31db2016-01-09 16:58:14 -07003994 final PackageSetting ps = mPackages.get(componentInfo.packageName);
3995 if (ps == null) return false;
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003996
Jeff Sharkey2bd31db2016-01-09 16:58:14 -07003997 final PackageUserState userState = ps.readUserState(userId);
3998 return userState.isMatch(componentInfo, flags);
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003999 }
4000
Kenny Root447106f2011-03-23 11:00:15 -07004001 String getInstallerPackageNameLPr(String packageName) {
4002 final PackageSetting pkg = mPackages.get(packageName);
4003 if (pkg == null) {
4004 throw new IllegalArgumentException("Unknown package: " + packageName);
4005 }
4006 return pkg.installerPackageName;
4007 }
4008
Amith Yamasani483f3b02012-03-13 16:08:00 -07004009 int getApplicationEnabledSettingLPr(String packageName, int userId) {
Kenny Root447106f2011-03-23 11:00:15 -07004010 final PackageSetting pkg = mPackages.get(packageName);
4011 if (pkg == null) {
4012 throw new IllegalArgumentException("Unknown package: " + packageName);
4013 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07004014 return pkg.getEnabled(userId);
Kenny Root447106f2011-03-23 11:00:15 -07004015 }
4016
Amith Yamasani483f3b02012-03-13 16:08:00 -07004017 int getComponentEnabledSettingLPr(ComponentName componentName, int userId) {
Kenny Root447106f2011-03-23 11:00:15 -07004018 final String packageName = componentName.getPackageName();
4019 final PackageSetting pkg = mPackages.get(packageName);
4020 if (pkg == null) {
4021 throw new IllegalArgumentException("Unknown component: " + componentName);
4022 }
4023 final String classNameStr = componentName.getClassName();
Amith Yamasani483f3b02012-03-13 16:08:00 -07004024 return pkg.getCurrentEnabledStateLPr(classNameStr, userId);
Kenny Root447106f2011-03-23 11:00:15 -07004025 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07004026
Jeff Sharkeybd0e9e42015-04-30 16:04:50 -07004027 boolean setPackageStoppedStateLPw(PackageManagerService yucky, String packageName,
4028 boolean stopped, boolean allowedByPermission, int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004029 int appId = UserHandle.getAppId(uid);
Kenny Root447106f2011-03-23 11:00:15 -07004030 final PackageSetting pkgSetting = mPackages.get(packageName);
4031 if (pkgSetting == null) {
4032 throw new IllegalArgumentException("Unknown package: " + packageName);
4033 }
Amith Yamasani13593602012-03-22 16:16:17 -07004034 if (!allowedByPermission && (appId != pkgSetting.appId)) {
Kenny Root447106f2011-03-23 11:00:15 -07004035 throw new SecurityException(
4036 "Permission Denial: attempt to change stopped state from pid="
4037 + Binder.getCallingPid()
Amith Yamasani13593602012-03-22 16:16:17 -07004038 + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
Kenny Root447106f2011-03-23 11:00:15 -07004039 }
4040 if (DEBUG_STOPPED) {
4041 if (stopped) {
4042 RuntimeException e = new RuntimeException("here");
4043 e.fillInStackTrace();
4044 Slog.i(TAG, "Stopping package " + packageName, e);
4045 }
4046 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07004047 if (pkgSetting.getStopped(userId) != stopped) {
4048 pkgSetting.setStopped(stopped, userId);
4049 // pkgSetting.pkg.mSetStopped = stopped;
4050 if (pkgSetting.getNotLaunched(userId)) {
Kenny Root447106f2011-03-23 11:00:15 -07004051 if (pkgSetting.installerPackageName != null) {
Jeff Sharkeybd0e9e42015-04-30 16:04:50 -07004052 yucky.sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH,
Dianne Hackbornf36003f2015-11-11 13:24:11 -08004053 pkgSetting.name, null, 0,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07004054 pkgSetting.installerPackageName, null, new int[] {userId});
Kenny Root447106f2011-03-23 11:00:15 -07004055 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07004056 pkgSetting.setNotLaunched(false, userId);
Kenny Root447106f2011-03-23 11:00:15 -07004057 }
4058 return true;
4059 }
4060 return false;
4061 }
4062
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08004063 List<UserInfo> getAllUsers() {
Amith Yamasani7ea3e7d2012-04-20 15:19:35 -07004064 long id = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07004065 try {
Amith Yamasani920ace02012-09-20 22:15:37 -07004066 return UserManagerService.getInstance().getUsers(false);
Amith Yamasani483f3b02012-03-13 16:08:00 -07004067 } catch (NullPointerException npe) {
4068 // packagemanager not yet initialized
Amith Yamasani7ea3e7d2012-04-20 15:19:35 -07004069 } finally {
4070 Binder.restoreCallingIdentity(id);
Amith Yamasani483f3b02012-03-13 16:08:00 -07004071 }
4072 return null;
4073 }
4074
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07004075 /**
4076 * Return all {@link PackageSetting} that are actively installed on the
4077 * given {@link VolumeInfo#fsUuid}.
4078 */
4079 List<PackageSetting> getVolumePackagesLPr(String volumeUuid) {
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07004080 ArrayList<PackageSetting> res = new ArrayList<>();
4081 for (int i = 0; i < mPackages.size(); i++) {
4082 final PackageSetting setting = mPackages.valueAt(i);
4083 if (Objects.equals(volumeUuid, setting.volumeUuid)) {
4084 res.add(setting);
4085 }
4086 }
4087 return res;
4088 }
4089
Svetoslavc6d1c342015-02-26 14:44:43 -08004090 static void printFlags(PrintWriter pw, int val, Object[] spec) {
Joe Onorato20963df2012-01-04 18:13:24 -08004091 pw.print("[ ");
4092 for (int i=0; i<spec.length; i+=2) {
4093 int mask = (Integer)spec[i];
4094 if ((val & mask) != 0) {
4095 pw.print(spec[i+1]);
4096 pw.print(" ");
4097 }
4098 }
4099 pw.print("]");
4100 }
4101
4102 static final Object[] FLAG_DUMP_SPEC = new Object[] {
4103 ApplicationInfo.FLAG_SYSTEM, "SYSTEM",
4104 ApplicationInfo.FLAG_DEBUGGABLE, "DEBUGGABLE",
4105 ApplicationInfo.FLAG_HAS_CODE, "HAS_CODE",
4106 ApplicationInfo.FLAG_PERSISTENT, "PERSISTENT",
4107 ApplicationInfo.FLAG_FACTORY_TEST, "FACTORY_TEST",
4108 ApplicationInfo.FLAG_ALLOW_TASK_REPARENTING, "ALLOW_TASK_REPARENTING",
4109 ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA, "ALLOW_CLEAR_USER_DATA",
4110 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, "UPDATED_SYSTEM_APP",
4111 ApplicationInfo.FLAG_TEST_ONLY, "TEST_ONLY",
4112 ApplicationInfo.FLAG_VM_SAFE_MODE, "VM_SAFE_MODE",
4113 ApplicationInfo.FLAG_ALLOW_BACKUP, "ALLOW_BACKUP",
4114 ApplicationInfo.FLAG_KILL_AFTER_RESTORE, "KILL_AFTER_RESTORE",
4115 ApplicationInfo.FLAG_RESTORE_ANY_VERSION, "RESTORE_ANY_VERSION",
4116 ApplicationInfo.FLAG_EXTERNAL_STORAGE, "EXTERNAL_STORAGE",
4117 ApplicationInfo.FLAG_LARGE_HEAP, "LARGE_HEAP",
Alex Klyubinb9f8a522015-02-03 11:12:59 -08004118 };
4119
4120 static final Object[] PRIVATE_FLAG_DUMP_SPEC = new Object[] {
4121 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED, "PRIVILEGED",
4122 ApplicationInfo.PRIVATE_FLAG_FORWARD_LOCK, "FORWARD_LOCK",
4123 ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE, "CANT_SAVE_STATE",
Joe Onorato20963df2012-01-04 18:13:24 -08004124 };
4125
Jeff Sharkeyf80b52b2015-07-17 14:56:34 -07004126 void dumpVersionLPr(IndentingPrintWriter pw) {
4127 pw.increaseIndent();
4128 for (int i= 0; i < mVersion.size(); i++) {
4129 final String volumeUuid = mVersion.keyAt(i);
4130 final VersionInfo ver = mVersion.valueAt(i);
4131 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
4132 pw.println("Internal:");
4133 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
4134 pw.println("External:");
4135 } else {
4136 pw.println("UUID " + volumeUuid + ":");
4137 }
4138 pw.increaseIndent();
4139 pw.printPair("sdkVersion", ver.sdkVersion);
4140 pw.printPair("databaseVersion", ver.databaseVersion);
4141 pw.println();
4142 pw.printPair("fingerprint", ver.fingerprint);
4143 pw.println();
4144 pw.decreaseIndent();
4145 }
4146 pw.decreaseIndent();
4147 }
4148
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004149 void dumpPackageLPr(PrintWriter pw, String prefix, String checkinTag,
4150 ArraySet<String> permissionNames, PackageSetting ps, SimpleDateFormat sdf,
Dianne Hackborn9f5b0a22015-08-13 18:25:20 -07004151 Date date, List<UserInfo> users, boolean dumpAll) {
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004152 if (checkinTag != null) {
4153 pw.print(checkinTag);
4154 pw.print(",");
4155 pw.print(ps.realName != null ? ps.realName : ps.name);
4156 pw.print(",");
4157 pw.print(ps.appId);
4158 pw.print(",");
4159 pw.print(ps.versionCode);
4160 pw.print(",");
4161 pw.print(ps.firstInstallTime);
4162 pw.print(",");
4163 pw.print(ps.lastUpdateTime);
4164 pw.print(",");
4165 pw.print(ps.installerPackageName != null ? ps.installerPackageName : "?");
4166 pw.println();
Jeff Sharkeyc4d05fc2014-12-01 16:24:01 -08004167 if (ps.pkg != null) {
4168 pw.print(checkinTag); pw.print("-"); pw.print("splt,");
4169 pw.print("base,");
4170 pw.println(ps.pkg.baseRevisionCode);
4171 if (ps.pkg.splitNames != null) {
4172 for (int i = 0; i < ps.pkg.splitNames.length; i++) {
4173 pw.print(checkinTag); pw.print("-"); pw.print("splt,");
4174 pw.print(ps.pkg.splitNames[i]); pw.print(",");
4175 pw.println(ps.pkg.splitRevisionCodes[i]);
4176 }
4177 }
4178 }
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004179 for (UserInfo user : users) {
4180 pw.print(checkinTag);
4181 pw.print("-");
4182 pw.print("usr");
4183 pw.print(",");
4184 pw.print(user.id);
4185 pw.print(",");
4186 pw.print(ps.getInstalled(user.id) ? "I" : "i");
Amith Yamasanie5bcff62014-07-19 15:44:09 -07004187 pw.print(ps.getHidden(user.id) ? "B" : "b");
Andrei Stingaceanu1e283912015-11-26 15:26:28 +00004188 pw.print(ps.getSuspended(user.id) ? "SU" : "su");
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004189 pw.print(ps.getStopped(user.id) ? "S" : "s");
4190 pw.print(ps.getNotLaunched(user.id) ? "l" : "L");
4191 pw.print(",");
4192 pw.print(ps.getEnabled(user.id));
4193 String lastDisabledAppCaller = ps.getLastDisabledAppCaller(user.id);
4194 pw.print(",");
4195 pw.print(lastDisabledAppCaller != null ? lastDisabledAppCaller : "?");
4196 pw.println();
4197 }
4198 return;
4199 }
4200
Dianne Hackbornc895be72013-03-11 17:48:43 -07004201 pw.print(prefix); pw.print("Package [");
4202 pw.print(ps.realName != null ? ps.realName : ps.name);
4203 pw.print("] (");
4204 pw.print(Integer.toHexString(System.identityHashCode(ps)));
4205 pw.println("):");
4206
Jeff Sharkeye31b8202015-04-29 21:44:57 -07004207 if (ps.frozen) {
4208 pw.print(prefix); pw.println(" FROZEN!");
4209 }
4210
Dianne Hackbornc895be72013-03-11 17:48:43 -07004211 if (ps.realName != null) {
4212 pw.print(prefix); pw.print(" compat name=");
4213 pw.println(ps.name);
4214 }
4215
Svetoslavc6d1c342015-02-26 14:44:43 -08004216 pw.print(prefix); pw.print(" userId="); pw.println(ps.appId);
4217
Dianne Hackbornc895be72013-03-11 17:48:43 -07004218 if (ps.sharedUser != null) {
4219 pw.print(prefix); pw.print(" sharedUser="); pw.println(ps.sharedUser);
4220 }
4221 pw.print(prefix); pw.print(" pkg="); pw.println(ps.pkg);
4222 pw.print(prefix); pw.print(" codePath="); pw.println(ps.codePathString);
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004223 if (permissionNames == null) {
4224 pw.print(prefix); pw.print(" resourcePath="); pw.println(ps.resourcePathString);
4225 pw.print(prefix); pw.print(" legacyNativeLibraryDir=");
4226 pw.println(ps.legacyNativeLibraryPathString);
4227 pw.print(prefix); pw.print(" primaryCpuAbi="); pw.println(ps.primaryCpuAbiString);
4228 pw.print(prefix); pw.print(" secondaryCpuAbi="); pw.println(ps.secondaryCpuAbiString);
4229 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004230 pw.print(prefix); pw.print(" versionCode="); pw.print(ps.versionCode);
4231 if (ps.pkg != null) {
4232 pw.print(" targetSdk="); pw.print(ps.pkg.applicationInfo.targetSdkVersion);
4233 }
4234 pw.println();
4235 if (ps.pkg != null) {
Svet Ganov354cd3c2015-12-17 11:35:04 -08004236 if (ps.pkg.parentPackage != null) {
4237 PackageParser.Package parentPkg = ps.pkg.parentPackage;
4238 PackageSetting pps = mPackages.get(parentPkg.packageName);
4239 if (pps == null || !pps.codePathString.equals(parentPkg.codePath)) {
4240 pps = mDisabledSysPackages.get(parentPkg.packageName);
4241 }
4242 if (pps != null) {
4243 pw.print(prefix); pw.print(" parentPackage=");
4244 pw.println(pps.realName != null ? pps.realName : pps.name);
4245 }
4246 } else if (ps.pkg.childPackages != null) {
4247 pw.print(prefix); pw.print(" childPackages=[");
4248 final int childCount = ps.pkg.childPackages.size();
4249 for (int i = 0; i < childCount; i++) {
4250 PackageParser.Package childPkg = ps.pkg.childPackages.get(i);
4251 PackageSetting cps = mPackages.get(childPkg.packageName);
4252 if (cps == null || !cps.codePathString.equals(childPkg.codePath)) {
4253 cps = mDisabledSysPackages.get(childPkg.packageName);
4254 }
4255 if (cps != null) {
4256 if (i > 0) {
4257 pw.print(", ");
4258 }
4259 pw.print(cps.realName != null ? cps.realName : cps.name);
4260 }
4261 }
4262 pw.println("]");
4263 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004264 pw.print(prefix); pw.print(" versionName="); pw.println(ps.pkg.mVersionName);
Jeff Sharkeyc4d05fc2014-12-01 16:24:01 -08004265 pw.print(prefix); pw.print(" splits="); dumpSplitNames(pw, ps.pkg); pw.println();
Dianne Hackbornc895be72013-03-11 17:48:43 -07004266 pw.print(prefix); pw.print(" applicationInfo=");
4267 pw.println(ps.pkg.applicationInfo.toString());
4268 pw.print(prefix); pw.print(" flags="); printFlags(pw, ps.pkg.applicationInfo.flags,
4269 FLAG_DUMP_SPEC); pw.println();
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004270 if (ps.pkg.applicationInfo.privateFlags != 0) {
4271 pw.print(prefix); pw.print(" privateFlags="); printFlags(pw,
4272 ps.pkg.applicationInfo.privateFlags, PRIVATE_FLAG_DUMP_SPEC); pw.println();
4273 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004274 pw.print(prefix); pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Dianne Hackbornc895be72013-03-11 17:48:43 -07004275 pw.print(prefix); pw.print(" supportsScreens=[");
4276 boolean first = true;
4277 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
4278 if (!first)
4279 pw.print(", ");
4280 first = false;
4281 pw.print("small");
4282 }
4283 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
4284 if (!first)
4285 pw.print(", ");
4286 first = false;
4287 pw.print("medium");
4288 }
4289 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
4290 if (!first)
4291 pw.print(", ");
4292 first = false;
4293 pw.print("large");
4294 }
4295 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
4296 if (!first)
4297 pw.print(", ");
4298 first = false;
4299 pw.print("xlarge");
4300 }
4301 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
4302 if (!first)
4303 pw.print(", ");
4304 first = false;
4305 pw.print("resizeable");
4306 }
4307 if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
4308 if (!first)
4309 pw.print(", ");
4310 first = false;
4311 pw.print("anyDensity");
4312 }
4313 pw.println("]");
4314 if (ps.pkg.libraryNames != null && ps.pkg.libraryNames.size() > 0) {
4315 pw.print(prefix); pw.println(" libraries:");
4316 for (int i=0; i<ps.pkg.libraryNames.size(); i++) {
4317 pw.print(prefix); pw.print(" "); pw.println(ps.pkg.libraryNames.get(i));
4318 }
4319 }
4320 if (ps.pkg.usesLibraries != null && ps.pkg.usesLibraries.size() > 0) {
4321 pw.print(prefix); pw.println(" usesLibraries:");
4322 for (int i=0; i<ps.pkg.usesLibraries.size(); i++) {
4323 pw.print(prefix); pw.print(" "); pw.println(ps.pkg.usesLibraries.get(i));
4324 }
4325 }
4326 if (ps.pkg.usesOptionalLibraries != null
4327 && ps.pkg.usesOptionalLibraries.size() > 0) {
4328 pw.print(prefix); pw.println(" usesOptionalLibraries:");
4329 for (int i=0; i<ps.pkg.usesOptionalLibraries.size(); i++) {
4330 pw.print(prefix); pw.print(" ");
4331 pw.println(ps.pkg.usesOptionalLibraries.get(i));
4332 }
4333 }
4334 if (ps.pkg.usesLibraryFiles != null
4335 && ps.pkg.usesLibraryFiles.length > 0) {
4336 pw.print(prefix); pw.println(" usesLibraryFiles:");
4337 for (int i=0; i<ps.pkg.usesLibraryFiles.length; i++) {
4338 pw.print(prefix); pw.print(" "); pw.println(ps.pkg.usesLibraryFiles[i]);
4339 }
4340 }
4341 }
4342 pw.print(prefix); pw.print(" timeStamp=");
4343 date.setTime(ps.timeStamp);
4344 pw.println(sdf.format(date));
4345 pw.print(prefix); pw.print(" firstInstallTime=");
4346 date.setTime(ps.firstInstallTime);
4347 pw.println(sdf.format(date));
4348 pw.print(prefix); pw.print(" lastUpdateTime=");
4349 date.setTime(ps.lastUpdateTime);
4350 pw.println(sdf.format(date));
4351 if (ps.installerPackageName != null) {
4352 pw.print(prefix); pw.print(" installerPackageName=");
4353 pw.println(ps.installerPackageName);
4354 }
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07004355 if (ps.volumeUuid != null) {
4356 pw.print(prefix); pw.print(" volumeUuid=");
4357 pw.println(ps.volumeUuid);
4358 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004359 pw.print(prefix); pw.print(" signatures="); pw.println(ps.signatures);
Svetoslavcf959f62015-03-26 20:53:34 -07004360 pw.print(prefix); pw.print(" installPermissionsFixed=");
4361 pw.print(ps.installPermissionsFixed);
Dianne Hackbornc895be72013-03-11 17:48:43 -07004362 pw.print(" installStatus="); pw.println(ps.installStatus);
4363 pw.print(prefix); pw.print(" pkgFlags="); printFlags(pw, ps.pkgFlags, FLAG_DUMP_SPEC);
4364 pw.println();
Svetoslavc6d1c342015-02-26 14:44:43 -08004365
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004366 if (ps.pkg != null && ps.pkg.permissions != null && ps.pkg.permissions.size() > 0) {
4367 final ArrayList<PackageParser.Permission> perms = ps.pkg.permissions;
4368 pw.print(prefix); pw.println(" declared permissions:");
4369 for (int i=0; i<perms.size(); i++) {
4370 PackageParser.Permission perm = perms.get(i);
4371 if (permissionNames != null
4372 && !permissionNames.contains(perm.info.name)) {
4373 continue;
4374 }
4375 pw.print(prefix); pw.print(" "); pw.print(perm.info.name);
4376 pw.print(": prot=");
4377 pw.print(PermissionInfo.protectionToString(perm.info.protectionLevel));
4378 if ((perm.info.flags&PermissionInfo.FLAG_COSTS_MONEY) != 0) {
4379 pw.print(", COSTS_MONEY");
4380 }
Svet Ganov3e0be742015-08-07 23:06:00 -07004381 if ((perm.info.flags&PermissionInfo.FLAG_HIDDEN) != 0) {
Svet Ganov52153f42015-08-11 08:59:12 -07004382 pw.print(", HIDDEN");
Svet Ganov3e0be742015-08-07 23:06:00 -07004383 }
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004384 if ((perm.info.flags&PermissionInfo.FLAG_INSTALLED) != 0) {
4385 pw.print(", INSTALLED");
4386 }
4387 pw.println();
4388 }
4389 }
4390
Dianne Hackborn9f5b0a22015-08-13 18:25:20 -07004391 if ((permissionNames != null || dumpAll) && ps.pkg.requestedPermissions != null
4392 && ps.pkg.requestedPermissions.size() > 0) {
4393 final ArrayList<String> perms = ps.pkg.requestedPermissions;
4394 pw.print(prefix); pw.println(" requested permissions:");
4395 for (int i=0; i<perms.size(); i++) {
4396 String perm = perms.get(i);
4397 if (permissionNames != null
4398 && !permissionNames.contains(perm)) {
4399 continue;
4400 }
4401 pw.print(prefix); pw.print(" "); pw.println(perm);
4402 }
4403 }
4404
4405 if (ps.sharedUser == null || permissionNames != null || dumpAll) {
Svetoslavc6d1c342015-02-26 14:44:43 -08004406 PermissionsState permissionsState = ps.getPermissionsState();
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004407 dumpInstallPermissionsLPr(pw, prefix + " ", permissionNames, permissionsState);
Svetoslavc6d1c342015-02-26 14:44:43 -08004408 }
4409
Dianne Hackbornc895be72013-03-11 17:48:43 -07004410 for (UserInfo user : users) {
4411 pw.print(prefix); pw.print(" User "); pw.print(user.id); pw.print(": ");
4412 pw.print(" installed=");
4413 pw.print(ps.getInstalled(user.id));
Amith Yamasanie5bcff62014-07-19 15:44:09 -07004414 pw.print(" hidden=");
4415 pw.print(ps.getHidden(user.id));
Andrei Stingaceanu1e283912015-11-26 15:26:28 +00004416 pw.print(" suspended=");
4417 pw.print(ps.getSuspended(user.id));
Dianne Hackbornc895be72013-03-11 17:48:43 -07004418 pw.print(" stopped=");
4419 pw.print(ps.getStopped(user.id));
4420 pw.print(" notLaunched=");
4421 pw.print(ps.getNotLaunched(user.id));
4422 pw.print(" enabled=");
4423 pw.println(ps.getEnabled(user.id));
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07004424 String lastDisabledAppCaller = ps.getLastDisabledAppCaller(user.id);
4425 if (lastDisabledAppCaller != null) {
4426 pw.print(prefix); pw.print(" lastDisabledCaller: ");
4427 pw.println(lastDisabledAppCaller);
4428 }
Svetoslavc6d1c342015-02-26 14:44:43 -08004429
4430 if (ps.sharedUser == null) {
4431 PermissionsState permissionsState = ps.getPermissionsState();
4432 dumpGidsLPr(pw, prefix + " ", permissionsState.computeGids(user.id));
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004433 dumpRuntimePermissionsLPr(pw, prefix + " ", permissionNames, permissionsState
Dianne Hackborn9f5b0a22015-08-13 18:25:20 -07004434 .getRuntimePermissionStates(user.id), dumpAll);
Svetoslavc6d1c342015-02-26 14:44:43 -08004435 }
4436
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004437 if (permissionNames == null) {
4438 ArraySet<String> cmp = ps.getDisabledComponents(user.id);
4439 if (cmp != null && cmp.size() > 0) {
4440 pw.print(prefix); pw.println(" disabledComponents:");
4441 for (String s : cmp) {
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004442 pw.print(prefix); pw.print(" "); pw.println(s);
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004443 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004444 }
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004445 cmp = ps.getEnabledComponents(user.id);
4446 if (cmp != null && cmp.size() > 0) {
4447 pw.print(prefix); pw.println(" enabledComponents:");
4448 for (String s : cmp) {
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004449 pw.print(prefix); pw.print(" "); pw.println(s);
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004450 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004451 }
4452 }
4453 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004454 }
4455
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004456 void dumpPackagesLPr(PrintWriter pw, String packageName, ArraySet<String> permissionNames,
4457 DumpState dumpState, boolean checkin) {
Kenny Root447106f2011-03-23 11:00:15 -07004458 final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
4459 final Date date = new Date();
4460 boolean printedSomething = false;
Amith Yamasani7ea3e7d2012-04-20 15:19:35 -07004461 List<UserInfo> users = getAllUsers();
Kenny Root447106f2011-03-23 11:00:15 -07004462 for (final PackageSetting ps : mPackages.values()) {
4463 if (packageName != null && !packageName.equals(ps.realName)
4464 && !packageName.equals(ps.name)) {
4465 continue;
4466 }
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004467 if (permissionNames != null
4468 && !ps.getPermissionsState().hasRequestedPermission(permissionNames)) {
4469 continue;
4470 }
Kenny Root447106f2011-03-23 11:00:15 -07004471
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004472 if (!checkin && packageName != null) {
Kenny Root447106f2011-03-23 11:00:15 -07004473 dumpState.setSharedUser(ps.sharedUser);
4474 }
4475
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004476 if (!checkin && !printedSomething) {
Kenny Root447106f2011-03-23 11:00:15 -07004477 if (dumpState.onTitlePrinted())
Dianne Hackborncbfd23e2013-06-11 14:26:53 -07004478 pw.println();
Kenny Root447106f2011-03-23 11:00:15 -07004479 pw.println("Packages:");
4480 printedSomething = true;
4481 }
Dianne Hackborn9f5b0a22015-08-13 18:25:20 -07004482 dumpPackageLPr(pw, " ", checkin ? "pkg" : null, permissionNames, ps, sdf, date, users,
4483 packageName != null);
Kenny Root447106f2011-03-23 11:00:15 -07004484 }
4485
4486 printedSomething = false;
Dianne Hackborn9f5b0a22015-08-13 18:25:20 -07004487 if (mRenamedPackages.size() > 0 && permissionNames == null) {
Andy McFadden2f362292012-01-20 14:43:38 -08004488 for (final Map.Entry<String, String> e : mRenamedPackages.entrySet()) {
Kenny Root447106f2011-03-23 11:00:15 -07004489 if (packageName != null && !packageName.equals(e.getKey())
4490 && !packageName.equals(e.getValue())) {
4491 continue;
4492 }
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004493 if (!checkin) {
4494 if (!printedSomething) {
4495 if (dumpState.onTitlePrinted())
4496 pw.println();
4497 pw.println("Renamed packages:");
4498 printedSomething = true;
4499 }
4500 pw.print(" ");
4501 } else {
4502 pw.print("ren,");
Kenny Root447106f2011-03-23 11:00:15 -07004503 }
Kenny Root447106f2011-03-23 11:00:15 -07004504 pw.print(e.getKey());
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004505 pw.print(checkin ? " -> " : ",");
Kenny Root447106f2011-03-23 11:00:15 -07004506 pw.println(e.getValue());
4507 }
4508 }
4509
4510 printedSomething = false;
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004511 if (mDisabledSysPackages.size() > 0 && permissionNames == null) {
Kenny Root447106f2011-03-23 11:00:15 -07004512 for (final PackageSetting ps : mDisabledSysPackages.values()) {
4513 if (packageName != null && !packageName.equals(ps.realName)
4514 && !packageName.equals(ps.name)) {
4515 continue;
4516 }
Dianne Hackborn60dc0d92014-01-17 13:29:21 -08004517 if (!checkin && !printedSomething) {
Kenny Root447106f2011-03-23 11:00:15 -07004518 if (dumpState.onTitlePrinted())
Dianne Hackborncbfd23e2013-06-11 14:26:53 -07004519 pw.println();
Kenny Root447106f2011-03-23 11:00:15 -07004520 pw.println("Hidden system packages:");
4521 printedSomething = true;
4522 }
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004523 dumpPackageLPr(pw, " ", checkin ? "dis" : null, permissionNames, ps, sdf, date,
Dianne Hackborn9f5b0a22015-08-13 18:25:20 -07004524 users, packageName != null);
Kenny Root447106f2011-03-23 11:00:15 -07004525 }
4526 }
4527 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07004528
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004529 void dumpPermissionsLPr(PrintWriter pw, String packageName, ArraySet<String> permissionNames,
4530 DumpState dumpState) {
Kenny Root447106f2011-03-23 11:00:15 -07004531 boolean printedSomething = false;
4532 for (BasePermission p : mPermissions.values()) {
4533 if (packageName != null && !packageName.equals(p.sourcePackage)) {
4534 continue;
4535 }
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004536 if (permissionNames != null && !permissionNames.contains(p.name)) {
4537 continue;
4538 }
Kenny Root447106f2011-03-23 11:00:15 -07004539 if (!printedSomething) {
4540 if (dumpState.onTitlePrinted())
Dianne Hackborncbfd23e2013-06-11 14:26:53 -07004541 pw.println();
Kenny Root447106f2011-03-23 11:00:15 -07004542 pw.println("Permissions:");
4543 printedSomething = true;
4544 }
4545 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
4546 pw.print(Integer.toHexString(System.identityHashCode(p)));
4547 pw.println("):");
4548 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
4549 pw.print(" uid="); pw.print(p.uid);
Jeff Sharkey00f39042015-03-23 16:51:22 -07004550 pw.print(" gids="); pw.print(Arrays.toString(
Xiaohui Chen594f2082015-08-18 11:04:20 -07004551 p.computeGids(UserHandle.USER_SYSTEM)));
Kenny Root447106f2011-03-23 11:00:15 -07004552 pw.print(" type="); pw.print(p.type);
Dianne Hackborne639da72012-02-21 15:11:13 -08004553 pw.print(" prot=");
4554 pw.println(PermissionInfo.protectionToString(p.protectionLevel));
Kenny Root447106f2011-03-23 11:00:15 -07004555 if (p.perm != null) {
4556 pw.print(" perm="); pw.println(p.perm);
Svet Ganov3e0be742015-08-07 23:06:00 -07004557 if ((p.perm.info.flags & PermissionInfo.FLAG_INSTALLED) == 0
4558 || (p.perm.info.flags & PermissionInfo.FLAG_HIDDEN) != 0) {
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004559 pw.print(" flags=0x"); pw.println(Integer.toHexString(p.perm.info.flags));
4560 }
4561 }
4562 if (p.packageSetting != null) {
4563 pw.print(" packageSetting="); pw.println(p.packageSetting);
Kenny Root447106f2011-03-23 11:00:15 -07004564 }
Jeff Sharkey1c27576a2012-04-11 19:07:08 -07004565 if (READ_EXTERNAL_STORAGE.equals(p.name)) {
Jeff Sharkey5d32e772012-04-12 15:59:23 -07004566 pw.print(" enforced=");
4567 pw.println(mReadExternalStorageEnforced);
Jeff Sharkey1c27576a2012-04-11 19:07:08 -07004568 }
Kenny Root447106f2011-03-23 11:00:15 -07004569 }
4570 }
Jeff Sharkey1c27576a2012-04-11 19:07:08 -07004571
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004572 void dumpSharedUsersLPr(PrintWriter pw, String packageName, ArraySet<String> permissionNames,
4573 DumpState dumpState, boolean checkin) {
Kenny Root447106f2011-03-23 11:00:15 -07004574 boolean printedSomething = false;
4575 for (SharedUserSetting su : mSharedUsers.values()) {
4576 if (packageName != null && su != dumpState.getSharedUser()) {
4577 continue;
4578 }
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004579 if (permissionNames != null
4580 && !su.getPermissionsState().hasRequestedPermission(permissionNames)) {
4581 continue;
4582 }
Dianne Hackbornd052a942014-11-21 15:23:13 -08004583 if (!checkin) {
4584 if (!printedSomething) {
4585 if (dumpState.onTitlePrinted())
4586 pw.println();
4587 pw.println("Shared users:");
4588 printedSomething = true;
4589 }
4590 pw.print(" SharedUser [");
4591 pw.print(su.name);
4592 pw.print("] (");
4593 pw.print(Integer.toHexString(System.identityHashCode(su)));
4594 pw.println("):");
Svetoslavc6d1c342015-02-26 14:44:43 -08004595
4596 String prefix = " ";
4597 pw.print(prefix); pw.print("userId="); pw.println(su.userId);
4598
4599 PermissionsState permissionsState = su.getPermissionsState();
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004600 dumpInstallPermissionsLPr(pw, prefix, permissionNames, permissionsState);
Svetoslavc6d1c342015-02-26 14:44:43 -08004601
4602 for (int userId : UserManagerService.getInstance().getUserIds()) {
4603 final int[] gids = permissionsState.computeGids(userId);
Svet Ganov8c7f7002015-05-07 10:48:44 -07004604 List<PermissionState> permissions = permissionsState
4605 .getRuntimePermissionStates(userId);
Svetoslavc6d1c342015-02-26 14:44:43 -08004606 if (!ArrayUtils.isEmpty(gids) || !permissions.isEmpty()) {
4607 pw.print(prefix); pw.print("User "); pw.print(userId); pw.println(": ");
4608 dumpGidsLPr(pw, prefix + " ", gids);
Dianne Hackborn9f5b0a22015-08-13 18:25:20 -07004609 dumpRuntimePermissionsLPr(pw, prefix + " ", permissionNames, permissions,
4610 packageName != null);
Svetoslavc6d1c342015-02-26 14:44:43 -08004611 }
Dianne Hackbornd052a942014-11-21 15:23:13 -08004612 }
4613 } else {
4614 pw.print("suid,"); pw.print(su.userId); pw.print(","); pw.println(su.name);
Kenny Root447106f2011-03-23 11:00:15 -07004615 }
4616 }
4617 }
4618
4619 void dumpReadMessagesLPr(PrintWriter pw, DumpState dumpState) {
4620 pw.println("Settings parse messages:");
4621 pw.print(mReadMessages.toString());
4622 }
Jeff Sharkeyc4d05fc2014-12-01 16:24:01 -08004623
Christopher Tatee9fd1fa2015-09-15 16:43:07 -07004624 void dumpRestoredPermissionGrantsLPr(PrintWriter pw, DumpState dumpState) {
4625 if (mRestoredUserGrants.size() > 0) {
4626 pw.println();
4627 pw.println("Restored (pending) permission grants:");
4628 for (int userIndex = 0; userIndex < mRestoredUserGrants.size(); userIndex++) {
4629 ArrayMap<String, ArraySet<RestoredPermissionGrant>> grantsByPackage =
4630 mRestoredUserGrants.valueAt(userIndex);
4631 if (grantsByPackage != null && grantsByPackage.size() > 0) {
4632 final int userId = mRestoredUserGrants.keyAt(userIndex);
4633 pw.print(" User "); pw.println(userId);
4634
4635 for (int pkgIndex = 0; pkgIndex < grantsByPackage.size(); pkgIndex++) {
4636 ArraySet<RestoredPermissionGrant> grants = grantsByPackage.valueAt(pkgIndex);
4637 if (grants != null && grants.size() > 0) {
4638 final String pkgName = grantsByPackage.keyAt(pkgIndex);
4639 pw.print(" "); pw.print(pkgName); pw.println(" :");
4640
4641 for (RestoredPermissionGrant g : grants) {
4642 pw.print(" ");
4643 pw.print(g.permissionName);
4644 if (g.granted) {
4645 pw.print(" GRANTED");
4646 }
4647 if ((g.grantBits&FLAG_PERMISSION_USER_SET) != 0) {
4648 pw.print(" user_set");
4649 }
4650 if ((g.grantBits&FLAG_PERMISSION_USER_FIXED) != 0) {
4651 pw.print(" user_fixed");
4652 }
4653 if ((g.grantBits&FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0) {
4654 pw.print(" revoke_on_upgrade");
4655 }
4656 pw.println();
4657 }
4658 }
4659 }
4660 }
4661 }
4662 pw.println();
4663 }
4664 }
4665
Jeff Sharkeyc4d05fc2014-12-01 16:24:01 -08004666 private static void dumpSplitNames(PrintWriter pw, PackageParser.Package pkg) {
4667 if (pkg == null) {
4668 pw.print("unknown");
4669 } else {
4670 // [base:10, config.mdpi, config.xhdpi:12]
4671 pw.print("[");
4672 pw.print("base");
4673 if (pkg.baseRevisionCode != 0) {
4674 pw.print(":"); pw.print(pkg.baseRevisionCode);
4675 }
4676 if (pkg.splitNames != null) {
4677 for (int i = 0; i < pkg.splitNames.length; i++) {
4678 pw.print(", ");
4679 pw.print(pkg.splitNames[i]);
4680 if (pkg.splitRevisionCodes[i] != 0) {
4681 pw.print(":"); pw.print(pkg.splitRevisionCodes[i]);
4682 }
4683 }
4684 }
4685 pw.print("]");
4686 }
4687 }
Svetoslavc6d1c342015-02-26 14:44:43 -08004688
4689 void dumpGidsLPr(PrintWriter pw, String prefix, int[] gids) {
4690 if (!ArrayUtils.isEmpty(gids)) {
Fabrice Di Meglio62271722015-04-10 17:24:02 -07004691 pw.print(prefix);
4692 pw.print("gids="); pw.println(
Svetoslavc6d1c342015-02-26 14:44:43 -08004693 PackageManagerService.arrayToString(gids));
4694 }
4695 }
4696
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004697 void dumpRuntimePermissionsLPr(PrintWriter pw, String prefix, ArraySet<String> permissionNames,
Dianne Hackborn9f5b0a22015-08-13 18:25:20 -07004698 List<PermissionState> permissionStates, boolean dumpAll) {
4699 if (!permissionStates.isEmpty() || dumpAll) {
Svetoslavc6d1c342015-02-26 14:44:43 -08004700 pw.print(prefix); pw.println("runtime permissions:");
Svet Ganov8c7f7002015-05-07 10:48:44 -07004701 for (PermissionState permissionState : permissionStates) {
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004702 if (permissionNames != null
4703 && !permissionNames.contains(permissionState.getName())) {
4704 continue;
4705 }
Svet Ganov8c7f7002015-05-07 10:48:44 -07004706 pw.print(prefix); pw.print(" "); pw.print(permissionState.getName());
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004707 pw.print(": granted="); pw.print(permissionState.isGranted());
4708 pw.println(permissionFlagsToString(", flags=",
4709 permissionState.getFlags()));
Svetoslavc6d1c342015-02-26 14:44:43 -08004710 }
4711 }
4712 }
4713
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004714 private static String permissionFlagsToString(String prefix, int flags) {
4715 StringBuilder flagsString = null;
Svet Ganov77ab6a82015-07-03 12:03:02 -07004716 while (flags != 0) {
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004717 if (flagsString == null) {
4718 flagsString = new StringBuilder();
4719 flagsString.append(prefix);
4720 flagsString.append("[ ");
4721 }
Svet Ganov77ab6a82015-07-03 12:03:02 -07004722 final int flag = 1 << Integer.numberOfTrailingZeros(flags);
4723 flags &= ~flag;
4724 flagsString.append(PackageManager.permissionFlagToString(flag));
4725 flagsString.append(' ');
4726 }
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004727 if (flagsString != null) {
4728 flagsString.append(']');
4729 return flagsString.toString();
4730 } else {
4731 return "";
4732 }
Svet Ganov77ab6a82015-07-03 12:03:02 -07004733 }
4734
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004735 void dumpInstallPermissionsLPr(PrintWriter pw, String prefix, ArraySet<String> permissionNames,
Svetoslavc6d1c342015-02-26 14:44:43 -08004736 PermissionsState permissionsState) {
Svet Ganov8c7f7002015-05-07 10:48:44 -07004737 List<PermissionState> permissionStates = permissionsState.getInstallPermissionStates();
4738 if (!permissionStates.isEmpty()) {
Svetoslavc6d1c342015-02-26 14:44:43 -08004739 pw.print(prefix); pw.println("install permissions:");
Svet Ganov8c7f7002015-05-07 10:48:44 -07004740 for (PermissionState permissionState : permissionStates) {
Dianne Hackbornca8e6da2015-06-24 15:19:17 -07004741 if (permissionNames != null
4742 && !permissionNames.contains(permissionState.getName())) {
4743 continue;
4744 }
Svet Ganov8c7f7002015-05-07 10:48:44 -07004745 pw.print(prefix); pw.print(" "); pw.print(permissionState.getName());
Dianne Hackborncfbfafe2015-07-21 16:57:51 -07004746 pw.print(": granted="); pw.print(permissionState.isGranted());
4747 pw.println(permissionFlagsToString(", flags=",
Svet Ganov8c7f7002015-05-07 10:48:44 -07004748 permissionState.getFlags()));
Svetoslavc6d1c342015-02-26 14:44:43 -08004749 }
4750 }
4751 }
4752
4753 public void writeRuntimePermissionsForUserLPr(int userId, boolean sync) {
4754 if (sync) {
4755 mRuntimePermissionsPersistence.writePermissionsForUserSyncLPr(userId);
4756 } else {
4757 mRuntimePermissionsPersistence.writePermissionsForUserAsyncLPr(userId);
4758 }
4759 }
4760
4761 private final class RuntimePermissionPersistence {
4762 private static final long WRITE_PERMISSIONS_DELAY_MILLIS = 200;
Svetoslavc6d1c342015-02-26 14:44:43 -08004763 private static final long MAX_WRITE_PERMISSIONS_DELAY_MILLIS = 2000;
4764
4765 private final Handler mHandler = new MyHandler();
4766
4767 private final Object mLock;
4768
4769 @GuardedBy("mLock")
Svet Ganovba3ba812015-06-26 10:54:06 -07004770 private final SparseBooleanArray mWriteScheduled = new SparseBooleanArray();
Svetoslavc6d1c342015-02-26 14:44:43 -08004771
4772 @GuardedBy("mLock")
Svet Ganovba3ba812015-06-26 10:54:06 -07004773 // The mapping keys are user ids.
4774 private final SparseLongArray mLastNotWrittenMutationTimesMillis = new SparseLongArray();
4775
4776 @GuardedBy("mLock")
4777 // The mapping keys are user ids.
4778 private final SparseArray<String> mFingerprints = new SparseArray<>();
4779
4780 @GuardedBy("mLock")
4781 // The mapping keys are user ids.
4782 private final SparseBooleanArray mDefaultPermissionsGranted = new SparseBooleanArray();
Svetoslavc6d1c342015-02-26 14:44:43 -08004783
4784 public RuntimePermissionPersistence(Object lock) {
4785 mLock = lock;
4786 }
4787
Svet Ganovba3ba812015-06-26 10:54:06 -07004788 public boolean areDefaultRuntimPermissionsGrantedLPr(int userId) {
4789 return mDefaultPermissionsGranted.get(userId);
4790 }
4791
4792 public void onDefaultRuntimePermissionsGrantedLPr(int userId) {
4793 mFingerprints.put(userId, Build.FINGERPRINT);
4794 writePermissionsForUserAsyncLPr(userId);
4795 }
4796
Svetoslavc6d1c342015-02-26 14:44:43 -08004797 public void writePermissionsForUserSyncLPr(int userId) {
4798 mHandler.removeMessages(userId);
4799 writePermissionsSync(userId);
4800 }
4801
4802 public void writePermissionsForUserAsyncLPr(int userId) {
4803 final long currentTimeMillis = SystemClock.uptimeMillis();
4804
4805 if (mWriteScheduled.get(userId)) {
4806 mHandler.removeMessages(userId);
4807
4808 // If enough time passed, write without holding off anymore.
4809 final long lastNotWrittenMutationTimeMillis = mLastNotWrittenMutationTimesMillis
4810 .get(userId);
4811 final long timeSinceLastNotWrittenMutationMillis = currentTimeMillis
4812 - lastNotWrittenMutationTimeMillis;
4813 if (timeSinceLastNotWrittenMutationMillis >= MAX_WRITE_PERMISSIONS_DELAY_MILLIS) {
4814 mHandler.obtainMessage(userId).sendToTarget();
4815 return;
4816 }
4817
4818 // Hold off a bit more as settings are frequently changing.
4819 final long maxDelayMillis = Math.max(lastNotWrittenMutationTimeMillis
4820 + MAX_WRITE_PERMISSIONS_DELAY_MILLIS - currentTimeMillis, 0);
4821 final long writeDelayMillis = Math.min(WRITE_PERMISSIONS_DELAY_MILLIS,
4822 maxDelayMillis);
4823
4824 Message message = mHandler.obtainMessage(userId);
4825 mHandler.sendMessageDelayed(message, writeDelayMillis);
4826 } else {
4827 mLastNotWrittenMutationTimesMillis.put(userId, currentTimeMillis);
4828 Message message = mHandler.obtainMessage(userId);
4829 mHandler.sendMessageDelayed(message, WRITE_PERMISSIONS_DELAY_MILLIS);
4830 mWriteScheduled.put(userId, true);
4831 }
4832 }
4833
4834 private void writePermissionsSync(int userId) {
4835 AtomicFile destination = new AtomicFile(getUserRuntimePermissionsFile(userId));
4836
Svet Ganov8c7f7002015-05-07 10:48:44 -07004837 ArrayMap<String, List<PermissionState>> permissionsForPackage = new ArrayMap<>();
4838 ArrayMap<String, List<PermissionState>> permissionsForSharedUser = new ArrayMap<>();
Svetoslavc6d1c342015-02-26 14:44:43 -08004839
4840 synchronized (mLock) {
4841 mWriteScheduled.delete(userId);
4842
4843 final int packageCount = mPackages.size();
4844 for (int i = 0; i < packageCount; i++) {
4845 String packageName = mPackages.keyAt(i);
4846 PackageSetting packageSetting = mPackages.valueAt(i);
4847 if (packageSetting.sharedUser == null) {
4848 PermissionsState permissionsState = packageSetting.getPermissionsState();
Svet Ganov8c7f7002015-05-07 10:48:44 -07004849 List<PermissionState> permissionsStates = permissionsState
4850 .getRuntimePermissionStates(userId);
4851 if (!permissionsStates.isEmpty()) {
4852 permissionsForPackage.put(packageName, permissionsStates);
Svetoslavc6d1c342015-02-26 14:44:43 -08004853 }
4854 }
4855 }
4856
4857 final int sharedUserCount = mSharedUsers.size();
4858 for (int i = 0; i < sharedUserCount; i++) {
4859 String sharedUserName = mSharedUsers.keyAt(i);
4860 SharedUserSetting sharedUser = mSharedUsers.valueAt(i);
4861 PermissionsState permissionsState = sharedUser.getPermissionsState();
Svet Ganov8c7f7002015-05-07 10:48:44 -07004862 List<PermissionState> permissionsStates = permissionsState
4863 .getRuntimePermissionStates(userId);
4864 if (!permissionsStates.isEmpty()) {
4865 permissionsForSharedUser.put(sharedUserName, permissionsStates);
Svetoslavc6d1c342015-02-26 14:44:43 -08004866 }
4867 }
4868 }
4869
4870 FileOutputStream out = null;
4871 try {
4872 out = destination.startWrite();
4873
4874 XmlSerializer serializer = Xml.newSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01004875 serializer.setOutput(out, StandardCharsets.UTF_8.name());
Svetoslavc6d1c342015-02-26 14:44:43 -08004876 serializer.setFeature(
4877 "http://xmlpull.org/v1/doc/features.html#indent-output", true);
4878 serializer.startDocument(null, true);
Christopher Tatee9fd1fa2015-09-15 16:43:07 -07004879
Svetoslavc6d1c342015-02-26 14:44:43 -08004880 serializer.startTag(null, TAG_RUNTIME_PERMISSIONS);
4881
Svet Ganovba3ba812015-06-26 10:54:06 -07004882 String fingerprint = mFingerprints.get(userId);
Svetoslavcdfd2302015-06-25 19:07:31 -07004883 if (fingerprint != null) {
4884 serializer.attribute(null, ATTR_FINGERPRINT, fingerprint);
4885 }
Svet Ganovba3ba812015-06-26 10:54:06 -07004886
Svetoslavc6d1c342015-02-26 14:44:43 -08004887 final int packageCount = permissionsForPackage.size();
4888 for (int i = 0; i < packageCount; i++) {
4889 String packageName = permissionsForPackage.keyAt(i);
Svet Ganov8c7f7002015-05-07 10:48:44 -07004890 List<PermissionState> permissionStates = permissionsForPackage.valueAt(i);
Svetoslavc6d1c342015-02-26 14:44:43 -08004891 serializer.startTag(null, TAG_PACKAGE);
4892 serializer.attribute(null, ATTR_NAME, packageName);
Svet Ganov8c7f7002015-05-07 10:48:44 -07004893 writePermissions(serializer, permissionStates);
Svetoslavc6d1c342015-02-26 14:44:43 -08004894 serializer.endTag(null, TAG_PACKAGE);
4895 }
4896
4897 final int sharedUserCount = permissionsForSharedUser.size();
4898 for (int i = 0; i < sharedUserCount; i++) {
4899 String packageName = permissionsForSharedUser.keyAt(i);
Svet Ganov8c7f7002015-05-07 10:48:44 -07004900 List<PermissionState> permissionStates = permissionsForSharedUser.valueAt(i);
Svetoslavc6d1c342015-02-26 14:44:43 -08004901 serializer.startTag(null, TAG_SHARED_USER);
4902 serializer.attribute(null, ATTR_NAME, packageName);
Svet Ganov8c7f7002015-05-07 10:48:44 -07004903 writePermissions(serializer, permissionStates);
Svetoslavc6d1c342015-02-26 14:44:43 -08004904 serializer.endTag(null, TAG_SHARED_USER);
4905 }
4906
4907 serializer.endTag(null, TAG_RUNTIME_PERMISSIONS);
Christopher Tatee9fd1fa2015-09-15 16:43:07 -07004908
4909 // Now any restored permission grants that are waiting for the apps
4910 // in question to be installed. These are stored as per-package
4911 // TAG_RESTORED_RUNTIME_PERMISSIONS blocks, each containing some
4912 // number of individual permission grant entities.
4913 if (mRestoredUserGrants.get(userId) != null) {
4914 ArrayMap<String, ArraySet<RestoredPermissionGrant>> restoredGrants =
4915 mRestoredUserGrants.get(userId);
4916 if (restoredGrants != null) {
4917 final int pkgCount = restoredGrants.size();
4918 for (int i = 0; i < pkgCount; i++) {
4919 final ArraySet<RestoredPermissionGrant> pkgGrants =
4920 restoredGrants.valueAt(i);
4921 if (pkgGrants != null && pkgGrants.size() > 0) {
4922 final String pkgName = restoredGrants.keyAt(i);
4923 serializer.startTag(null, TAG_RESTORED_RUNTIME_PERMISSIONS);
4924 serializer.attribute(null, ATTR_PACKAGE_NAME, pkgName);
4925
4926 final int N = pkgGrants.size();
4927 for (int z = 0; z < N; z++) {
4928 RestoredPermissionGrant g = pkgGrants.valueAt(z);
4929 serializer.startTag(null, TAG_PERMISSION_ENTRY);
4930 serializer.attribute(null, ATTR_NAME, g.permissionName);
4931
4932 if (g.granted) {
4933 serializer.attribute(null, ATTR_GRANTED, "true");
4934 }
4935
4936 if ((g.grantBits&FLAG_PERMISSION_USER_SET) != 0) {
4937 serializer.attribute(null, ATTR_USER_SET, "true");
4938 }
4939 if ((g.grantBits&FLAG_PERMISSION_USER_FIXED) != 0) {
4940 serializer.attribute(null, ATTR_USER_FIXED, "true");
4941 }
4942 if ((g.grantBits&FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0) {
4943 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
4944 }
4945 serializer.endTag(null, TAG_PERMISSION_ENTRY);
4946 }
4947 serializer.endTag(null, TAG_RESTORED_RUNTIME_PERMISSIONS);
4948 }
4949 }
4950 }
4951 }
4952
Svetoslavc6d1c342015-02-26 14:44:43 -08004953 serializer.endDocument();
4954 destination.finishWrite(out);
Svet Ganovba0821e2015-04-22 13:34:31 -07004955
Svet Ganovba3ba812015-06-26 10:54:06 -07004956 if (Build.FINGERPRINT.equals(fingerprint)) {
4957 mDefaultPermissionsGranted.put(userId, true);
4958 }
4959 // Any error while writing is fatal.
Svet Ganovba0821e2015-04-22 13:34:31 -07004960 } catch (Throwable t) {
Svetoslavc6d1c342015-02-26 14:44:43 -08004961 Slog.wtf(PackageManagerService.TAG,
Svet Ganovba0821e2015-04-22 13:34:31 -07004962 "Failed to write settings, restoring backup", t);
Svetoslavc6d1c342015-02-26 14:44:43 -08004963 destination.failWrite(out);
4964 } finally {
4965 IoUtils.closeQuietly(out);
4966 }
4967 }
4968
4969 private void onUserRemoved(int userId) {
4970 // Make sure we do not
4971 mHandler.removeMessages(userId);
4972
4973 for (SettingBase sb : mPackages.values()) {
Svet Ganov8c7f7002015-05-07 10:48:44 -07004974 revokeRuntimePermissionsAndClearFlags(sb, userId);
Svetoslavc6d1c342015-02-26 14:44:43 -08004975 }
4976
4977 for (SettingBase sb : mSharedUsers.values()) {
Svet Ganov8c7f7002015-05-07 10:48:44 -07004978 revokeRuntimePermissionsAndClearFlags(sb, userId);
Svetoslavc6d1c342015-02-26 14:44:43 -08004979 }
4980 }
4981
Svet Ganov8c7f7002015-05-07 10:48:44 -07004982 private void revokeRuntimePermissionsAndClearFlags(SettingBase sb, int userId) {
Svetoslavc6d1c342015-02-26 14:44:43 -08004983 PermissionsState permissionsState = sb.getPermissionsState();
Svet Ganov8c7f7002015-05-07 10:48:44 -07004984 for (PermissionState permissionState
4985 : permissionsState.getRuntimePermissionStates(userId)) {
4986 BasePermission bp = mPermissions.get(permissionState.getName());
Svetoslavc6d1c342015-02-26 14:44:43 -08004987 if (bp != null) {
4988 permissionsState.revokeRuntimePermission(bp, userId);
Svet Ganov8c7f7002015-05-07 10:48:44 -07004989 permissionsState.updatePermissionFlags(bp, userId,
4990 PackageManager.MASK_PERMISSION_FLAGS, 0);
Svetoslavc6d1c342015-02-26 14:44:43 -08004991 }
4992 }
4993 }
4994
Svet Ganovadc1cf42015-06-15 16:36:24 -07004995 public void deleteUserRuntimePermissionsFile(int userId) {
4996 getUserRuntimePermissionsFile(userId).delete();
4997 }
4998
Svetoslavc6d1c342015-02-26 14:44:43 -08004999 public void readStateForUserSyncLPr(int userId) {
5000 File permissionsFile = getUserRuntimePermissionsFile(userId);
5001 if (!permissionsFile.exists()) {
5002 return;
5003 }
5004
5005 FileInputStream in;
5006 try {
Svetoslav3dcdd372015-05-29 13:00:32 -07005007 in = new AtomicFile(permissionsFile).openRead();
Svetoslavc6d1c342015-02-26 14:44:43 -08005008 } catch (FileNotFoundException fnfe) {
5009 Slog.i(PackageManagerService.TAG, "No permissions state");
5010 return;
5011 }
5012
5013 try {
5014 XmlPullParser parser = Xml.newPullParser();
5015 parser.setInput(in, null);
5016 parseRuntimePermissionsLPr(parser, userId);
Svet Ganovba0821e2015-04-22 13:34:31 -07005017
Svet Ganove723e542015-04-23 11:58:26 -07005018 } catch (XmlPullParserException | IOException e) {
Svetoslavc6d1c342015-02-26 14:44:43 -08005019 throw new IllegalStateException("Failed parsing permissions file: "
Svet Ganove723e542015-04-23 11:58:26 -07005020 + permissionsFile , e);
Svetoslavc6d1c342015-02-26 14:44:43 -08005021 } finally {
5022 IoUtils.closeQuietly(in);
5023 }
5024 }
5025
Christopher Tatee9fd1fa2015-09-15 16:43:07 -07005026 // Backup/restore support
5027
5028 public void rememberRestoredUserGrantLPr(String pkgName, String permission,
5029 boolean isGranted, int restoredFlagSet, int userId) {
5030 // This change will be remembered at write-settings time
5031 ArrayMap<String, ArraySet<RestoredPermissionGrant>> grantsByPackage =
5032 mRestoredUserGrants.get(userId);
5033 if (grantsByPackage == null) {
5034 grantsByPackage = new ArrayMap<String, ArraySet<RestoredPermissionGrant>>();
5035 mRestoredUserGrants.put(userId, grantsByPackage);
5036 }
5037
5038 ArraySet<RestoredPermissionGrant> grants = grantsByPackage.get(pkgName);
5039 if (grants == null) {
5040 grants = new ArraySet<RestoredPermissionGrant>();
5041 grantsByPackage.put(pkgName, grants);
5042 }
5043
5044 RestoredPermissionGrant grant = new RestoredPermissionGrant(permission,
5045 isGranted, restoredFlagSet);
5046 grants.add(grant);
5047 }
5048
5049 // Private internals
5050
Svetoslavc6d1c342015-02-26 14:44:43 -08005051 private void parseRuntimePermissionsLPr(XmlPullParser parser, int userId)
5052 throws IOException, XmlPullParserException {
Svet Ganov12a692a2015-03-28 19:34:15 -07005053 final int outerDepth = parser.getDepth();
5054 int type;
5055 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
5056 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
5057 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
5058 continue;
5059 }
Svetoslavc6d1c342015-02-26 14:44:43 -08005060
Svet Ganov12a692a2015-03-28 19:34:15 -07005061 switch (parser.getName()) {
Svet Ganovba3ba812015-06-26 10:54:06 -07005062 case TAG_RUNTIME_PERMISSIONS: {
5063 String fingerprint = parser.getAttributeValue(null, ATTR_FINGERPRINT);
5064 mFingerprints.put(userId, fingerprint);
5065 final boolean defaultsGranted = Build.FINGERPRINT.equals(fingerprint);
5066 mDefaultPermissionsGranted.put(userId, defaultsGranted);
5067 } break;
5068
Svet Ganov12a692a2015-03-28 19:34:15 -07005069 case TAG_PACKAGE: {
5070 String name = parser.getAttributeValue(null, ATTR_NAME);
5071 PackageSetting ps = mPackages.get(name);
5072 if (ps == null) {
5073 Slog.w(PackageManagerService.TAG, "Unknown package:" + name);
5074 XmlUtils.skipCurrentTag(parser);
5075 continue;
5076 }
5077 parsePermissionsLPr(parser, ps.getPermissionsState(), userId);
5078 } break;
Svetoslavc6d1c342015-02-26 14:44:43 -08005079
Svet Ganov12a692a2015-03-28 19:34:15 -07005080 case TAG_SHARED_USER: {
5081 String name = parser.getAttributeValue(null, ATTR_NAME);
5082 SharedUserSetting sus = mSharedUsers.get(name);
5083 if (sus == null) {
5084 Slog.w(PackageManagerService.TAG, "Unknown shared user:" + name);
5085 XmlUtils.skipCurrentTag(parser);
5086 continue;
5087 }
5088 parsePermissionsLPr(parser, sus.getPermissionsState(), userId);
5089 } break;
Christopher Tatee9fd1fa2015-09-15 16:43:07 -07005090
5091 case TAG_RESTORED_RUNTIME_PERMISSIONS: {
5092 final String pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
5093 parseRestoredRuntimePermissionsLPr(parser, pkgName, userId);
5094 } break;
5095 }
5096 }
5097 }
5098
5099 private void parseRestoredRuntimePermissionsLPr(XmlPullParser parser,
5100 final String pkgName, final int userId) throws IOException, XmlPullParserException {
5101 final int outerDepth = parser.getDepth();
5102 int type;
5103 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
5104 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
5105 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
5106 continue;
5107 }
5108
5109 switch (parser.getName()) {
5110 case TAG_PERMISSION_ENTRY: {
5111 final String permName = parser.getAttributeValue(null, ATTR_NAME);
5112 final boolean isGranted = "true".equals(
5113 parser.getAttributeValue(null, ATTR_GRANTED));
5114
5115 int permBits = 0;
5116 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
5117 permBits |= FLAG_PERMISSION_USER_SET;
5118 }
5119 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
5120 permBits |= FLAG_PERMISSION_USER_FIXED;
5121 }
5122 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
5123 permBits |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
5124 }
5125
5126 if (isGranted || permBits != 0) {
5127 rememberRestoredUserGrantLPr(pkgName, permName, isGranted, permBits, userId);
5128 }
5129 } break;
Svetoslavc6d1c342015-02-26 14:44:43 -08005130 }
5131 }
Svetoslavc6d1c342015-02-26 14:44:43 -08005132 }
5133
Svet Ganov12a692a2015-03-28 19:34:15 -07005134 private void parsePermissionsLPr(XmlPullParser parser, PermissionsState permissionsState,
Svetoslavc6d1c342015-02-26 14:44:43 -08005135 int userId) throws IOException, XmlPullParserException {
Svet Ganov12a692a2015-03-28 19:34:15 -07005136 final int outerDepth = parser.getDepth();
5137 int type;
5138 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
5139 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
5140 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
5141 continue;
Svetoslavc6d1c342015-02-26 14:44:43 -08005142 }
Svetoslavc6d1c342015-02-26 14:44:43 -08005143
Svet Ganov12a692a2015-03-28 19:34:15 -07005144 switch (parser.getName()) {
5145 case TAG_ITEM: {
5146 String name = parser.getAttributeValue(null, ATTR_NAME);
5147 BasePermission bp = mPermissions.get(name);
5148 if (bp == null) {
5149 Slog.w(PackageManagerService.TAG, "Unknown permission:" + name);
5150 XmlUtils.skipCurrentTag(parser);
5151 continue;
5152 }
Svetoslavc6d1c342015-02-26 14:44:43 -08005153
Svet Ganov8c7f7002015-05-07 10:48:44 -07005154 String grantedStr = parser.getAttributeValue(null, ATTR_GRANTED);
5155 final boolean granted = grantedStr == null
5156 || Boolean.parseBoolean(grantedStr);
5157
5158 String flagsStr = parser.getAttributeValue(null, ATTR_FLAGS);
5159 final int flags = (flagsStr != null)
5160 ? Integer.parseInt(flagsStr, 16) : 0;
5161
5162 if (granted) {
Svet Ganovadc1cf42015-06-15 16:36:24 -07005163 permissionsState.grantRuntimePermission(bp, userId);
5164 permissionsState.updatePermissionFlags(bp, userId,
Svet Ganov8c7f7002015-05-07 10:48:44 -07005165 PackageManager.MASK_PERMISSION_FLAGS, flags);
Svet Ganov8c7f7002015-05-07 10:48:44 -07005166 } else {
Svet Ganovadc1cf42015-06-15 16:36:24 -07005167 permissionsState.updatePermissionFlags(bp, userId,
5168 PackageManager.MASK_PERMISSION_FLAGS, flags);
Svet Ganov12a692a2015-03-28 19:34:15 -07005169 }
Svet Ganov8c7f7002015-05-07 10:48:44 -07005170
Svet Ganov12a692a2015-03-28 19:34:15 -07005171 } break;
Svetoslavc6d1c342015-02-26 14:44:43 -08005172 }
Svetoslavc6d1c342015-02-26 14:44:43 -08005173 }
Svetoslavc6d1c342015-02-26 14:44:43 -08005174 }
5175
Svet Ganov8c7f7002015-05-07 10:48:44 -07005176 private void writePermissions(XmlSerializer serializer,
5177 List<PermissionState> permissionStates) throws IOException {
5178 for (PermissionState permissionState : permissionStates) {
Svetoslavc6d1c342015-02-26 14:44:43 -08005179 serializer.startTag(null, TAG_ITEM);
Svet Ganov8c7f7002015-05-07 10:48:44 -07005180 serializer.attribute(null, ATTR_NAME,permissionState.getName());
5181 serializer.attribute(null, ATTR_GRANTED,
5182 String.valueOf(permissionState.isGranted()));
5183 serializer.attribute(null, ATTR_FLAGS,
5184 Integer.toHexString(permissionState.getFlags()));
Svetoslavc6d1c342015-02-26 14:44:43 -08005185 serializer.endTag(null, TAG_ITEM);
5186 }
5187 }
5188
5189 private final class MyHandler extends Handler {
5190 public MyHandler() {
5191 super(BackgroundThread.getHandler().getLooper());
5192 }
5193
5194 @Override
5195 public void handleMessage(Message message) {
5196 final int userId = message.what;
5197 Runnable callback = (Runnable) message.obj;
5198 writePermissionsSync(userId);
5199 if (callback != null) {
5200 callback.run();
5201 }
5202 }
5203 }
5204 }
Andy McFadden2f362292012-01-20 14:43:38 -08005205}