2 * Copyright (C) 2006 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.server.pm;
19 import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20 import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21 import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27 import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28 import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
30 import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
31 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
32 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
33 import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
34 import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
35 import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
36 import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
37 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39 import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
40 import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
41 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
42 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
43 import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
44 import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
45 import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
46 import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
47 import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
48 import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
49 import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
50 import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
51 import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
52 import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
53 import static android.content.pm.PackageManager.INSTALL_INTERNAL;
54 import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
55 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
56 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
57 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
58 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
59 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
60 import static android.content.pm.PackageManager.MATCH_ALL;
61 import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
62 import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
63 import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
64 import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
65 import static android.content.pm.PackageManager.PERMISSION_DENIED;
66 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
67 import static android.content.pm.PackageParser.isApkFile;
68 import static android.os.Process.PACKAGE_INFO_GID;
69 import static android.os.Process.SYSTEM_UID;
70 import static android.system.OsConstants.O_CREAT;
71 import static android.system.OsConstants.O_RDWR;
72 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
73 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
74 import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
75 import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
76 import static com.android.internal.util.ArrayUtils.appendInt;
77 import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
78 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
79 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
80 import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
81 import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
82 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
83 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
84 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
86 import android.Manifest;
87 import android.app.ActivityManager;
88 import android.app.ActivityManagerNative;
89 import android.app.AppGlobals;
90 import android.app.IActivityManager;
91 import android.app.admin.IDevicePolicyManager;
92 import android.app.backup.IBackupManager;
93 import android.app.usage.UsageStats;
94 import android.app.usage.UsageStatsManager;
95 import android.content.BroadcastReceiver;
96 import android.content.ComponentName;
97 import android.content.Context;
98 import android.content.IIntentReceiver;
99 import android.content.Intent;
100 import android.content.IntentFilter;
101 import android.content.IntentSender;
102 import android.content.IntentSender.SendIntentException;
103 import android.content.ServiceConnection;
104 import android.content.pm.ActivityInfo;
105 import android.content.pm.ApplicationInfo;
106 import android.content.pm.FeatureInfo;
107 import android.content.pm.IOnPermissionsChangeListener;
108 import android.content.pm.IPackageDataObserver;
109 import android.content.pm.IPackageDeleteObserver;
110 import android.content.pm.IPackageDeleteObserver2;
111 import android.content.pm.IPackageInstallObserver2;
112 import android.content.pm.IPackageInstaller;
113 import android.content.pm.IPackageManager;
114 import android.content.pm.IPackageMoveObserver;
115 import android.content.pm.IPackageStatsObserver;
116 import android.content.pm.InstrumentationInfo;
117 import android.content.pm.IntentFilterVerificationInfo;
118 import android.content.pm.KeySet;
119 import android.content.pm.ManifestDigest;
120 import android.content.pm.PackageCleanItem;
121 import android.content.pm.PackageInfo;
122 import android.content.pm.PackageInfoLite;
123 import android.content.pm.PackageInstaller;
124 import android.content.pm.PackageManager;
125 import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
126 import android.content.pm.PackageManagerInternal;
127 import android.content.pm.PackageParser;
128 import android.content.pm.PackageParser.ActivityIntentInfo;
129 import android.content.pm.PackageParser.PackageLite;
130 import android.content.pm.PackageParser.PackageParserException;
131 import android.content.pm.PackageStats;
132 import android.content.pm.PackageUserState;
133 import android.content.pm.ParceledListSlice;
134 import android.content.pm.PermissionGroupInfo;
135 import android.content.pm.PermissionInfo;
136 import android.content.pm.ProviderInfo;
137 import android.content.pm.ResolveInfo;
138 import android.content.pm.ServiceInfo;
139 import android.content.pm.Signature;
140 import android.content.pm.UserInfo;
141 import android.content.pm.VerificationParams;
142 import android.content.pm.VerifierDeviceIdentity;
143 import android.content.pm.VerifierInfo;
144 import android.content.res.Resources;
145 import android.hardware.display.DisplayManager;
146 import android.net.Uri;
147 import android.os.Debug;
148 import android.os.Binder;
149 import android.os.Build;
150 import android.os.Bundle;
151 import android.os.Environment;
152 import android.os.Environment.UserEnvironment;
153 import android.os.FileUtils;
154 import android.os.Handler;
155 import android.os.IBinder;
156 import android.os.Looper;
157 import android.os.Message;
158 import android.os.Parcel;
159 import android.os.ParcelFileDescriptor;
160 import android.os.Process;
161 import android.os.RemoteCallbackList;
162 import android.os.RemoteException;
163 import android.os.SELinux;
164 import android.os.ServiceManager;
165 import android.os.SystemClock;
166 import android.os.SystemProperties;
167 import android.os.UserHandle;
168 import android.os.UserManager;
169 import android.os.storage.IMountService;
170 import android.os.storage.MountServiceInternal;
171 import android.os.storage.StorageEventListener;
172 import android.os.storage.StorageManager;
173 import android.os.storage.VolumeInfo;
174 import android.os.storage.VolumeRecord;
175 import android.security.KeyStore;
176 import android.security.SystemKeyStore;
177 import android.system.ErrnoException;
178 import android.system.Os;
179 import android.system.StructStat;
180 import android.text.TextUtils;
181 import android.text.format.DateUtils;
182 import android.util.ArrayMap;
183 import android.util.ArraySet;
184 import android.util.AtomicFile;
185 import android.util.DisplayMetrics;
186 import android.util.EventLog;
187 import android.util.ExceptionUtils;
188 import android.util.Log;
189 import android.util.LogPrinter;
190 import android.util.MathUtils;
191 import android.util.PrintStreamPrinter;
192 import android.util.Slog;
193 import android.util.SparseArray;
194 import android.util.SparseBooleanArray;
195 import android.util.SparseIntArray;
196 import android.util.Xml;
197 import android.view.Display;
199 import dalvik.system.DexFile;
200 import dalvik.system.VMRuntime;
202 import libcore.io.IoUtils;
203 import libcore.util.EmptyArray;
205 import com.android.internal.R;
206 import com.android.internal.annotations.GuardedBy;
207 import com.android.internal.app.IMediaContainerService;
208 import com.android.internal.app.ResolverActivity;
209 import com.android.internal.content.NativeLibraryHelper;
210 import com.android.internal.content.PackageHelper;
211 import com.android.internal.os.IParcelFileDescriptorFactory;
212 import com.android.internal.os.SomeArgs;
213 import com.android.internal.os.Zygote;
214 import com.android.internal.util.ArrayUtils;
215 import com.android.internal.util.FastPrintWriter;
216 import com.android.internal.util.FastXmlSerializer;
217 import com.android.internal.util.IndentingPrintWriter;
218 import com.android.internal.util.Preconditions;
219 import com.android.server.EventLogTags;
220 import com.android.server.FgThread;
221 import com.android.server.IntentResolver;
222 import com.android.server.LocalServices;
223 import com.android.server.ServiceThread;
224 import com.android.server.SystemConfig;
225 import com.android.server.Watchdog;
226 import com.android.server.pm.PermissionsState.PermissionState;
227 import com.android.server.pm.Settings.DatabaseVersion;
228 import com.android.server.pm.Settings.VersionInfo;
229 import com.android.server.storage.DeviceStorageMonitorInternal;
231 import org.xmlpull.v1.XmlPullParser;
232 import org.xmlpull.v1.XmlPullParserException;
233 import org.xmlpull.v1.XmlSerializer;
235 import java.io.BufferedInputStream;
236 import java.io.BufferedOutputStream;
237 import java.io.BufferedReader;
238 import java.io.ByteArrayInputStream;
239 import java.io.ByteArrayOutputStream;
241 import java.io.FileDescriptor;
242 import java.io.FileNotFoundException;
243 import java.io.FileOutputStream;
244 import java.io.FileReader;
245 import java.io.FilenameFilter;
246 import java.io.IOException;
247 import java.io.InputStream;
248 import java.io.PrintWriter;
249 import java.nio.charset.StandardCharsets;
250 import java.security.NoSuchAlgorithmException;
251 import java.security.PublicKey;
252 import java.security.cert.CertificateEncodingException;
253 import java.security.cert.CertificateException;
254 import java.text.SimpleDateFormat;
255 import java.util.ArrayList;
256 import java.util.Arrays;
257 import java.util.Collection;
258 import java.util.Collections;
259 import java.util.Comparator;
260 import java.util.Date;
261 import java.util.Iterator;
262 import java.util.List;
263 import java.util.Map;
264 import java.util.Objects;
265 import java.util.Set;
266 import java.util.concurrent.CountDownLatch;
267 import java.util.concurrent.TimeUnit;
268 import java.util.concurrent.atomic.AtomicBoolean;
269 import java.util.concurrent.atomic.AtomicInteger;
270 import java.util.concurrent.atomic.AtomicLong;
273 * Keep track of all those .apks everywhere.
275 * This is very central to the platform's security; please run the unit
276 * tests whenever making modifications here:
278 mmm frameworks/base/tests/AndroidTests
279 adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
280 adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
284 public class PackageManagerService extends IPackageManager.Stub {
285 static final String TAG = "PackageManager";
286 static final boolean DEBUG_SETTINGS = false;
287 static final boolean DEBUG_PREFERRED = false;
288 static final boolean DEBUG_UPGRADE = false;
289 static final boolean DEBUG_DOMAIN_VERIFICATION = false;
290 private static final boolean DEBUG_BACKUP = false;
291 private static final boolean DEBUG_INSTALL = false;
292 private static final boolean DEBUG_REMOVE = false;
293 private static final boolean DEBUG_BROADCASTS = false;
294 private static final boolean DEBUG_SHOW_INFO = false;
295 private static final boolean DEBUG_PACKAGE_INFO = false;
296 private static final boolean DEBUG_INTENT_MATCHING = false;
297 private static final boolean DEBUG_PACKAGE_SCANNING = false;
298 private static final boolean DEBUG_VERIFY = false;
299 private static final boolean DEBUG_DEXOPT = false;
300 private static final boolean DEBUG_FILTERS = false;
301 private static final boolean DEBUG_ABI_SELECTION = false;
303 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
305 private static final int RADIO_UID = Process.PHONE_UID;
306 private static final int LOG_UID = Process.LOG_UID;
307 private static final int NFC_UID = Process.NFC_UID;
308 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
309 private static final int SHELL_UID = Process.SHELL_UID;
311 // Cap the size of permission trees that 3rd party apps can define
312 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text
314 // Suffix used during package installation when copying/moving
315 // package apks to install directory.
316 private static final String INSTALL_PACKAGE_SUFFIX = "-";
318 static final int SCAN_NO_DEX = 1<<1;
319 static final int SCAN_FORCE_DEX = 1<<2;
320 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
321 static final int SCAN_NEW_INSTALL = 1<<4;
322 static final int SCAN_NO_PATHS = 1<<5;
323 static final int SCAN_UPDATE_TIME = 1<<6;
324 static final int SCAN_DEFER_DEX = 1<<7;
325 static final int SCAN_BOOTING = 1<<8;
326 static final int SCAN_TRUSTED_OVERLAY = 1<<9;
327 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
328 static final int SCAN_REPLACING = 1<<11;
329 static final int SCAN_REQUIRE_KNOWN = 1<<12;
330 static final int SCAN_MOVE = 1<<13;
331 static final int SCAN_INITIAL = 1<<14;
333 static final int REMOVE_CHATTY = 1<<16;
335 private static final int[] EMPTY_INT_ARRAY = new int[0];
338 * Timeout (in milliseconds) after which the watchdog should declare that
339 * our handler thread is wedged. The usual default for such things is one
340 * minute but we sometimes do very lengthy I/O operations on this thread,
341 * such as installing multi-gigabyte applications, so ours needs to be longer.
343 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes
346 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
347 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
348 * settings entry if available, otherwise we use the hardcoded default. If it's been
349 * more than this long since the last fstrim, we force one during the boot sequence.
351 * This backstops other fstrim scheduling: if the device is alive at midnight+idle,
352 * one gets run at the next available charging+idle time. This final mandatory
353 * no-fstrim check kicks in only of the other scheduling criteria is never met.
355 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
358 * Whether verification is enabled by default.
360 private static final boolean DEFAULT_VERIFY_ENABLE = true;
363 * The default maximum time to wait for the verification agent to return in
366 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
369 * The default response for package verification timeout.
371 * This can be either PackageManager.VERIFICATION_ALLOW or
372 * PackageManager.VERIFICATION_REJECT.
374 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
376 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
378 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
379 DEFAULT_CONTAINER_PACKAGE,
380 "com.android.defcontainer.DefaultContainerService");
382 private static final String KILL_APP_REASON_GIDS_CHANGED =
383 "permission grant or revoke changed gids";
385 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
386 "permissions revoked";
388 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
390 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
392 /** Permission grant: not grant the permission. */
393 private static final int GRANT_DENIED = 1;
395 /** Permission grant: grant the permission as an install permission. */
396 private static final int GRANT_INSTALL = 2;
398 /** Permission grant: grant the permission as an install permission for a legacy app. */
399 private static final int GRANT_INSTALL_LEGACY = 3;
401 /** Permission grant: grant the permission as a runtime one. */
402 private static final int GRANT_RUNTIME = 4;
404 /** Permission grant: grant as runtime a permission that was granted as an install time one. */
405 private static final int GRANT_UPGRADE = 5;
407 /** Canonical intent used to identify what counts as a "web browser" app */
408 private static final Intent sBrowserIntent;
410 sBrowserIntent = new Intent();
411 sBrowserIntent.setAction(Intent.ACTION_VIEW);
412 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
413 sBrowserIntent.setData(Uri.parse("http:"));
416 final ServiceThread mHandlerThread;
418 final PackageHandler mHandler;
421 * Messages for {@link #mHandler} that need to wait for system ready before
424 private ArrayList<Message> mPostSystemReadyMessages;
426 final int mSdkVersion = Build.VERSION.SDK_INT;
428 final Context mContext;
429 final boolean mFactoryTest;
430 final boolean mOnlyCore;
431 final boolean mLazyDexOpt;
432 final long mDexOptLRUThresholdInMills;
433 final DisplayMetrics mMetrics;
434 final int mDefParseFlags;
435 final String[] mSeparateProcesses;
436 final boolean mIsUpgrade;
438 // This is where all application persistent data goes.
439 final File mAppDataDir;
441 // This is where all application persistent data goes for secondary users.
442 final File mUserAppDataDir;
444 /** The location for ASEC container files on internal storage. */
445 final String mAsecInternalPath;
447 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
448 // LOCK HELD. Can be called with mInstallLock held.
449 @GuardedBy("mInstallLock")
450 final Installer mInstaller;
452 /** Directory where installed third-party apps stored */
453 final File mAppInstallDir;
456 * Directory to which applications installed internally have their
457 * 32 bit native libraries copied.
459 private File mAppLib32InstallDir;
461 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
463 final File mDrmAppPrivateInstallDir;
465 // ----------------------------------------------------------------
467 // Lock for state used when installing and doing other long running
468 // operations. Methods that must be called with this lock held have
470 final Object mInstallLock = new Object();
472 // ----------------------------------------------------------------
474 // Keys are String (package name), values are Package. This also serves
475 // as the lock for the global state. Methods that must be called with
476 // this lock held have the prefix "LP".
477 @GuardedBy("mPackages")
478 final ArrayMap<String, PackageParser.Package> mPackages =
479 new ArrayMap<String, PackageParser.Package>();
481 // Tracks available target package names -> overlay package paths.
482 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
483 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
486 * Tracks new system packages [received in an OTA] that we expect to
487 * find updated user-installed versions. Keys are package name, values
488 * are package location.
490 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
493 * Tracks existing system packages prior to receiving an OTA. Keys are package name.
495 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
497 * Whether or not system app permissions should be promoted from install to runtime.
499 boolean mPromoteSystemApps;
501 final Settings mSettings;
502 boolean mRestoredSettings;
504 // System configuration read by SystemConfig.
505 final int[] mGlobalGids;
506 final SparseArray<ArraySet<String>> mSystemPermissions;
507 final ArrayMap<String, FeatureInfo> mAvailableFeatures;
509 // If mac_permissions.xml was found for seinfo labeling.
510 boolean mFoundPolicyFile;
512 // If a recursive restorecon of /data/data/<pkg> is needed.
513 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
515 public static final class SharedLibraryEntry {
516 public final String path;
517 public final String apk;
519 SharedLibraryEntry(String _path, String _apk) {
525 // Currently known shared libraries.
526 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
527 new ArrayMap<String, SharedLibraryEntry>();
529 // All available activities, for your resolving pleasure.
530 final ActivityIntentResolver mActivities =
531 new ActivityIntentResolver();
533 // All available receivers, for your resolving pleasure.
534 final ActivityIntentResolver mReceivers =
535 new ActivityIntentResolver();
537 // All available services, for your resolving pleasure.
538 final ServiceIntentResolver mServices = new ServiceIntentResolver();
540 // All available providers, for your resolving pleasure.
541 final ProviderIntentResolver mProviders = new ProviderIntentResolver();
543 // Mapping from provider base names (first directory in content URI codePath)
544 // to the provider information.
545 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
546 new ArrayMap<String, PackageParser.Provider>();
548 // Mapping from instrumentation class names to info about them.
549 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
550 new ArrayMap<ComponentName, PackageParser.Instrumentation>();
552 // Mapping from permission names to info about them.
553 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
554 new ArrayMap<String, PackageParser.PermissionGroup>();
556 // Packages whose data we have transfered into another package, thus
557 // should no longer exist.
558 final ArraySet<String> mTransferedPackages = new ArraySet<String>();
560 // Broadcast actions that are only available to the system.
561 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
563 /** List of packages waiting for verification. */
564 final SparseArray<PackageVerificationState> mPendingVerification
565 = new SparseArray<PackageVerificationState>();
567 /** Set of packages associated with each app op permission. */
568 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
570 final PackageInstallerService mInstallerService;
572 private final PackageDexOptimizer mPackageDexOptimizer;
574 private AtomicInteger mNextMoveId = new AtomicInteger();
575 private final MoveCallbacks mMoveCallbacks;
577 private final OnPermissionChangeListeners mOnPermissionChangeListeners;
579 // Cache of users who need badging.
580 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
582 /** Token for keys in mPendingVerification. */
583 private int mPendingVerificationToken = 0;
585 volatile boolean mSystemReady;
586 volatile boolean mSafeMode;
587 volatile boolean mHasSystemUidErrors;
589 ApplicationInfo mAndroidApplication;
590 final ActivityInfo mResolveActivity = new ActivityInfo();
591 final ResolveInfo mResolveInfo = new ResolveInfo();
592 ComponentName mResolveComponentName;
593 PackageParser.Package mPlatformPackage;
594 ComponentName mCustomResolverComponentName;
596 boolean mResolverReplaced = false;
598 private final ComponentName mIntentFilterVerifierComponent;
599 private int mIntentFilterVerificationToken = 0;
601 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
602 = new SparseArray<IntentFilterVerificationState>();
604 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
605 new DefaultPermissionGrantPolicy(this);
607 private static class IFVerificationParams {
608 PackageParser.Package pkg;
613 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
614 int _userId, int _verifierUid) {
616 replacing = _replacing;
618 replacing = _replacing;
619 verifierUid = _verifierUid;
623 private interface IntentFilterVerifier<T extends IntentFilter> {
624 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
625 T filter, String packageName);
626 void startVerifications(int userId);
627 void receiveVerificationResponse(int verificationId);
630 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
631 private Context mContext;
632 private ComponentName mIntentFilterVerifierComponent;
633 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
635 public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
637 mIntentFilterVerifierComponent = verifierComponent;
640 private String getDefaultScheme() {
641 return IntentFilter.SCHEME_HTTPS;
645 public void startVerifications(int userId) {
646 // Launch verifications requests
647 int count = mCurrentIntentFilterVerifications.size();
648 for (int n=0; n<count; n++) {
649 int verificationId = mCurrentIntentFilterVerifications.get(n);
650 final IntentFilterVerificationState ivs =
651 mIntentFilterVerificationStates.get(verificationId);
653 String packageName = ivs.getPackageName();
655 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
656 final int filterCount = filters.size();
657 ArraySet<String> domainsSet = new ArraySet<>();
658 for (int m=0; m<filterCount; m++) {
659 PackageParser.ActivityIntentInfo filter = filters.get(m);
660 domainsSet.addAll(filter.getHostsList());
662 ArrayList<String> domainsList = new ArrayList<>(domainsSet);
663 synchronized (mPackages) {
664 if (mSettings.createIntentFilterVerificationIfNeededLPw(
665 packageName, domainsList) != null) {
666 scheduleWriteSettingsLocked();
669 sendVerificationRequest(userId, verificationId, ivs);
671 mCurrentIntentFilterVerifications.clear();
674 private void sendVerificationRequest(int userId, int verificationId,
675 IntentFilterVerificationState ivs) {
677 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
678 verificationIntent.putExtra(
679 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
681 verificationIntent.putExtra(
682 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
684 verificationIntent.putExtra(
685 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
686 ivs.getHostsString());
687 verificationIntent.putExtra(
688 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
689 ivs.getPackageName());
690 verificationIntent.setComponent(mIntentFilterVerifierComponent);
691 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
693 UserHandle user = new UserHandle(userId);
694 mContext.sendBroadcastAsUser(verificationIntent, user);
695 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
696 "Sending IntentFilter verification broadcast");
699 public void receiveVerificationResponse(int verificationId) {
700 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
702 final boolean verified = ivs.isVerified();
704 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
705 final int count = filters.size();
706 if (DEBUG_DOMAIN_VERIFICATION) {
707 Slog.i(TAG, "Received verification response " + verificationId
708 + " for " + count + " filters, verified=" + verified);
710 for (int n=0; n<count; n++) {
711 PackageParser.ActivityIntentInfo filter = filters.get(n);
712 filter.setVerified(verified);
714 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
715 + " verified with result:" + verified + " and hosts:"
716 + ivs.getHostsString());
719 mIntentFilterVerificationStates.remove(verificationId);
721 final String packageName = ivs.getPackageName();
722 IntentFilterVerificationInfo ivi = null;
724 synchronized (mPackages) {
725 ivi = mSettings.getIntentFilterVerificationLPr(packageName);
728 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
729 + verificationId + " packageName:" + packageName);
732 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
733 "Updating IntentFilterVerificationInfo for package " + packageName
734 +" verificationId:" + verificationId);
736 synchronized (mPackages) {
738 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
740 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
742 scheduleWriteSettingsLocked();
744 final int userId = ivs.getUserId();
745 if (userId != UserHandle.USER_ALL) {
746 final int userStatus =
747 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
749 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
750 boolean needUpdate = false;
752 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
753 // already been set by the User thru the Disambiguation dialog
754 switch (userStatus) {
755 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
757 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
759 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
764 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
766 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
776 mSettings.updateIntentFilterVerificationStatusLPw(
777 packageName, updatedStatus, userId);
778 scheduleWritePackageRestrictionsLocked(userId);
785 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
786 ActivityIntentInfo filter, String packageName) {
787 if (!hasValidDomains(filter)) {
790 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
792 ivs = createDomainVerificationState(verifierUid, userId, verificationId,
795 if (DEBUG_DOMAIN_VERIFICATION) {
796 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
798 ivs.addFilter(filter);
802 private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
803 int userId, int verificationId, String packageName) {
804 IntentFilterVerificationState ivs = new IntentFilterVerificationState(
805 verifierUid, userId, packageName);
806 ivs.setPendingState();
807 synchronized (mPackages) {
808 mIntentFilterVerificationStates.append(verificationId, ivs);
809 mCurrentIntentFilterVerifications.add(verificationId);
815 private static boolean hasValidDomains(ActivityIntentInfo filter) {
816 return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
817 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
818 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
821 private IntentFilterVerifier mIntentFilterVerifier;
823 // Set of pending broadcasts for aggregating enable/disable of components.
824 static class PendingPackageBroadcasts {
825 // for each user id, a map of <package name -> components within that package>
826 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
828 public PendingPackageBroadcasts() {
829 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
832 public ArrayList<String> get(int userId, String packageName) {
833 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
834 return packages.get(packageName);
837 public void put(int userId, String packageName, ArrayList<String> components) {
838 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
839 packages.put(packageName, components);
842 public void remove(int userId, String packageName) {
843 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
844 if (packages != null) {
845 packages.remove(packageName);
849 public void remove(int userId) {
850 mUidMap.remove(userId);
853 public int userIdCount() {
854 return mUidMap.size();
857 public int userIdAt(int n) {
858 return mUidMap.keyAt(n);
861 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
862 return mUidMap.get(userId);
866 // total number of pending broadcast entries across all userIds
868 for (int i = 0; i< mUidMap.size(); i++) {
869 num += mUidMap.valueAt(i).size();
874 public void clear() {
878 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
879 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
881 map = new ArrayMap<String, ArrayList<String>>();
882 mUidMap.put(userId, map);
887 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
889 // Service Connection to remote media container service to copy
890 // package uri's from external media onto secure containers
891 // or internal storage.
892 private IMediaContainerService mContainerService = null;
894 static final int SEND_PENDING_BROADCAST = 1;
895 static final int MCS_BOUND = 3;
896 static final int END_COPY = 4;
897 static final int INIT_COPY = 5;
898 static final int MCS_UNBIND = 6;
899 static final int START_CLEANING_PACKAGE = 7;
900 static final int FIND_INSTALL_LOC = 8;
901 static final int POST_INSTALL = 9;
902 static final int MCS_RECONNECT = 10;
903 static final int MCS_GIVE_UP = 11;
904 static final int UPDATED_MEDIA_STATUS = 12;
905 static final int WRITE_SETTINGS = 13;
906 static final int WRITE_PACKAGE_RESTRICTIONS = 14;
907 static final int PACKAGE_VERIFIED = 15;
908 static final int CHECK_PENDING_VERIFICATION = 16;
909 static final int START_INTENT_FILTER_VERIFICATIONS = 17;
910 static final int INTENT_FILTER_VERIFIED = 18;
912 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
914 // Delay time in millisecs
915 static final int BROADCAST_DELAY = 10 * 1000;
917 static UserManagerService sUserManager;
919 // Stores a list of users whose package restrictions file needs to be updated
920 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
922 final private DefaultContainerConnection mDefContainerConn =
923 new DefaultContainerConnection();
924 class DefaultContainerConnection implements ServiceConnection {
925 public void onServiceConnected(ComponentName name, IBinder service) {
926 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
927 IMediaContainerService imcs =
928 IMediaContainerService.Stub.asInterface(service);
929 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
932 public void onServiceDisconnected(ComponentName name) {
933 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
937 // Recordkeeping of restore-after-install operations that are currently in flight
938 // between the Package Manager and the Backup Manager
939 class PostInstallData {
940 public InstallArgs args;
941 public PackageInstalledInfo res;
943 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
949 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
950 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
952 // XML tags for backup/restore of various bits of state
953 private static final String TAG_PREFERRED_BACKUP = "pa";
954 private static final String TAG_DEFAULT_APPS = "da";
955 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
957 final String mRequiredVerifierPackage;
958 final String mRequiredInstallerPackage;
960 private final PackageUsage mPackageUsage = new PackageUsage();
962 private class PackageUsage {
963 private static final int WRITE_INTERVAL
964 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
966 private final Object mFileLock = new Object();
967 private final AtomicLong mLastWritten = new AtomicLong(0);
968 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
970 private boolean mIsHistoricalPackageUsageAvailable = true;
972 boolean isHistoricalPackageUsageAvailable() {
973 return mIsHistoricalPackageUsageAvailable;
976 void write(boolean force) {
981 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
985 if (mBackgroundWriteRunning.compareAndSet(false, true)) {
986 new Thread("PackageUsage_DiskWriter") {
992 mBackgroundWriteRunning.set(false);
999 private void writeInternal() {
1000 synchronized (mPackages) {
1001 synchronized (mFileLock) {
1002 AtomicFile file = getFile();
1003 FileOutputStream f = null;
1005 f = file.startWrite();
1006 BufferedOutputStream out = new BufferedOutputStream(f);
1007 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1008 StringBuilder sb = new StringBuilder();
1009 for (PackageParser.Package pkg : mPackages.values()) {
1010 if (pkg.mLastPackageUsageTimeInMills == 0) {
1014 sb.append(pkg.packageName);
1016 sb.append((long)pkg.mLastPackageUsageTimeInMills);
1018 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1021 file.finishWrite(f);
1022 } catch (IOException e) {
1026 Log.e(TAG, "Failed to write package usage times", e);
1030 mLastWritten.set(SystemClock.elapsedRealtime());
1034 synchronized (mFileLock) {
1035 AtomicFile file = getFile();
1036 BufferedInputStream in = null;
1038 in = new BufferedInputStream(file.openRead());
1039 StringBuffer sb = new StringBuffer();
1041 String packageName = readToken(in, sb, ' ');
1042 if (packageName == null) {
1045 String timeInMillisString = readToken(in, sb, '\n');
1046 if (timeInMillisString == null) {
1047 throw new IOException("Failed to find last usage time for package "
1050 PackageParser.Package pkg = mPackages.get(packageName);
1056 timeInMillis = Long.parseLong(timeInMillisString.toString());
1057 } catch (NumberFormatException e) {
1058 throw new IOException("Failed to parse " + timeInMillisString
1059 + " as a long.", e);
1061 pkg.mLastPackageUsageTimeInMills = timeInMillis;
1063 } catch (FileNotFoundException expected) {
1064 mIsHistoricalPackageUsageAvailable = false;
1065 } catch (IOException e) {
1066 Log.w(TAG, "Failed to read package usage times", e);
1068 IoUtils.closeQuietly(in);
1071 mLastWritten.set(SystemClock.elapsedRealtime());
1074 private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1075 throws IOException {
1080 if (sb.length() == 0) {
1083 throw new IOException("Unexpected EOF");
1085 if (ch == endOfToken) {
1086 return sb.toString();
1088 sb.append((char)ch);
1092 private AtomicFile getFile() {
1093 File dataDir = Environment.getDataDirectory();
1094 File systemDir = new File(dataDir, "system");
1095 File fname = new File(systemDir, "package-usage.list");
1096 return new AtomicFile(fname);
1100 class PackageHandler extends Handler {
1101 private boolean mBound = false;
1102 final ArrayList<HandlerParams> mPendingInstalls =
1103 new ArrayList<HandlerParams>();
1105 private boolean connectToService() {
1106 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1107 " DefaultContainerService");
1108 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1109 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1110 if (mContext.bindServiceAsUser(service, mDefContainerConn,
1111 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1112 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1116 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1120 private void disconnectService() {
1121 mContainerService = null;
1123 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1124 mContext.unbindService(mDefContainerConn);
1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1128 PackageHandler(Looper looper) {
1132 public void handleMessage(Message msg) {
1134 doHandleMessage(msg);
1136 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1140 void doHandleMessage(Message msg) {
1143 HandlerParams params = (HandlerParams) msg.obj;
1144 int idx = mPendingInstalls.size();
1145 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1146 // If a bind was already initiated we dont really
1147 // need to do anything. The pending install
1148 // will be processed later on.
1150 // If this is the only one pending we might
1151 // have to bind to the service again.
1152 if (!connectToService()) {
1153 Slog.e(TAG, "Failed to bind to media container service");
1154 params.serviceError();
1157 // Once we bind to the service, the first
1158 // pending request will be processed.
1159 mPendingInstalls.add(idx, params);
1162 mPendingInstalls.add(idx, params);
1163 // Already bound to the service. Just make
1164 // sure we trigger off processing the first request.
1166 mHandler.sendEmptyMessage(MCS_BOUND);
1172 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1173 if (msg.obj != null) {
1174 mContainerService = (IMediaContainerService) msg.obj;
1176 if (mContainerService == null) {
1178 // Something seriously wrong since we are not bound and we are not
1179 // waiting for connection. Bail out.
1180 Slog.e(TAG, "Cannot bind to media container service");
1181 for (HandlerParams params : mPendingInstalls) {
1182 // Indicate service bind error
1183 params.serviceError();
1185 mPendingInstalls.clear();
1187 Slog.w(TAG, "Waiting to connect to media container service");
1189 } else if (mPendingInstalls.size() > 0) {
1190 HandlerParams params = mPendingInstalls.get(0);
1191 if (params != null) {
1192 if (params.startCopy()) {
1193 // We are done... look for more work or to
1195 if (DEBUG_SD_INSTALL) Log.i(TAG,
1196 "Checking for more work or unbind...");
1197 // Delete pending install
1198 if (mPendingInstalls.size() > 0) {
1199 mPendingInstalls.remove(0);
1201 if (mPendingInstalls.size() == 0) {
1203 if (DEBUG_SD_INSTALL) Log.i(TAG,
1204 "Posting delayed MCS_UNBIND");
1205 removeMessages(MCS_UNBIND);
1206 Message ubmsg = obtainMessage(MCS_UNBIND);
1207 // Unbind after a little delay, to avoid
1208 // continual thrashing.
1209 sendMessageDelayed(ubmsg, 10000);
1212 // There are more pending requests in queue.
1213 // Just post MCS_BOUND message to trigger processing
1214 // of next pending install.
1215 if (DEBUG_SD_INSTALL) Log.i(TAG,
1216 "Posting MCS_BOUND for next work");
1217 mHandler.sendEmptyMessage(MCS_BOUND);
1222 // Should never happen ideally.
1223 Slog.w(TAG, "Empty queue");
1227 case MCS_RECONNECT: {
1228 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1229 if (mPendingInstalls.size() > 0) {
1231 disconnectService();
1233 if (!connectToService()) {
1234 Slog.e(TAG, "Failed to bind to media container service");
1235 for (HandlerParams params : mPendingInstalls) {
1236 // Indicate service bind error
1237 params.serviceError();
1239 mPendingInstalls.clear();
1245 // If there is no actual work left, then time to unbind.
1246 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1248 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1250 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1252 disconnectService();
1254 } else if (mPendingInstalls.size() > 0) {
1255 // There are more pending requests in queue.
1256 // Just post MCS_BOUND message to trigger processing
1257 // of next pending install.
1258 mHandler.sendEmptyMessage(MCS_BOUND);
1264 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1265 mPendingInstalls.remove(0);
1268 case SEND_PENDING_BROADCAST: {
1270 ArrayList<String> components[];
1273 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1274 synchronized (mPackages) {
1275 if (mPendingBroadcasts == null) {
1278 size = mPendingBroadcasts.size();
1280 // Nothing to be done. Just return
1283 packages = new String[size];
1284 components = new ArrayList[size];
1285 uids = new int[size];
1286 int i = 0; // filling out the above arrays
1288 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1289 int packageUserId = mPendingBroadcasts.userIdAt(n);
1290 Iterator<Map.Entry<String, ArrayList<String>>> it
1291 = mPendingBroadcasts.packagesForUserId(packageUserId)
1292 .entrySet().iterator();
1293 while (it.hasNext() && i < size) {
1294 Map.Entry<String, ArrayList<String>> ent = it.next();
1295 packages[i] = ent.getKey();
1296 components[i] = ent.getValue();
1297 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1298 uids[i] = (ps != null)
1299 ? UserHandle.getUid(packageUserId, ps.appId)
1305 mPendingBroadcasts.clear();
1308 for (int i = 0; i < size; i++) {
1309 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1311 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1314 case START_CLEANING_PACKAGE: {
1315 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1316 final String packageName = (String)msg.obj;
1317 final int userId = msg.arg1;
1318 final boolean andCode = msg.arg2 != 0;
1319 synchronized (mPackages) {
1320 if (userId == UserHandle.USER_ALL) {
1321 int[] users = sUserManager.getUserIds();
1322 for (int user : users) {
1323 mSettings.addPackageToCleanLPw(
1324 new PackageCleanItem(user, packageName, andCode));
1327 mSettings.addPackageToCleanLPw(
1328 new PackageCleanItem(userId, packageName, andCode));
1331 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1332 startCleaningPackages();
1334 case POST_INSTALL: {
1335 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1336 PostInstallData data = mRunningInstalls.get(msg.arg1);
1337 mRunningInstalls.delete(msg.arg1);
1338 boolean deleteOld = false;
1341 InstallArgs args = data.args;
1342 PackageInstalledInfo res = data.res;
1344 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1345 final String packageName = res.pkg.applicationInfo.packageName;
1346 res.removedInfo.sendBroadcast(false, true, false);
1347 Bundle extras = new Bundle(1);
1348 extras.putInt(Intent.EXTRA_UID, res.uid);
1350 // Now that we successfully installed the package, grant runtime
1351 // permissions if requested before broadcasting the install.
1352 if ((args.installFlags
1353 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1354 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1355 args.installGrantPermissions);
1358 // Determine the set of users who are adding this
1359 // package for the first time vs. those who are seeing
1362 int[] updateUsers = new int[0];
1363 if (res.origUsers == null || res.origUsers.length == 0) {
1364 firstUsers = res.newUsers;
1366 firstUsers = new int[0];
1367 for (int i=0; i<res.newUsers.length; i++) {
1368 int user = res.newUsers[i];
1369 boolean isNew = true;
1370 for (int j=0; j<res.origUsers.length; j++) {
1371 if (res.origUsers[j] == user) {
1377 int[] newFirst = new int[firstUsers.length+1];
1378 System.arraycopy(firstUsers, 0, newFirst, 0,
1380 newFirst[firstUsers.length] = user;
1381 firstUsers = newFirst;
1383 int[] newUpdate = new int[updateUsers.length+1];
1384 System.arraycopy(updateUsers, 0, newUpdate, 0,
1385 updateUsers.length);
1386 newUpdate[updateUsers.length] = user;
1387 updateUsers = newUpdate;
1391 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1392 packageName, extras, null, null, firstUsers);
1393 final boolean update = res.removedInfo.removedPackage != null;
1395 extras.putBoolean(Intent.EXTRA_REPLACING, true);
1397 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1398 packageName, extras, null, null, updateUsers);
1400 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1401 packageName, extras, null, null, updateUsers);
1402 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1403 null, null, packageName, null, updateUsers);
1405 // treat asec-hosted packages like removable media on upgrade
1406 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1407 if (DEBUG_INSTALL) {
1408 Slog.i(TAG, "upgrading pkg " + res.pkg
1409 + " is ASEC-hosted -> AVAILABLE");
1411 int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1412 ArrayList<String> pkgList = new ArrayList<String>(1);
1413 pkgList.add(packageName);
1414 sendResourcesChangedBroadcast(true, true,
1415 pkgList,uidArray, null);
1418 if (res.removedInfo.args != null) {
1419 // Remove the replaced package's older resources safely now
1423 // If this app is a browser and it's newly-installed for some
1424 // users, clear any default-browser state in those users
1425 if (firstUsers.length > 0) {
1426 // the app's nature doesn't depend on the user, so we can just
1427 // check its browser nature in any user and generalize.
1428 if (packageIsBrowser(packageName, firstUsers[0])) {
1429 synchronized (mPackages) {
1430 for (int userId : firstUsers) {
1431 mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1436 // Log current value of "unknown sources" setting
1437 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1438 getUnknownSourcesSettings());
1440 // Force a gc to clear up things
1441 Runtime.getRuntime().gc();
1442 // We delete after a gc for applications on sdcard.
1444 synchronized (mInstallLock) {
1445 res.removedInfo.args.doPostDeleteLI(true);
1448 if (args.observer != null) {
1450 Bundle extras = extrasForInstallResult(res);
1451 args.observer.onPackageInstalled(res.name, res.returnCode,
1452 res.returnMsg, extras);
1453 } catch (RemoteException e) {
1454 Slog.i(TAG, "Observer no longer exists.");
1458 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1461 case UPDATED_MEDIA_STATUS: {
1462 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1463 boolean reportStatus = msg.arg1 == 1;
1464 boolean doGc = msg.arg2 == 1;
1465 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1467 // Force a gc to clear up stale containers.
1468 Runtime.getRuntime().gc();
1470 if (msg.obj != null) {
1471 @SuppressWarnings("unchecked")
1472 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1473 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1474 // Unload containers
1475 unloadAllContainers(args);
1479 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1480 PackageHelper.getMountService().finishMediaUpdate();
1481 } catch (RemoteException e) {
1482 Log.e(TAG, "MountService not running?");
1486 case WRITE_SETTINGS: {
1487 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1488 synchronized (mPackages) {
1489 removeMessages(WRITE_SETTINGS);
1490 removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1491 mSettings.writeLPr();
1492 mDirtyUsers.clear();
1494 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1496 case WRITE_PACKAGE_RESTRICTIONS: {
1497 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1498 synchronized (mPackages) {
1499 removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1500 for (int userId : mDirtyUsers) {
1501 mSettings.writePackageRestrictionsLPr(userId);
1503 mDirtyUsers.clear();
1505 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1507 case CHECK_PENDING_VERIFICATION: {
1508 final int verificationId = msg.arg1;
1509 final PackageVerificationState state = mPendingVerification.get(verificationId);
1511 if ((state != null) && !state.timeoutExtended()) {
1512 final InstallArgs args = state.getInstallArgs();
1513 final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1515 Slog.i(TAG, "Verification timed out for " + originUri);
1516 mPendingVerification.remove(verificationId);
1518 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1520 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1521 Slog.i(TAG, "Continuing with installation of " + originUri);
1522 state.setVerifierResponse(Binder.getCallingUid(),
1523 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1524 broadcastPackageVerified(verificationId, originUri,
1525 PackageManager.VERIFICATION_ALLOW,
1526 state.getInstallArgs().getUser());
1528 ret = args.copyApk(mContainerService, true);
1529 } catch (RemoteException e) {
1530 Slog.e(TAG, "Could not contact the ContainerService");
1533 broadcastPackageVerified(verificationId, originUri,
1534 PackageManager.VERIFICATION_REJECT,
1535 state.getInstallArgs().getUser());
1538 processPendingInstall(args, ret);
1539 mHandler.sendEmptyMessage(MCS_UNBIND);
1543 case PACKAGE_VERIFIED: {
1544 final int verificationId = msg.arg1;
1546 final PackageVerificationState state = mPendingVerification.get(verificationId);
1547 if (state == null) {
1548 Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1552 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1554 state.setVerifierResponse(response.callerUid, response.code);
1556 if (state.isVerificationComplete()) {
1557 mPendingVerification.remove(verificationId);
1559 final InstallArgs args = state.getInstallArgs();
1560 final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1563 if (state.isInstallAllowed()) {
1564 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1565 broadcastPackageVerified(verificationId, originUri,
1566 response.code, state.getInstallArgs().getUser());
1568 ret = args.copyApk(mContainerService, true);
1569 } catch (RemoteException e) {
1570 Slog.e(TAG, "Could not contact the ContainerService");
1573 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1576 processPendingInstall(args, ret);
1578 mHandler.sendEmptyMessage(MCS_UNBIND);
1583 case START_INTENT_FILTER_VERIFICATIONS: {
1584 IFVerificationParams params = (IFVerificationParams) msg.obj;
1585 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1586 params.replacing, params.pkg);
1589 case INTENT_FILTER_VERIFIED: {
1590 final int verificationId = msg.arg1;
1592 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1594 if (state == null) {
1595 Slog.w(TAG, "Invalid IntentFilter verification token "
1596 + verificationId + " received");
1600 final int userId = state.getUserId();
1602 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1603 "Processing IntentFilter verification with token:"
1604 + verificationId + " and userId:" + userId);
1606 final IntentFilterVerificationResponse response =
1607 (IntentFilterVerificationResponse) msg.obj;
1609 state.setVerifierResponse(response.callerUid, response.code);
1611 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1612 "IntentFilter verification with token:" + verificationId
1613 + " and userId:" + userId
1614 + " is settings verifier response with response code:"
1617 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1618 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1619 + response.getFailedDomainsString());
1622 if (state.isVerificationComplete()) {
1623 mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1625 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1626 "IntentFilter verification with token:" + verificationId
1627 + " was not said to be complete");
1636 private StorageEventListener mStorageListener = new StorageEventListener() {
1638 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1639 if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1640 if (vol.state == VolumeInfo.STATE_MOUNTED) {
1641 final String volumeUuid = vol.getFsUuid();
1643 // Clean up any users or apps that were removed or recreated
1644 // while this volume was missing
1645 reconcileUsers(volumeUuid);
1646 reconcileApps(volumeUuid);
1648 // Clean up any install sessions that expired or were
1649 // cancelled while this volume was missing
1650 mInstallerService.onPrivateVolumeMounted(volumeUuid);
1652 loadPrivatePackages(vol);
1654 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1655 unloadPrivatePackages(vol);
1659 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1660 if (vol.state == VolumeInfo.STATE_MOUNTED) {
1661 updateExternalMediaStatus(true, false);
1662 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1663 updateExternalMediaStatus(false, false);
1669 public void onVolumeForgotten(String fsUuid) {
1670 if (TextUtils.isEmpty(fsUuid)) {
1671 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1675 // Remove any apps installed on the forgotten volume
1676 synchronized (mPackages) {
1677 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1678 for (PackageSetting ps : packages) {
1679 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1680 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1681 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1684 mSettings.onVolumeForgotten(fsUuid);
1685 mSettings.writeLPr();
1690 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1691 String[] grantedPermissions) {
1692 if (userId >= UserHandle.USER_OWNER) {
1693 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1694 } else if (userId == UserHandle.USER_ALL) {
1695 final int[] userIds;
1696 synchronized (mPackages) {
1697 userIds = UserManagerService.getInstance().getUserIds();
1699 for (int someUserId : userIds) {
1700 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1704 // We could have touched GID membership, so flush out packages.list
1705 synchronized (mPackages) {
1706 mSettings.writePackageListLPr();
1710 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1711 String[] grantedPermissions) {
1712 SettingBase sb = (SettingBase) pkg.mExtras;
1717 PermissionsState permissionsState = sb.getPermissionsState();
1719 for (String permission : pkg.requestedPermissions) {
1720 BasePermission bp = mSettings.mPermissions.get(permission);
1721 if (bp != null && bp.isRuntime() && (grantedPermissions == null
1722 || ArrayUtils.contains(grantedPermissions, permission))) {
1723 permissionsState.grantRuntimePermission(bp, userId);
1728 Bundle extrasForInstallResult(PackageInstalledInfo res) {
1729 Bundle extras = null;
1730 switch (res.returnCode) {
1731 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1732 extras = new Bundle();
1733 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1734 res.origPermission);
1735 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1739 case PackageManager.INSTALL_SUCCEEDED: {
1740 extras = new Bundle();
1741 extras.putBoolean(Intent.EXTRA_REPLACING,
1742 res.removedInfo != null && res.removedInfo.removedPackage != null);
1749 void scheduleWriteSettingsLocked() {
1750 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1751 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1755 void scheduleWritePackageRestrictionsLocked(int userId) {
1756 if (!sUserManager.exists(userId)) return;
1757 mDirtyUsers.add(userId);
1758 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1759 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1763 public static PackageManagerService main(Context context, Installer installer,
1764 boolean factoryTest, boolean onlyCore) {
1765 PackageManagerService m = new PackageManagerService(context, installer,
1766 factoryTest, onlyCore);
1767 ServiceManager.addService("package", m);
1771 static String[] splitString(String str, char sep) {
1774 while ((i=str.indexOf(sep, i)) >= 0) {
1779 String[] res = new String[count];
1783 while ((i=str.indexOf(sep, i)) >= 0) {
1784 res[count] = str.substring(lastI, i);
1789 res[count] = str.substring(lastI, str.length());
1793 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1794 DisplayManager displayManager = (DisplayManager) context.getSystemService(
1795 Context.DISPLAY_SERVICE);
1796 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1799 public PackageManagerService(Context context, Installer installer,
1800 boolean factoryTest, boolean onlyCore) {
1801 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1802 SystemClock.uptimeMillis());
1804 if (mSdkVersion <= 0) {
1805 Slog.w(TAG, "**** ro.build.version.sdk not set!");
1809 mFactoryTest = factoryTest;
1810 mOnlyCore = onlyCore;
1811 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1812 mMetrics = new DisplayMetrics();
1813 mSettings = new Settings(mPackages);
1814 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1815 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1816 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1817 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1818 mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1819 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1820 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1821 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1822 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1823 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1824 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1825 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1827 // TODO: add a property to control this?
1828 long dexOptLRUThresholdInMinutes;
1830 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1832 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1834 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1836 String separateProcesses = SystemProperties.get("debug.separate_processes");
1837 if (separateProcesses != null && separateProcesses.length() > 0) {
1838 if ("*".equals(separateProcesses)) {
1839 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1840 mSeparateProcesses = null;
1841 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1844 mSeparateProcesses = separateProcesses.split(",");
1845 Slog.w(TAG, "Running with debug.separate_processes: "
1846 + separateProcesses);
1850 mSeparateProcesses = null;
1853 mInstaller = installer;
1854 mPackageDexOptimizer = new PackageDexOptimizer(this);
1855 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1857 mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1858 FgThread.get().getLooper());
1860 getDefaultDisplayMetrics(context, mMetrics);
1862 SystemConfig systemConfig = SystemConfig.getInstance();
1863 mGlobalGids = systemConfig.getGlobalGids();
1864 mSystemPermissions = systemConfig.getSystemPermissions();
1865 mAvailableFeatures = systemConfig.getAvailableFeatures();
1867 synchronized (mInstallLock) {
1869 synchronized (mPackages) {
1870 mHandlerThread = new ServiceThread(TAG,
1871 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1872 mHandlerThread.start();
1873 mHandler = new PackageHandler(mHandlerThread.getLooper());
1874 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1876 File dataDir = Environment.getDataDirectory();
1877 mAppDataDir = new File(dataDir, "data");
1878 mAppInstallDir = new File(dataDir, "app");
1879 mAppLib32InstallDir = new File(dataDir, "app-lib");
1880 mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1881 mUserAppDataDir = new File(dataDir, "user");
1882 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1884 sUserManager = new UserManagerService(context, this,
1885 mInstallLock, mPackages);
1887 // Propagate permission configuration in to package manager.
1888 ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1889 = systemConfig.getPermissions();
1890 for (int i=0; i<permConfig.size(); i++) {
1891 SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1892 BasePermission bp = mSettings.mPermissions.get(perm.name);
1894 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1895 mSettings.mPermissions.put(perm.name, bp);
1897 if (perm.gids != null) {
1898 bp.setGids(perm.gids, perm.perUser);
1902 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1903 for (int i=0; i<libConfig.size(); i++) {
1904 mSharedLibraries.put(libConfig.keyAt(i),
1905 new SharedLibraryEntry(libConfig.valueAt(i), null));
1908 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1910 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1911 mSdkVersion, mOnlyCore);
1913 String customResolverActivity = Resources.getSystem().getString(
1914 R.string.config_customResolverActivity);
1915 if (TextUtils.isEmpty(customResolverActivity)) {
1916 customResolverActivity = null;
1918 mCustomResolverComponentName = ComponentName.unflattenFromString(
1919 customResolverActivity);
1922 long startTime = SystemClock.uptimeMillis();
1924 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1927 // Set flag to monitor and not change apk file paths when
1928 // scanning install directories.
1929 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1931 final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1934 * Add everything in the in the boot class path to the
1935 * list of process files because dexopt will have been run
1936 * if necessary during zygote startup.
1938 final String bootClassPath = System.getenv("BOOTCLASSPATH");
1939 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1941 if (bootClassPath != null) {
1942 String[] bootClassPathElements = splitString(bootClassPath, ':');
1943 for (String element : bootClassPathElements) {
1944 alreadyDexOpted.add(element);
1947 Slog.w(TAG, "No BOOTCLASSPATH found!");
1950 if (systemServerClassPath != null) {
1951 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1952 for (String element : systemServerClassPathElements) {
1953 alreadyDexOpted.add(element);
1956 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1959 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1960 final String[] dexCodeInstructionSets =
1961 getDexCodeInstructionSets(
1962 allInstructionSets.toArray(new String[allInstructionSets.size()]));
1965 * Ensure all external libraries have had dexopt run on them.
1967 if (mSharedLibraries.size() > 0) {
1968 // NOTE: For now, we're compiling these system "shared libraries"
1969 // (and framework jars) into all available architectures. It's possible
1970 // to compile them only when we come across an app that uses them (there's
1971 // already logic for that in scanPackageLI) but that adds some complexity.
1972 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1973 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1974 final String lib = libEntry.path;
1980 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1981 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1982 alreadyDexOpted.add(lib);
1983 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1985 } catch (FileNotFoundException e) {
1986 Slog.w(TAG, "Library not found: " + lib);
1987 } catch (IOException e) {
1988 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1995 File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1997 // Gross hack for now: we know this file doesn't contain any
1998 // code, so don't dexopt it to avoid the resulting log spew.
1999 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
2001 // Gross hack for now: we know this file is only part of
2002 // the boot class path for art, so don't dexopt it to
2003 // avoid the resulting log spew.
2004 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
2007 * There are a number of commands implemented in Java, which
2008 * we currently need to do the dexopt on so that they can be
2009 * run from a non-root shell.
2011 String[] frameworkFiles = frameworkDir.list();
2012 if (frameworkFiles != null) {
2013 // TODO: We could compile these only for the most preferred ABI. We should
2014 // first double check that the dex files for these commands are not referenced
2015 // by other system apps.
2016 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2017 for (int i=0; i<frameworkFiles.length; i++) {
2018 File libPath = new File(frameworkDir, frameworkFiles[i]);
2019 String path = libPath.getPath();
2020 // Skip the file if we already did it.
2021 if (alreadyDexOpted.contains(path)) {
2024 // Skip the file if it is not a type we want to dexopt.
2025 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2029 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2030 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2031 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2033 } catch (FileNotFoundException e) {
2034 Slog.w(TAG, "Jar not found: " + path);
2035 } catch (IOException e) {
2036 Slog.w(TAG, "Exception reading jar: " + path, e);
2042 final VersionInfo ver = mSettings.getInternalVersion();
2043 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2044 // when upgrading from pre-M, promote system app permissions from install to runtime
2045 mPromoteSystemApps =
2046 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2048 // save off the names of pre-existing system packages prior to scanning; we don't
2049 // want to automatically grant runtime permissions for new system apps
2050 if (mPromoteSystemApps) {
2051 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2052 while (pkgSettingIter.hasNext()) {
2053 PackageSetting ps = pkgSettingIter.next();
2054 if (isSystemApp(ps)) {
2055 mExistingSystemPackages.add(ps.name);
2060 // Collect vendor overlay packages.
2061 // (Do this before scanning any apps.)
2062 // For security and version matching reason, only consider
2063 // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2064 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2065 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2066 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2068 // Find base frameworks (resource packages without code).
2069 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2070 | PackageParser.PARSE_IS_SYSTEM_DIR
2071 | PackageParser.PARSE_IS_PRIVILEGED,
2072 scanFlags | SCAN_NO_DEX, 0);
2074 // Collected privileged system packages.
2075 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2076 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2077 | PackageParser.PARSE_IS_SYSTEM_DIR
2078 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2080 // Collect ordinary system packages.
2081 final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2082 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2083 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2085 // Collect all vendor packages.
2086 File vendorAppDir = new File("/vendor/app");
2088 vendorAppDir = vendorAppDir.getCanonicalFile();
2089 } catch (IOException e) {
2090 // failed to look up canonical path, continue with original one
2092 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2093 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2095 // Collect all OEM packages.
2096 final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2097 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2098 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2100 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2101 mInstaller.moveFiles();
2103 // Prune any system packages that no longer exist.
2104 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2106 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2107 while (psit.hasNext()) {
2108 PackageSetting ps = psit.next();
2111 * If this is not a system app, it can't be a
2112 * disable system app.
2114 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2119 * If the package is scanned, it's not erased.
2121 final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2122 if (scannedPkg != null) {
2124 * If the system app is both scanned and in the
2125 * disabled packages list, then it must have been
2126 * added via OTA. Remove it from the currently
2127 * scanned package so the previously user-installed
2128 * application can be scanned.
2130 if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2131 logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2132 + ps.name + "; removing system app. Last known codePath="
2133 + ps.codePathString + ", installStatus=" + ps.installStatus
2134 + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2135 + scannedPkg.mVersionCode);
2136 removePackageLI(ps, true);
2137 mExpectingBetter.put(ps.name, ps.codePath);
2143 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2145 logCriticalInfo(Log.WARN, "System package " + ps.name
2146 + " no longer exists; wiping its data");
2147 removeDataDirsLI(null, ps.name);
2149 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2150 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2151 possiblyDeletedUpdatedSystemApps.add(ps.name);
2157 //look for any incomplete package installations
2158 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2160 for(int i = 0; i < deletePkgsList.size(); i++) {
2162 cleanupInstallFailedPackage(deletePkgsList.get(i));
2165 deleteTempPackageFiles();
2167 // Remove any shared userIDs that have no associated packages
2168 mSettings.pruneSharedUsersLPw();
2171 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2172 SystemClock.uptimeMillis());
2173 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2175 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2176 scanFlags | SCAN_REQUIRE_KNOWN, 0);
2179 * Remove disable package settings for any updated system
2180 * apps that were removed via an OTA. If they're not a
2181 * previously-updated app, remove them completely.
2182 * Otherwise, just revoke their system-level permissions.
2184 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2185 PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2186 mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2189 if (deletedPkg == null) {
2190 msg = "Updated system package " + deletedAppName
2191 + " no longer exists; wiping its data";
2192 removeDataDirsLI(null, deletedAppName);
2194 msg = "Updated system app + " + deletedAppName
2195 + " no longer present; removing system privileges for "
2198 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2200 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2201 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2203 logCriticalInfo(Log.WARN, msg);
2207 * Make sure all system apps that we expected to appear on
2208 * the userdata partition actually showed up. If they never
2209 * appeared, crawl back and revive the system version.
2211 for (int i = 0; i < mExpectingBetter.size(); i++) {
2212 final String packageName = mExpectingBetter.keyAt(i);
2213 if (!mPackages.containsKey(packageName)) {
2214 final File scanFile = mExpectingBetter.valueAt(i);
2216 logCriticalInfo(Log.WARN, "Expected better " + packageName
2217 + " but never showed up; reverting to system");
2219 final int reparseFlags;
2220 if (FileUtils.contains(privilegedAppDir, scanFile)) {
2221 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2222 | PackageParser.PARSE_IS_SYSTEM_DIR
2223 | PackageParser.PARSE_IS_PRIVILEGED;
2224 } else if (FileUtils.contains(systemAppDir, scanFile)) {
2225 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2226 | PackageParser.PARSE_IS_SYSTEM_DIR;
2227 } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2228 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2229 | PackageParser.PARSE_IS_SYSTEM_DIR;
2230 } else if (FileUtils.contains(oemAppDir, scanFile)) {
2231 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2232 | PackageParser.PARSE_IS_SYSTEM_DIR;
2234 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2238 mSettings.enableSystemPackageLPw(packageName);
2241 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2242 } catch (PackageManagerException e) {
2243 Slog.e(TAG, "Failed to parse original system package: "
2249 mExpectingBetter.clear();
2251 // Now that we know all of the shared libraries, update all clients to have
2252 // the correct library paths.
2253 updateAllSharedLibrariesLPw();
2255 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2256 // NOTE: We ignore potential failures here during a system scan (like
2257 // the rest of the commands above) because there's precious little we
2258 // can do about it. A settings error is reported, though.
2259 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2260 false /* force dexopt */, false /* defer dexopt */);
2263 // Now that we know all the packages we are keeping,
2264 // read and update their last usage times.
2265 mPackageUsage.readLP();
2267 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2268 SystemClock.uptimeMillis());
2269 Slog.i(TAG, "Time to scan packages: "
2270 + ((SystemClock.uptimeMillis()-startTime)/1000f)
2273 // If the platform SDK has changed since the last time we booted,
2274 // we need to re-grant app permission to catch any new ones that
2275 // appear. This is really a hack, and means that apps can in some
2276 // cases get permissions that the user didn't initially explicitly
2277 // allow... it would be nice to have some better way to handle
2279 int updateFlags = UPDATE_PERMISSIONS_ALL;
2280 if (ver.sdkVersion != mSdkVersion) {
2281 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2282 + mSdkVersion + "; regranting permissions for internal storage");
2283 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2285 updatePermissionsLPw(null, null, updateFlags);
2286 ver.sdkVersion = mSdkVersion;
2288 // If this is the first boot or an update from pre-M, and it is a normal
2289 // boot, then we need to initialize the default preferred apps across
2290 // all defined users.
2291 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2292 for (UserInfo user : sUserManager.getUsers(true)) {
2293 mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2294 applyFactoryDefaultBrowserLPw(user.id);
2295 primeDomainVerificationsLPw(user.id);
2299 // If this is first boot after an OTA, and a normal boot, then
2300 // we need to clear code cache directories.
2301 if (mIsUpgrade && !onlyCore) {
2302 Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2303 for (int i = 0; i < mSettings.mPackages.size(); i++) {
2304 final PackageSetting ps = mSettings.mPackages.valueAt(i);
2305 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2306 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2309 ver.fingerprint = Build.FINGERPRINT;
2312 checkDefaultBrowser();
2314 // clear only after permissions and other defaults have been updated
2315 mExistingSystemPackages.clear();
2316 mPromoteSystemApps = false;
2318 // All the changes are done during package scanning.
2319 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2321 // can downgrade to reader
2322 mSettings.writeLPr();
2324 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2325 SystemClock.uptimeMillis());
2327 mRequiredVerifierPackage = getRequiredVerifierLPr();
2328 mRequiredInstallerPackage = getRequiredInstallerLPr();
2330 mInstallerService = new PackageInstallerService(context, this);
2332 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2333 mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2334 mIntentFilterVerifierComponent);
2336 } // synchronized (mPackages)
2337 } // synchronized (mInstallLock)
2339 // Now after opening every single application zip, make sure they
2340 // are all flushed. Not really needed, but keeps things nice and
2342 Runtime.getRuntime().gc();
2344 // Expose private service for system components to use.
2345 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2349 public boolean isFirstBoot() {
2350 return !mRestoredSettings;
2354 public boolean isOnlyCoreApps() {
2359 public boolean isUpgrade() {
2363 private String getRequiredVerifierLPr() {
2364 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2365 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2366 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2368 String requiredVerifier = null;
2370 final int N = receivers.size();
2371 for (int i = 0; i < N; i++) {
2372 final ResolveInfo info = receivers.get(i);
2374 if (info.activityInfo == null) {
2378 final String packageName = info.activityInfo.packageName;
2380 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2381 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2385 if (requiredVerifier != null) {
2386 throw new RuntimeException("There can be only one required verifier");
2389 requiredVerifier = packageName;
2392 return requiredVerifier;
2395 private String getRequiredInstallerLPr() {
2396 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2397 installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2398 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2400 final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2401 PACKAGE_MIME_TYPE, 0, 0);
2403 String requiredInstaller = null;
2405 final int N = installers.size();
2406 for (int i = 0; i < N; i++) {
2407 final ResolveInfo info = installers.get(i);
2408 final String packageName = info.activityInfo.packageName;
2410 if (!info.activityInfo.applicationInfo.isSystemApp()) {
2414 if (requiredInstaller != null) {
2415 throw new RuntimeException("There must be one required installer");
2418 requiredInstaller = packageName;
2421 if (requiredInstaller == null) {
2422 throw new RuntimeException("There must be one required installer");
2425 return requiredInstaller;
2428 private ComponentName getIntentFilterVerifierComponentNameLPr() {
2429 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2430 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2431 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2433 ComponentName verifierComponentName = null;
2435 int priority = -1000;
2436 final int N = receivers.size();
2437 for (int i = 0; i < N; i++) {
2438 final ResolveInfo info = receivers.get(i);
2440 if (info.activityInfo == null) {
2444 final String packageName = info.activityInfo.packageName;
2446 final PackageSetting ps = mSettings.mPackages.get(packageName);
2451 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2452 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2456 // Select the IntentFilterVerifier with the highest priority
2457 if (priority < info.priority) {
2458 priority = info.priority;
2459 verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2460 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2461 + verifierComponentName + " with priority: " + info.priority);
2465 return verifierComponentName;
2468 private void primeDomainVerificationsLPw(int userId) {
2469 if (DEBUG_DOMAIN_VERIFICATION) {
2470 Slog.d(TAG, "Priming domain verifications in user " + userId);
2473 SystemConfig systemConfig = SystemConfig.getInstance();
2474 ArraySet<String> packages = systemConfig.getLinkedApps();
2475 ArraySet<String> domains = new ArraySet<String>();
2477 for (String packageName : packages) {
2478 PackageParser.Package pkg = mPackages.get(packageName);
2480 if (!pkg.isSystemApp()) {
2481 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2486 for (PackageParser.Activity a : pkg.activities) {
2487 for (ActivityIntentInfo filter : a.intents) {
2488 if (hasValidDomains(filter)) {
2489 domains.addAll(filter.getHostsList());
2494 if (domains.size() > 0) {
2495 if (DEBUG_DOMAIN_VERIFICATION) {
2496 Slog.v(TAG, " + " + packageName);
2498 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2499 // state w.r.t. the formal app-linkage "no verification attempted" state;
2500 // and then 'always' in the per-user state actually used for intent resolution.
2501 final IntentFilterVerificationInfo ivi;
2502 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2503 new ArrayList<String>(domains));
2504 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2505 mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2506 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2508 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2509 + "' does not handle web links");
2512 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2516 scheduleWritePackageRestrictionsLocked(userId);
2517 scheduleWriteSettingsLocked();
2520 private void applyFactoryDefaultBrowserLPw(int userId) {
2521 // The default browser app's package name is stored in a string resource,
2522 // with a product-specific overlay used for vendor customization.
2523 String browserPkg = mContext.getResources().getString(
2524 com.android.internal.R.string.default_browser);
2525 if (!TextUtils.isEmpty(browserPkg)) {
2526 // non-empty string => required to be a known package
2527 PackageSetting ps = mSettings.mPackages.get(browserPkg);
2529 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2532 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2536 // Nothing valid explicitly set? Make the factory-installed browser the explicit
2537 // default. If there's more than one, just leave everything alone.
2538 if (browserPkg == null) {
2539 calculateDefaultBrowserLPw(userId);
2543 private void calculateDefaultBrowserLPw(int userId) {
2544 List<String> allBrowsers = resolveAllBrowserApps(userId);
2545 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2546 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2549 private List<String> resolveAllBrowserApps(int userId) {
2550 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2551 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2552 PackageManager.MATCH_ALL, userId);
2554 final int count = list.size();
2555 List<String> result = new ArrayList<String>(count);
2556 for (int i=0; i<count; i++) {
2557 ResolveInfo info = list.get(i);
2558 if (info.activityInfo == null
2559 || !info.handleAllWebDataURI
2560 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2561 || result.contains(info.activityInfo.packageName)) {
2564 result.add(info.activityInfo.packageName);
2570 private boolean packageIsBrowser(String packageName, int userId) {
2571 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2572 PackageManager.MATCH_ALL, userId);
2573 final int N = list.size();
2574 for (int i = 0; i < N; i++) {
2575 ResolveInfo info = list.get(i);
2576 if (packageName.equals(info.activityInfo.packageName)) {
2583 private void checkDefaultBrowser() {
2584 final int myUserId = UserHandle.myUserId();
2585 final String packageName = getDefaultBrowserPackageName(myUserId);
2586 if (packageName != null) {
2587 PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2589 Slog.w(TAG, "Default browser no longer installed: " + packageName);
2590 synchronized (mPackages) {
2591 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1
2598 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2599 throws RemoteException {
2601 return super.onTransact(code, data, reply, flags);
2602 } catch (RuntimeException e) {
2603 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2604 Slog.wtf(TAG, "Package Manager Crash", e);
2610 void cleanupInstallFailedPackage(PackageSetting ps) {
2611 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2613 removeDataDirsLI(ps.volumeUuid, ps.name);
2614 if (ps.codePath != null) {
2615 if (ps.codePath.isDirectory()) {
2616 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2618 ps.codePath.delete();
2621 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2622 if (ps.resourcePath.isDirectory()) {
2623 FileUtils.deleteContents(ps.resourcePath);
2625 ps.resourcePath.delete();
2627 mSettings.removePackageLPw(ps.name);
2630 static int[] appendInts(int[] cur, int[] add) {
2631 if (add == null) return cur;
2632 if (cur == null) return add;
2633 final int N = add.length;
2634 for (int i=0; i<N; i++) {
2635 cur = appendInt(cur, add[i]);
2640 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2641 if (!sUserManager.exists(userId)) return null;
2642 final PackageSetting ps = (PackageSetting) p.mExtras;
2647 final PermissionsState permissionsState = ps.getPermissionsState();
2649 final int[] gids = permissionsState.computeGids(userId);
2650 final Set<String> permissions = permissionsState.getPermissions(userId);
2651 final PackageUserState state = ps.readUserState(userId);
2653 return PackageParser.generatePackageInfo(p, gids, flags,
2654 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2658 public boolean isPackageFrozen(String packageName) {
2659 synchronized (mPackages) {
2660 final PackageSetting ps = mSettings.mPackages.get(packageName);
2665 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2670 public boolean isPackageAvailable(String packageName, int userId) {
2671 if (!sUserManager.exists(userId)) return false;
2672 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2673 synchronized (mPackages) {
2674 PackageParser.Package p = mPackages.get(packageName);
2676 final PackageSetting ps = (PackageSetting) p.mExtras;
2678 final PackageUserState state = ps.readUserState(userId);
2679 if (state != null) {
2680 return PackageParser.isAvailable(state);
2689 public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2690 if (!sUserManager.exists(userId)) return null;
2691 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2693 synchronized (mPackages) {
2694 PackageParser.Package p = mPackages.get(packageName);
2695 if (DEBUG_PACKAGE_INFO)
2696 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2698 return generatePackageInfo(p, flags, userId);
2700 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2701 return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2708 public String[] currentToCanonicalPackageNames(String[] names) {
2709 String[] out = new String[names.length];
2711 synchronized (mPackages) {
2712 for (int i=names.length-1; i>=0; i--) {
2713 PackageSetting ps = mSettings.mPackages.get(names[i]);
2714 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2721 public String[] canonicalToCurrentPackageNames(String[] names) {
2722 String[] out = new String[names.length];
2724 synchronized (mPackages) {
2725 for (int i=names.length-1; i>=0; i--) {
2726 String cur = mSettings.mRenamedPackages.get(names[i]);
2727 out[i] = cur != null ? cur : names[i];
2734 public int getPackageUid(String packageName, int userId) {
2735 if (!sUserManager.exists(userId)) return -1;
2736 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2739 synchronized (mPackages) {
2740 PackageParser.Package p = mPackages.get(packageName);
2742 return UserHandle.getUid(userId, p.applicationInfo.uid);
2744 PackageSetting ps = mSettings.mPackages.get(packageName);
2745 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2749 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2754 public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2755 if (!sUserManager.exists(userId)) {
2759 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2763 synchronized (mPackages) {
2764 PackageParser.Package p = mPackages.get(packageName);
2765 if (DEBUG_PACKAGE_INFO) {
2766 Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2769 PackageSetting ps = (PackageSetting) p.mExtras;
2770 return ps.getPermissionsState().computeGids(userId);
2777 static PermissionInfo generatePermissionInfo(
2778 BasePermission bp, int flags) {
2779 if (bp.perm != null) {
2780 return PackageParser.generatePermissionInfo(bp.perm, flags);
2782 PermissionInfo pi = new PermissionInfo();
2784 pi.packageName = bp.sourcePackage;
2785 pi.nonLocalizedLabel = bp.name;
2786 pi.protectionLevel = bp.protectionLevel;
2791 public PermissionInfo getPermissionInfo(String name, int flags) {
2793 synchronized (mPackages) {
2794 final BasePermission p = mSettings.mPermissions.get(name);
2796 return generatePermissionInfo(p, flags);
2803 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2805 synchronized (mPackages) {
2806 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2807 for (BasePermission p : mSettings.mPermissions.values()) {
2808 if (group == null) {
2809 if (p.perm == null || p.perm.info.group == null) {
2810 out.add(generatePermissionInfo(p, flags));
2813 if (p.perm != null && group.equals(p.perm.info.group)) {
2814 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2819 if (out.size() > 0) {
2822 return mPermissionGroups.containsKey(group) ? out : null;
2827 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2829 synchronized (mPackages) {
2830 return PackageParser.generatePermissionGroupInfo(
2831 mPermissionGroups.get(name), flags);
2836 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2838 synchronized (mPackages) {
2839 final int N = mPermissionGroups.size();
2840 ArrayList<PermissionGroupInfo> out
2841 = new ArrayList<PermissionGroupInfo>(N);
2842 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2843 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2849 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2851 if (!sUserManager.exists(userId)) return null;
2852 PackageSetting ps = mSettings.mPackages.get(packageName);
2854 if (ps.pkg == null) {
2855 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2857 if (pInfo != null) {
2858 return pInfo.applicationInfo;
2862 return PackageParser.generateApplicationInfo(ps.pkg, flags,
2863 ps.readUserState(userId), userId);
2868 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2870 if (!sUserManager.exists(userId)) return null;
2871 PackageSetting ps = mSettings.mPackages.get(packageName);
2873 PackageParser.Package pkg = ps.pkg;
2875 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2878 // Only data remains, so we aren't worried about code paths
2879 pkg = new PackageParser.Package(packageName);
2880 pkg.applicationInfo.packageName = packageName;
2881 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2882 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2883 pkg.applicationInfo.dataDir = Environment
2884 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2886 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2887 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2889 return generatePackageInfo(pkg, flags, userId);
2895 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2896 if (!sUserManager.exists(userId)) return null;
2897 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2899 synchronized (mPackages) {
2900 PackageParser.Package p = mPackages.get(packageName);
2901 if (DEBUG_PACKAGE_INFO) Log.v(
2902 TAG, "getApplicationInfo " + packageName
2905 PackageSetting ps = mSettings.mPackages.get(packageName);
2906 if (ps == null) return null;
2907 // Note: isEnabledLP() does not apply here - always return info
2908 return PackageParser.generateApplicationInfo(
2909 p, flags, ps.readUserState(userId), userId);
2911 if ("android".equals(packageName)||"system".equals(packageName)) {
2912 return mAndroidApplication;
2914 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2915 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2922 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2923 final IPackageDataObserver observer) {
2924 mContext.enforceCallingOrSelfPermission(
2925 android.Manifest.permission.CLEAR_APP_CACHE, null);
2926 // Queue up an async operation since clearing cache may take a little while.
2927 mHandler.post(new Runnable() {
2929 mHandler.removeCallbacks(this);
2931 synchronized (mInstallLock) {
2932 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2934 Slog.w(TAG, "Couldn't clear application caches");
2937 if (observer != null) {
2939 observer.onRemoveCompleted(null, (retCode >= 0));
2940 } catch (RemoteException e) {
2941 Slog.w(TAG, "RemoveException when invoking call back");
2949 public void freeStorage(final String volumeUuid, final long freeStorageSize,
2950 final IntentSender pi) {
2951 mContext.enforceCallingOrSelfPermission(
2952 android.Manifest.permission.CLEAR_APP_CACHE, null);
2953 // Queue up an async operation since clearing cache may take a little while.
2954 mHandler.post(new Runnable() {
2956 mHandler.removeCallbacks(this);
2958 synchronized (mInstallLock) {
2959 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2961 Slog.w(TAG, "Couldn't clear application caches");
2966 // Callback via pending intent
2967 int code = (retCode >= 0) ? 1 : 0;
2968 pi.sendIntent(null, code, null,
2970 } catch (SendIntentException e1) {
2971 Slog.i(TAG, "Failed to send pending intent");
2978 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2979 synchronized (mInstallLock) {
2980 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2981 throw new IOException("Failed to free enough space");
2987 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2988 if (!sUserManager.exists(userId)) return null;
2989 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2990 synchronized (mPackages) {
2991 PackageParser.Activity a = mActivities.mActivities.get(component);
2993 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2994 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2995 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2996 if (ps == null) return null;
2997 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3000 if (mResolveComponentName.equals(component)) {
3001 return PackageParser.generateActivityInfo(mResolveActivity, flags,
3002 new PackageUserState(), userId);
3009 public boolean activitySupportsIntent(ComponentName component, Intent intent,
3010 String resolvedType) {
3011 synchronized (mPackages) {
3012 if (component.equals(mResolveComponentName)) {
3013 // The resolver supports EVERYTHING!
3016 PackageParser.Activity a = mActivities.mActivities.get(component);
3020 for (int i=0; i<a.intents.size(); i++) {
3021 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3022 intent.getData(), intent.getCategories(), TAG) >= 0) {
3031 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3032 if (!sUserManager.exists(userId)) return null;
3033 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3034 synchronized (mPackages) {
3035 PackageParser.Activity a = mReceivers.mActivities.get(component);
3036 if (DEBUG_PACKAGE_INFO) Log.v(
3037 TAG, "getReceiverInfo " + component + ": " + a);
3038 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3039 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3040 if (ps == null) return null;
3041 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3049 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3050 if (!sUserManager.exists(userId)) return null;
3051 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3052 synchronized (mPackages) {
3053 PackageParser.Service s = mServices.mServices.get(component);
3054 if (DEBUG_PACKAGE_INFO) Log.v(
3055 TAG, "getServiceInfo " + component + ": " + s);
3056 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3057 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3058 if (ps == null) return null;
3059 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3067 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3068 if (!sUserManager.exists(userId)) return null;
3069 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3070 synchronized (mPackages) {
3071 PackageParser.Provider p = mProviders.mProviders.get(component);
3072 if (DEBUG_PACKAGE_INFO) Log.v(
3073 TAG, "getProviderInfo " + component + ": " + p);
3074 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3075 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3076 if (ps == null) return null;
3077 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3085 public String[] getSystemSharedLibraryNames() {
3087 synchronized (mPackages) {
3088 libSet = mSharedLibraries.keySet();
3089 int size = libSet.size();
3091 String[] libs = new String[size];
3092 libSet.toArray(libs);
3102 PackageParser.Package findSharedNonSystemLibrary(String libName) {
3103 synchronized (mPackages) {
3104 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3105 if (lib != null && lib.apk != null) {
3106 return mPackages.get(lib.apk);
3113 public FeatureInfo[] getSystemAvailableFeatures() {
3114 Collection<FeatureInfo> featSet;
3115 synchronized (mPackages) {
3116 featSet = mAvailableFeatures.values();
3117 int size = featSet.size();
3119 FeatureInfo[] features = new FeatureInfo[size+1];
3120 featSet.toArray(features);
3121 FeatureInfo fi = new FeatureInfo();
3122 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3123 FeatureInfo.GL_ES_VERSION_UNDEFINED);
3124 features[size] = fi;
3132 public boolean hasSystemFeature(String name) {
3133 synchronized (mPackages) {
3134 return mAvailableFeatures.containsKey(name);
3138 private void checkValidCaller(int uid, int userId) {
3139 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3142 throw new SecurityException("Caller uid=" + uid
3143 + " is not privileged to communicate with user=" + userId);
3147 public int checkPermission(String permName, String pkgName, int userId) {
3148 if (!sUserManager.exists(userId)) {
3149 return PackageManager.PERMISSION_DENIED;
3152 synchronized (mPackages) {
3153 final PackageParser.Package p = mPackages.get(pkgName);
3154 if (p != null && p.mExtras != null) {
3155 final PackageSetting ps = (PackageSetting) p.mExtras;
3156 final PermissionsState permissionsState = ps.getPermissionsState();
3157 if (permissionsState.hasPermission(permName, userId)) {
3158 return PackageManager.PERMISSION_GRANTED;
3160 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3161 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3162 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3163 return PackageManager.PERMISSION_GRANTED;
3168 return PackageManager.PERMISSION_DENIED;
3172 public int checkUidPermission(String permName, int uid) {
3173 final int userId = UserHandle.getUserId(uid);
3175 if (!sUserManager.exists(userId)) {
3176 return PackageManager.PERMISSION_DENIED;
3179 synchronized (mPackages) {
3180 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3182 final SettingBase ps = (SettingBase) obj;
3183 final PermissionsState permissionsState = ps.getPermissionsState();
3184 if (permissionsState.hasPermission(permName, userId)) {
3185 return PackageManager.PERMISSION_GRANTED;
3187 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3188 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3189 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3190 return PackageManager.PERMISSION_GRANTED;
3193 ArraySet<String> perms = mSystemPermissions.get(uid);
3194 if (perms != null) {
3195 if (perms.contains(permName)) {
3196 return PackageManager.PERMISSION_GRANTED;
3198 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3199 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3200 return PackageManager.PERMISSION_GRANTED;
3206 return PackageManager.PERMISSION_DENIED;
3210 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3211 if (UserHandle.getCallingUserId() != userId) {
3212 mContext.enforceCallingPermission(
3213 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3214 "isPermissionRevokedByPolicy for user " + userId);
3217 if (checkPermission(permission, packageName, userId)
3218 == PackageManager.PERMISSION_GRANTED) {
3222 final long identity = Binder.clearCallingIdentity();
3224 final int flags = getPermissionFlags(permission, packageName, userId);
3225 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3227 Binder.restoreCallingIdentity(identity);
3232 public String getPermissionControllerPackageName() {
3233 synchronized (mPackages) {
3234 return mRequiredInstallerPackage;
3239 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3240 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3241 * @param checkShell TODO(yamasani):
3242 * @param message the message to log on security exception
3244 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3245 boolean checkShell, String message) {
3247 throw new IllegalArgumentException("Invalid userId " + userId);
3250 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3252 if (userId == UserHandle.getUserId(callingUid)) return;
3253 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3254 if (requireFullPermission) {
3255 mContext.enforceCallingOrSelfPermission(
3256 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3259 mContext.enforceCallingOrSelfPermission(
3260 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3261 } catch (SecurityException se) {
3262 mContext.enforceCallingOrSelfPermission(
3263 android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3269 void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3270 if (callingUid == Process.SHELL_UID) {
3272 && sUserManager.hasUserRestriction(restriction, userHandle)) {
3273 throw new SecurityException("Shell does not have permission to access user "
3275 } else if (userHandle < 0) {
3276 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3277 + Debug.getCallers(3));
3282 private BasePermission findPermissionTreeLP(String permName) {
3283 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3284 if (permName.startsWith(bp.name) &&
3285 permName.length() > bp.name.length() &&
3286 permName.charAt(bp.name.length()) == '.') {
3293 private BasePermission checkPermissionTreeLP(String permName) {
3294 if (permName != null) {
3295 BasePermission bp = findPermissionTreeLP(permName);
3297 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3300 throw new SecurityException("Calling uid "
3301 + Binder.getCallingUid()
3302 + " is not allowed to add to permission tree "
3303 + bp.name + " owned by uid " + bp.uid);
3306 throw new SecurityException("No permission tree found for " + permName);
3309 static boolean compareStrings(CharSequence s1, CharSequence s2) {
3316 if (s1.getClass() != s2.getClass()) {
3319 return s1.equals(s2);
3322 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3323 if (pi1.icon != pi2.icon) return false;
3324 if (pi1.logo != pi2.logo) return false;
3325 if (pi1.protectionLevel != pi2.protectionLevel) return false;
3326 if (!compareStrings(pi1.name, pi2.name)) return false;
3327 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3328 // We'll take care of setting this one.
3329 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3330 // These are not currently stored in settings.
3331 //if (!compareStrings(pi1.group, pi2.group)) return false;
3332 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3333 //if (pi1.labelRes != pi2.labelRes) return false;
3334 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3338 int permissionInfoFootprint(PermissionInfo info) {
3339 int size = info.name.length();
3340 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3341 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3345 int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3347 for (BasePermission perm : mSettings.mPermissions.values()) {
3348 if (perm.uid == tree.uid) {
3349 size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3355 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3356 // We calculate the max size of permissions defined by this uid and throw
3357 // if that plus the size of 'info' would exceed our stated maximum.
3358 if (tree.uid != Process.SYSTEM_UID) {
3359 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3360 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3361 throw new SecurityException("Permission tree size cap exceeded");
3366 boolean addPermissionLocked(PermissionInfo info, boolean async) {
3367 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3368 throw new SecurityException("Label must be specified in permission");
3370 BasePermission tree = checkPermissionTreeLP(info.name);
3371 BasePermission bp = mSettings.mPermissions.get(info.name);
3372 boolean added = bp == null;
3373 boolean changed = true;
3374 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3376 enforcePermissionCapLocked(info, tree);
3377 bp = new BasePermission(info.name, tree.sourcePackage,
3378 BasePermission.TYPE_DYNAMIC);
3379 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3380 throw new SecurityException(
3381 "Not allowed to modify non-dynamic permission "
3384 if (bp.protectionLevel == fixedLevel
3385 && bp.perm.owner.equals(tree.perm.owner)
3386 && bp.uid == tree.uid
3387 && comparePermissionInfos(bp.perm.info, info)) {
3391 bp.protectionLevel = fixedLevel;
3392 info = new PermissionInfo(info);
3393 info.protectionLevel = fixedLevel;
3394 bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3395 bp.perm.info.packageName = tree.perm.info.packageName;
3398 mSettings.mPermissions.put(info.name, bp);
3402 mSettings.writeLPr();
3404 scheduleWriteSettingsLocked();
3411 public boolean addPermission(PermissionInfo info) {
3412 synchronized (mPackages) {
3413 return addPermissionLocked(info, false);
3418 public boolean addPermissionAsync(PermissionInfo info) {
3419 synchronized (mPackages) {
3420 return addPermissionLocked(info, true);
3425 public void removePermission(String name) {
3426 synchronized (mPackages) {
3427 checkPermissionTreeLP(name);
3428 BasePermission bp = mSettings.mPermissions.get(name);
3430 if (bp.type != BasePermission.TYPE_DYNAMIC) {
3431 throw new SecurityException(
3432 "Not allowed to modify non-dynamic permission "
3435 mSettings.mPermissions.remove(name);
3436 mSettings.writeLPr();
3441 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3442 BasePermission bp) {
3443 int index = pkg.requestedPermissions.indexOf(bp.name);
3445 throw new SecurityException("Package " + pkg.packageName
3446 + " has not requested permission " + bp.name);
3448 if (!bp.isRuntime() && !bp.isDevelopment()) {
3449 throw new SecurityException("Permission " + bp.name
3450 + " is not a changeable permission type");
3455 public void grantRuntimePermission(String packageName, String name, final int userId) {
3456 if (!sUserManager.exists(userId)) {
3457 Log.e(TAG, "No such user:" + userId);
3461 mContext.enforceCallingOrSelfPermission(
3462 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3463 "grantRuntimePermission");
3465 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3466 "grantRuntimePermission");
3469 final SettingBase sb;
3471 synchronized (mPackages) {
3472 final PackageParser.Package pkg = mPackages.get(packageName);
3474 throw new IllegalArgumentException("Unknown package: " + packageName);
3477 final BasePermission bp = mSettings.mPermissions.get(name);
3479 throw new IllegalArgumentException("Unknown permission: " + name);
3482 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3484 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3485 sb = (SettingBase) pkg.mExtras;
3487 throw new IllegalArgumentException("Unknown package: " + packageName);
3490 final PermissionsState permissionsState = sb.getPermissionsState();
3492 final int flags = permissionsState.getPermissionFlags(name, userId);
3493 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3494 throw new SecurityException("Cannot grant system fixed permission: "
3495 + name + " for package: " + packageName);
3498 if (bp.isDevelopment()) {
3499 // Development permissions must be handled specially, since they are not
3500 // normal runtime permissions. For now they apply to all users.
3501 if (permissionsState.grantInstallPermission(bp) !=
3502 PermissionsState.PERMISSION_OPERATION_FAILURE) {
3503 scheduleWriteSettingsLocked();
3508 final int result = permissionsState.grantRuntimePermission(bp, userId);
3510 case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3514 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3515 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3516 mHandler.post(new Runnable() {
3519 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3525 mOnPermissionChangeListeners.onPermissionsChanged(uid);
3527 // Not critical if that is lost - app has to request again.
3528 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3531 // Only need to do this if user is initialized. Otherwise it's a new user
3532 // and there are no processes running as the user yet and there's no need
3533 // to make an expensive call to remount processes for the changed permissions.
3534 if (READ_EXTERNAL_STORAGE.equals(name)
3535 || WRITE_EXTERNAL_STORAGE.equals(name)) {
3536 final long token = Binder.clearCallingIdentity();
3538 if (sUserManager.isInitialized(userId)) {
3539 MountServiceInternal mountServiceInternal = LocalServices.getService(
3540 MountServiceInternal.class);
3541 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3544 Binder.restoreCallingIdentity(token);
3550 public void revokeRuntimePermission(String packageName, String name, int userId) {
3551 if (!sUserManager.exists(userId)) {
3552 Log.e(TAG, "No such user:" + userId);
3556 mContext.enforceCallingOrSelfPermission(
3557 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3558 "revokeRuntimePermission");
3560 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3561 "revokeRuntimePermission");
3565 synchronized (mPackages) {
3566 final PackageParser.Package pkg = mPackages.get(packageName);
3568 throw new IllegalArgumentException("Unknown package: " + packageName);
3571 final BasePermission bp = mSettings.mPermissions.get(name);
3573 throw new IllegalArgumentException("Unknown permission: " + name);
3576 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3578 SettingBase sb = (SettingBase) pkg.mExtras;
3580 throw new IllegalArgumentException("Unknown package: " + packageName);
3583 final PermissionsState permissionsState = sb.getPermissionsState();
3585 final int flags = permissionsState.getPermissionFlags(name, userId);
3586 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3587 throw new SecurityException("Cannot revoke system fixed permission: "
3588 + name + " for package: " + packageName);
3591 if (bp.isDevelopment()) {
3592 // Development permissions must be handled specially, since they are not
3593 // normal runtime permissions. For now they apply to all users.
3594 if (permissionsState.revokeInstallPermission(bp) !=
3595 PermissionsState.PERMISSION_OPERATION_FAILURE) {
3596 scheduleWriteSettingsLocked();
3601 if (permissionsState.revokeRuntimePermission(bp, userId) ==
3602 PermissionsState.PERMISSION_OPERATION_FAILURE) {
3606 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3608 // Critical, after this call app should never have the permission.
3609 mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3611 appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3614 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3618 public void resetRuntimePermissions() {
3619 mContext.enforceCallingOrSelfPermission(
3620 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3621 "revokeRuntimePermission");
3623 int callingUid = Binder.getCallingUid();
3624 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3625 mContext.enforceCallingOrSelfPermission(
3626 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3627 "resetRuntimePermissions");
3630 synchronized (mPackages) {
3631 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3632 for (int userId : UserManagerService.getInstance().getUserIds()) {
3633 final int packageCount = mPackages.size();
3634 for (int i = 0; i < packageCount; i++) {
3635 PackageParser.Package pkg = mPackages.valueAt(i);
3636 if (!(pkg.mExtras instanceof PackageSetting)) {
3639 PackageSetting ps = (PackageSetting) pkg.mExtras;
3640 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3647 public int getPermissionFlags(String name, String packageName, int userId) {
3648 if (!sUserManager.exists(userId)) {
3652 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3654 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3655 "getPermissionFlags");
3657 synchronized (mPackages) {
3658 final PackageParser.Package pkg = mPackages.get(packageName);
3660 throw new IllegalArgumentException("Unknown package: " + packageName);
3663 final BasePermission bp = mSettings.mPermissions.get(name);
3665 throw new IllegalArgumentException("Unknown permission: " + name);
3668 SettingBase sb = (SettingBase) pkg.mExtras;
3670 throw new IllegalArgumentException("Unknown package: " + packageName);
3673 PermissionsState permissionsState = sb.getPermissionsState();
3674 return permissionsState.getPermissionFlags(name, userId);
3679 public void updatePermissionFlags(String name, String packageName, int flagMask,
3680 int flagValues, int userId) {
3681 if (!sUserManager.exists(userId)) {
3685 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3687 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3688 "updatePermissionFlags");
3690 // Only the system can change these flags and nothing else.
3691 if (getCallingUid() != Process.SYSTEM_UID) {
3692 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3693 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3694 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3695 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3698 synchronized (mPackages) {
3699 final PackageParser.Package pkg = mPackages.get(packageName);
3701 throw new IllegalArgumentException("Unknown package: " + packageName);
3704 final BasePermission bp = mSettings.mPermissions.get(name);
3706 throw new IllegalArgumentException("Unknown permission: " + name);
3709 SettingBase sb = (SettingBase) pkg.mExtras;
3711 throw new IllegalArgumentException("Unknown package: " + packageName);
3714 PermissionsState permissionsState = sb.getPermissionsState();
3716 // Only the package manager can change flags for system component permissions.
3717 final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3718 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3722 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3724 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3725 // Install and runtime permissions are stored in different places,
3726 // so figure out what permission changed and persist the change.
3727 if (permissionsState.getInstallPermissionState(name) != null) {
3728 scheduleWriteSettingsLocked();
3729 } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3731 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3738 * Update the permission flags for all packages and runtime permissions of a user in order
3739 * to allow device or profile owner to remove POLICY_FIXED.
3742 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3743 if (!sUserManager.exists(userId)) {
3747 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3749 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3750 "updatePermissionFlagsForAllApps");
3752 // Only the system can change system fixed flags.
3753 if (getCallingUid() != Process.SYSTEM_UID) {
3754 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3755 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3758 synchronized (mPackages) {
3759 boolean changed = false;
3760 final int packageCount = mPackages.size();
3761 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3762 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3763 SettingBase sb = (SettingBase) pkg.mExtras;
3767 PermissionsState permissionsState = sb.getPermissionsState();
3768 changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3769 userId, flagMask, flagValues);
3772 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3777 private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3778 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3779 != PackageManager.PERMISSION_GRANTED
3780 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3781 != PackageManager.PERMISSION_GRANTED) {
3782 throw new SecurityException(message + " requires "
3783 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3784 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3789 public boolean shouldShowRequestPermissionRationale(String permissionName,
3790 String packageName, int userId) {
3791 if (UserHandle.getCallingUserId() != userId) {
3792 mContext.enforceCallingPermission(
3793 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3794 "canShowRequestPermissionRationale for user " + userId);
3797 final int uid = getPackageUid(packageName, userId);
3798 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3802 if (checkPermission(permissionName, packageName, userId)
3803 == PackageManager.PERMISSION_GRANTED) {
3809 final long identity = Binder.clearCallingIdentity();
3811 flags = getPermissionFlags(permissionName,
3812 packageName, userId);
3814 Binder.restoreCallingIdentity(identity);
3817 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3818 | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3819 | PackageManager.FLAG_PERMISSION_USER_FIXED;
3821 if ((flags & fixedFlags) != 0) {
3825 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3829 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3830 mContext.enforceCallingOrSelfPermission(
3831 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3832 "addOnPermissionsChangeListener");
3834 synchronized (mPackages) {
3835 mOnPermissionChangeListeners.addListenerLocked(listener);
3840 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3841 synchronized (mPackages) {
3842 mOnPermissionChangeListeners.removeListenerLocked(listener);
3847 public boolean isProtectedBroadcast(String actionName) {
3848 synchronized (mPackages) {
3849 return mProtectedBroadcasts.contains(actionName);
3854 public int checkSignatures(String pkg1, String pkg2) {
3855 synchronized (mPackages) {
3856 final PackageParser.Package p1 = mPackages.get(pkg1);
3857 final PackageParser.Package p2 = mPackages.get(pkg2);
3858 if (p1 == null || p1.mExtras == null
3859 || p2 == null || p2.mExtras == null) {
3860 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3862 return compareSignatures(p1.mSignatures, p2.mSignatures);
3867 public int checkUidSignatures(int uid1, int uid2) {
3868 // Map to base uids.
3869 uid1 = UserHandle.getAppId(uid1);
3870 uid2 = UserHandle.getAppId(uid2);
3872 synchronized (mPackages) {
3875 Object obj = mSettings.getUserIdLPr(uid1);
3877 if (obj instanceof SharedUserSetting) {
3878 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3879 } else if (obj instanceof PackageSetting) {
3880 s1 = ((PackageSetting)obj).signatures.mSignatures;
3882 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3885 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3887 obj = mSettings.getUserIdLPr(uid2);
3889 if (obj instanceof SharedUserSetting) {
3890 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3891 } else if (obj instanceof PackageSetting) {
3892 s2 = ((PackageSetting)obj).signatures.mSignatures;
3894 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3897 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3899 return compareSignatures(s1, s2);
3903 private void killUid(int appId, int userId, String reason) {
3904 final long identity = Binder.clearCallingIdentity();
3906 IActivityManager am = ActivityManagerNative.getDefault();
3909 am.killUid(appId, userId, reason);
3910 } catch (RemoteException e) {
3911 /* ignore - same process */
3915 Binder.restoreCallingIdentity(identity);
3920 * Compares two sets of signatures. Returns:
3922 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3924 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3926 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3928 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3930 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3932 static int compareSignatures(Signature[] s1, Signature[] s2) {
3935 ? PackageManager.SIGNATURE_NEITHER_SIGNED
3936 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3940 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3943 if (s1.length != s2.length) {
3944 return PackageManager.SIGNATURE_NO_MATCH;
3947 // Since both signature sets are of size 1, we can compare without HashSets.
3948 if (s1.length == 1) {
3949 return s1[0].equals(s2[0]) ?
3950 PackageManager.SIGNATURE_MATCH :
3951 PackageManager.SIGNATURE_NO_MATCH;
3954 ArraySet<Signature> set1 = new ArraySet<Signature>();
3955 for (Signature sig : s1) {
3958 ArraySet<Signature> set2 = new ArraySet<Signature>();
3959 for (Signature sig : s2) {
3962 // Make sure s2 contains all signatures in s1.
3963 if (set1.equals(set2)) {
3964 return PackageManager.SIGNATURE_MATCH;
3966 return PackageManager.SIGNATURE_NO_MATCH;
3970 * If the database version for this type of package (internal storage or
3971 * external storage) is less than the version where package signatures
3972 * were updated, return true.
3974 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3975 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3976 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3980 * Used for backward compatibility to make sure any packages with
3981 * certificate chains get upgraded to the new style. {@code existingSigs}
3982 * will be in the old format (since they were stored on disk from before the
3983 * system upgrade) and {@code scannedSigs} will be in the newer format.
3985 private int compareSignaturesCompat(PackageSignatures existingSigs,
3986 PackageParser.Package scannedPkg) {
3987 if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3988 return PackageManager.SIGNATURE_NO_MATCH;
3991 ArraySet<Signature> existingSet = new ArraySet<Signature>();
3992 for (Signature sig : existingSigs.mSignatures) {
3993 existingSet.add(sig);
3995 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3996 for (Signature sig : scannedPkg.mSignatures) {
3998 Signature[] chainSignatures = sig.getChainSignatures();
3999 for (Signature chainSig : chainSignatures) {
4000 scannedCompatSet.add(chainSig);
4002 } catch (CertificateEncodingException e) {
4003 scannedCompatSet.add(sig);
4007 * Make sure the expanded scanned set contains all signatures in the
4010 if (scannedCompatSet.equals(existingSet)) {
4011 // Migrate the old signatures to the new scheme.
4012 existingSigs.assignSignatures(scannedPkg.mSignatures);
4013 // The new KeySets will be re-added later in the scanning process.
4014 synchronized (mPackages) {
4015 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4017 return PackageManager.SIGNATURE_MATCH;
4019 return PackageManager.SIGNATURE_NO_MATCH;
4022 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4023 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4024 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4027 private int compareSignaturesRecover(PackageSignatures existingSigs,
4028 PackageParser.Package scannedPkg) {
4029 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4030 return PackageManager.SIGNATURE_NO_MATCH;
4035 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4036 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4037 + scannedPkg.packageName);
4038 return PackageManager.SIGNATURE_MATCH;
4040 } catch (CertificateException e) {
4041 msg = e.getMessage();
4044 logCriticalInfo(Log.INFO,
4045 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4046 return PackageManager.SIGNATURE_NO_MATCH;
4050 public String[] getPackagesForUid(int uid) {
4051 uid = UserHandle.getAppId(uid);
4053 synchronized (mPackages) {
4054 Object obj = mSettings.getUserIdLPr(uid);
4055 if (obj instanceof SharedUserSetting) {
4056 final SharedUserSetting sus = (SharedUserSetting) obj;
4057 final int N = sus.packages.size();
4058 final String[] res = new String[N];
4059 final Iterator<PackageSetting> it = sus.packages.iterator();
4061 while (it.hasNext()) {
4062 res[i++] = it.next().name;
4065 } else if (obj instanceof PackageSetting) {
4066 final PackageSetting ps = (PackageSetting) obj;
4067 return new String[] { ps.name };
4074 public String getNameForUid(int uid) {
4076 synchronized (mPackages) {
4077 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4078 if (obj instanceof SharedUserSetting) {
4079 final SharedUserSetting sus = (SharedUserSetting) obj;
4080 return sus.name + ":" + sus.userId;
4081 } else if (obj instanceof PackageSetting) {
4082 final PackageSetting ps = (PackageSetting) obj;
4090 public int getUidForSharedUser(String sharedUserName) {
4091 if(sharedUserName == null) {
4095 synchronized (mPackages) {
4096 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4105 public int getFlagsForUid(int uid) {
4106 synchronized (mPackages) {
4107 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4108 if (obj instanceof SharedUserSetting) {
4109 final SharedUserSetting sus = (SharedUserSetting) obj;
4110 return sus.pkgFlags;
4111 } else if (obj instanceof PackageSetting) {
4112 final PackageSetting ps = (PackageSetting) obj;
4120 public int getPrivateFlagsForUid(int uid) {
4121 synchronized (mPackages) {
4122 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4123 if (obj instanceof SharedUserSetting) {
4124 final SharedUserSetting sus = (SharedUserSetting) obj;
4125 return sus.pkgPrivateFlags;
4126 } else if (obj instanceof PackageSetting) {
4127 final PackageSetting ps = (PackageSetting) obj;
4128 return ps.pkgPrivateFlags;
4135 public boolean isUidPrivileged(int uid) {
4136 uid = UserHandle.getAppId(uid);
4138 synchronized (mPackages) {
4139 Object obj = mSettings.getUserIdLPr(uid);
4140 if (obj instanceof SharedUserSetting) {
4141 final SharedUserSetting sus = (SharedUserSetting) obj;
4142 final Iterator<PackageSetting> it = sus.packages.iterator();
4143 while (it.hasNext()) {
4144 if (it.next().isPrivileged()) {
4148 } else if (obj instanceof PackageSetting) {
4149 final PackageSetting ps = (PackageSetting) obj;
4150 return ps.isPrivileged();
4157 public String[] getAppOpPermissionPackages(String permissionName) {
4158 synchronized (mPackages) {
4159 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4163 return pkgs.toArray(new String[pkgs.size()]);
4168 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4169 int flags, int userId) {
4170 if (!sUserManager.exists(userId)) return null;
4171 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4172 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4173 return chooseBestActivity(intent, resolvedType, flags, query, userId);
4177 public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4178 IntentFilter filter, int match, ComponentName activity) {
4179 final int userId = UserHandle.getCallingUserId();
4180 if (DEBUG_PREFERRED) {
4181 Log.v(TAG, "setLastChosenActivity intent=" + intent
4182 + " resolvedType=" + resolvedType
4184 + " filter=" + filter
4186 + " activity=" + activity);
4187 filter.dump(new PrintStreamPrinter(System.out), " ");
4189 intent.setComponent(null);
4190 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4191 // Find any earlier preferred or last chosen entries and nuke them
4192 findPreferredActivity(intent, resolvedType,
4193 flags, query, 0, false, true, false, userId);
4194 // Add the new activity as the last chosen for this filter
4195 addPreferredActivityInternal(filter, match, null, activity, false, userId,
4196 "Setting last chosen");
4200 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4201 final int userId = UserHandle.getCallingUserId();
4202 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4203 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4204 return findPreferredActivity(intent, resolvedType, flags, query, 0,
4205 false, false, false, userId);
4208 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4209 int flags, List<ResolveInfo> query, int userId) {
4210 if (query != null) {
4211 final int N = query.size();
4213 return query.get(0);
4215 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4216 // If there is more than one activity with the same priority,
4217 // then let the user decide between them.
4218 ResolveInfo r0 = query.get(0);
4219 ResolveInfo r1 = query.get(1);
4220 if (DEBUG_INTENT_MATCHING || debug) {
4221 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4222 + r1.activityInfo.name + "=" + r1.priority);
4224 // If the first activity has a higher priority, or a different
4225 // default, then it is always desireable to pick it.
4226 if (r0.priority != r1.priority
4227 || r0.preferredOrder != r1.preferredOrder
4228 || r0.isDefault != r1.isDefault) {
4229 return query.get(0);
4231 // If we have saved a preference for a preferred activity for
4232 // this Intent, use that.
4233 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4234 flags, query, r0.priority, true, false, debug, userId);
4238 ri = new ResolveInfo(mResolveInfo);
4239 ri.activityInfo = new ActivityInfo(ri.activityInfo);
4240 ri.activityInfo.applicationInfo = new ApplicationInfo(
4241 ri.activityInfo.applicationInfo);
4243 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4244 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4246 // Make sure that the resolver is displayable in car mode
4247 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4248 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4255 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4256 int flags, List<ResolveInfo> query, boolean debug, int userId) {
4257 final int N = query.size();
4258 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4260 // Get the list of persistent preferred activities that handle the intent
4261 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4262 List<PersistentPreferredActivity> pprefs = ppir != null
4263 ? ppir.queryIntent(intent, resolvedType,
4264 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4266 if (pprefs != null && pprefs.size() > 0) {
4267 final int M = pprefs.size();
4268 for (int i=0; i<M; i++) {
4269 final PersistentPreferredActivity ppa = pprefs.get(i);
4270 if (DEBUG_PREFERRED || debug) {
4271 Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4272 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4273 + "\n component=" + ppa.mComponent);
4274 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
4276 final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4277 flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4278 if (DEBUG_PREFERRED || debug) {
4279 Slog.v(TAG, "Found persistent preferred activity:");
4281 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
4283 Slog.v(TAG, " null");
4287 // This previously registered persistent preferred activity
4288 // component is no longer known. Ignore it and do NOT remove it.
4291 for (int j=0; j<N; j++) {
4292 final ResolveInfo ri = query.get(j);
4293 if (!ri.activityInfo.applicationInfo.packageName
4294 .equals(ai.applicationInfo.packageName)) {
4297 if (!ri.activityInfo.name.equals(ai.name)) {
4300 // Found a persistent preference that can handle the intent.
4301 if (DEBUG_PREFERRED || debug) {
4302 Slog.v(TAG, "Returning persistent preferred activity: " +
4303 ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4312 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4313 List<ResolveInfo> query, int priority, boolean always,
4314 boolean removeMatches, boolean debug, int userId) {
4315 if (!sUserManager.exists(userId)) return null;
4317 synchronized (mPackages) {
4318 if (intent.getSelector() != null) {
4319 intent = intent.getSelector();
4321 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4323 // Try to find a matching persistent preferred activity.
4324 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4327 // If a persistent preferred activity matched, use it.
4332 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4333 // Get the list of preferred activities that handle the intent
4334 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4335 List<PreferredActivity> prefs = pir != null
4336 ? pir.queryIntent(intent, resolvedType,
4337 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4339 if (prefs != null && prefs.size() > 0) {
4340 boolean changed = false;
4342 // First figure out how good the original match set is.
4343 // We will only allow preferred activities that came
4344 // from the same match quality.
4347 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4349 final int N = query.size();
4350 for (int j=0; j<N; j++) {
4351 final ResolveInfo ri = query.get(j);
4352 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4353 + ": 0x" + Integer.toHexString(match));
4354 if (ri.match > match) {
4359 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4360 + Integer.toHexString(match));
4362 match &= IntentFilter.MATCH_CATEGORY_MASK;
4363 final int M = prefs.size();
4364 for (int i=0; i<M; i++) {
4365 final PreferredActivity pa = prefs.get(i);
4366 if (DEBUG_PREFERRED || debug) {
4367 Slog.v(TAG, "Checking PreferredActivity ds="
4368 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4369 + "\n component=" + pa.mPref.mComponent);
4370 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
4372 if (pa.mPref.mMatch != match) {
4373 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4374 + Integer.toHexString(pa.mPref.mMatch));
4377 // If it's not an "always" type preferred activity and that's what we're
4378 // looking for, skip it.
4379 if (always && !pa.mPref.mAlways) {
4380 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4383 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4384 flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4385 if (DEBUG_PREFERRED || debug) {
4386 Slog.v(TAG, "Found preferred activity:");
4388 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
4390 Slog.v(TAG, " null");
4394 // This previously registered preferred activity
4395 // component is no longer known. Most likely an update
4396 // to the app was installed and in the new version this
4397 // component no longer exists. Clean it up by removing
4398 // it from the preferred activities list, and skip it.
4399 Slog.w(TAG, "Removing dangling preferred activity: "
4400 + pa.mPref.mComponent);
4401 pir.removeFilter(pa);
4405 for (int j=0; j<N; j++) {
4406 final ResolveInfo ri = query.get(j);
4407 if (!ri.activityInfo.applicationInfo.packageName
4408 .equals(ai.applicationInfo.packageName)) {
4411 if (!ri.activityInfo.name.equals(ai.name)) {
4415 if (removeMatches) {
4416 pir.removeFilter(pa);
4418 if (DEBUG_PREFERRED) {
4419 Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4424 // Okay we found a previously set preferred or last chosen app.
4425 // If the result set is different from when this
4426 // was created, we need to clear it and re-ask the
4427 // user their preference, if we're looking for an "always" type entry.
4428 if (always && !pa.mPref.sameSet(query)) {
4429 Slog.i(TAG, "Result set changed, dropping preferred activity for "
4430 + intent + " type " + resolvedType);
4431 if (DEBUG_PREFERRED) {
4432 Slog.v(TAG, "Removing preferred activity since set changed "
4433 + pa.mPref.mComponent);
4435 pir.removeFilter(pa);
4436 // Re-add the filter as a "last chosen" entry (!always)
4437 PreferredActivity lastChosen = new PreferredActivity(
4438 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4439 pir.addFilter(lastChosen);
4444 // Yay! Either the set matched or we're looking for the last chosen
4445 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4446 + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4452 if (DEBUG_PREFERRED) {
4453 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4455 scheduleWritePackageRestrictionsLocked(userId);
4460 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4465 * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4468 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4470 mContext.enforceCallingOrSelfPermission(
4471 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4472 List<CrossProfileIntentFilter> matches =
4473 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4474 if (matches != null) {
4475 int size = matches.size();
4476 for (int i = 0; i < size; i++) {
4477 if (matches.get(i).getTargetUserId() == targetUserId) return true;
4480 if (hasWebURI(intent)) {
4481 // cross-profile app linking works only towards the parent.
4482 final UserInfo parent = getProfileParent(sourceUserId);
4483 synchronized(mPackages) {
4484 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4485 intent, resolvedType, 0, sourceUserId, parent.id);
4486 return xpDomainInfo != null;
4492 private UserInfo getProfileParent(int userId) {
4493 final long identity = Binder.clearCallingIdentity();
4495 return sUserManager.getProfileParent(userId);
4497 Binder.restoreCallingIdentity(identity);
4501 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4502 String resolvedType, int userId) {
4503 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4504 if (resolver != null) {
4505 return resolver.queryIntent(intent, resolvedType, false, userId);
4511 public List<ResolveInfo> queryIntentActivities(Intent intent,
4512 String resolvedType, int flags, int userId) {
4513 if (!sUserManager.exists(userId)) return Collections.emptyList();
4514 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4515 ComponentName comp = intent.getComponent();
4517 if (intent.getSelector() != null) {
4518 intent = intent.getSelector();
4519 comp = intent.getComponent();
4524 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4525 final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4527 final ResolveInfo ri = new ResolveInfo();
4528 ri.activityInfo = ai;
4535 synchronized (mPackages) {
4536 final String pkgName = intent.getPackage();
4537 if (pkgName == null) {
4538 List<CrossProfileIntentFilter> matchingFilters =
4539 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4540 // Check for results that need to skip the current profile.
4541 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
4542 resolvedType, flags, userId);
4543 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4544 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4545 result.add(xpResolveInfo);
4546 return filterIfNotPrimaryUser(result, userId);
4549 // Check for results in the current profile.
4550 List<ResolveInfo> result = mActivities.queryIntent(
4551 intent, resolvedType, flags, userId);
4553 // Check for cross profile results.
4554 xpResolveInfo = queryCrossProfileIntents(
4555 matchingFilters, intent, resolvedType, flags, userId);
4556 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4557 result.add(xpResolveInfo);
4558 Collections.sort(result, mResolvePrioritySorter);
4560 result = filterIfNotPrimaryUser(result, userId);
4561 if (hasWebURI(intent)) {
4562 CrossProfileDomainInfo xpDomainInfo = null;
4563 final UserInfo parent = getProfileParent(userId);
4564 if (parent != null) {
4565 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4566 flags, userId, parent.id);
4568 if (xpDomainInfo != null) {
4569 if (xpResolveInfo != null) {
4570 // If we didn't remove it, the cross-profile ResolveInfo would be twice
4572 result.remove(xpResolveInfo);
4574 if (result.size() == 0) {
4575 result.add(xpDomainInfo.resolveInfo);
4578 } else if (result.size() <= 1) {
4581 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4582 xpDomainInfo, userId);
4583 Collections.sort(result, mResolvePrioritySorter);
4587 final PackageParser.Package pkg = mPackages.get(pkgName);
4589 return filterIfNotPrimaryUser(
4590 mActivities.queryIntentForPackage(
4591 intent, resolvedType, flags, pkg.activities, userId),
4594 return new ArrayList<ResolveInfo>();
4598 private static class CrossProfileDomainInfo {
4599 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4600 ResolveInfo resolveInfo;
4601 /* Best domain verification status of the activities found in the other profile */
4602 int bestDomainVerificationStatus;
4605 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4606 String resolvedType, int flags, int sourceUserId, int parentUserId) {
4607 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4611 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4612 resolvedType, flags, parentUserId);
4614 if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4617 CrossProfileDomainInfo result = null;
4618 int size = resultTargetUser.size();
4619 for (int i = 0; i < size; i++) {
4620 ResolveInfo riTargetUser = resultTargetUser.get(i);
4621 // Intent filter verification is only for filters that specify a host. So don't return
4622 // those that handle all web uris.
4623 if (riTargetUser.handleAllWebDataURI) {
4626 String packageName = riTargetUser.activityInfo.packageName;
4627 PackageSetting ps = mSettings.mPackages.get(packageName);
4631 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4632 int status = (int)(verificationState >> 32);
4633 if (result == null) {
4634 result = new CrossProfileDomainInfo();
4635 result.resolveInfo =
4636 createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId);
4637 result.bestDomainVerificationStatus = status;
4639 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4640 result.bestDomainVerificationStatus);
4643 // Don't consider matches with status NEVER across profiles.
4644 if (result != null && result.bestDomainVerificationStatus
4645 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4652 * Verification statuses are ordered from the worse to the best, except for
4653 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4655 private int bestDomainVerificationStatus(int status1, int status2) {
4656 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4659 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4662 return (int) MathUtils.max(status1, status2);
4665 private boolean isUserEnabled(int userId) {
4666 long callingId = Binder.clearCallingIdentity();
4668 UserInfo userInfo = sUserManager.getUserInfo(userId);
4669 return userInfo != null && userInfo.isEnabled();
4671 Binder.restoreCallingIdentity(callingId);
4676 * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4678 * @return filtered list
4680 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4681 if (userId == UserHandle.USER_OWNER) {
4682 return resolveInfos;
4684 for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4685 ResolveInfo info = resolveInfos.get(i);
4686 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4687 resolveInfos.remove(i);
4690 return resolveInfos;
4693 private static boolean hasWebURI(Intent intent) {
4694 if (intent.getData() == null) {
4697 final String scheme = intent.getScheme();
4698 if (TextUtils.isEmpty(scheme)) {
4701 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4704 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4705 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4707 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4709 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4710 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4714 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4715 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4716 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4717 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4718 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4719 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4721 synchronized (mPackages) {
4722 final int count = candidates.size();
4723 // First, try to use linked apps. Partition the candidates into four lists:
4724 // one for the final results, one for the "do not use ever", one for "undefined status"
4725 // and finally one for "browser app type".
4726 for (int n=0; n<count; n++) {
4727 ResolveInfo info = candidates.get(n);
4728 String packageName = info.activityInfo.packageName;
4729 PackageSetting ps = mSettings.mPackages.get(packageName);
4731 // Add to the special match all list (Browser use case)
4732 if (info.handleAllWebDataURI) {
4733 matchAllList.add(info);
4736 // Try to get the status from User settings first
4737 long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4738 int status = (int)(packedStatus >> 32);
4739 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4740 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4741 if (DEBUG_DOMAIN_VERIFICATION) {
4742 Slog.i(TAG, " + always: " + info.activityInfo.packageName
4743 + " : linkgen=" + linkGeneration);
4745 // Use link-enabled generation as preferredOrder, i.e.
4746 // prefer newly-enabled over earlier-enabled.
4747 info.preferredOrder = linkGeneration;
4748 alwaysList.add(info);
4749 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4750 if (DEBUG_DOMAIN_VERIFICATION) {
4751 Slog.i(TAG, " + never: " + info.activityInfo.packageName);
4753 neverList.add(info);
4754 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4755 if (DEBUG_DOMAIN_VERIFICATION) {
4756 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName);
4758 alwaysAskList.add(info);
4759 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4760 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4761 if (DEBUG_DOMAIN_VERIFICATION) {
4762 Slog.i(TAG, " + ask: " + info.activityInfo.packageName);
4764 undefinedList.add(info);
4769 // We'll want to include browser possibilities in a few cases
4770 boolean includeBrowser = false;
4772 // First try to add the "always" resolution(s) for the current user, if any
4773 if (alwaysList.size() > 0) {
4774 result.addAll(alwaysList);
4775 // if there is an "always" for the parent user, add it.
4776 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4777 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4778 result.add(xpDomainInfo.resolveInfo);
4780 // Add all undefined apps as we want them to appear in the disambiguation dialog.
4781 result.addAll(undefinedList);
4782 if (xpDomainInfo != null && (
4783 xpDomainInfo.bestDomainVerificationStatus
4784 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4785 || xpDomainInfo.bestDomainVerificationStatus
4786 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4787 result.add(xpDomainInfo.resolveInfo);
4789 includeBrowser = true;
4792 // The presence of any 'always ask' alternatives means we'll also offer browsers.
4793 // If there were 'always' entries their preferred order has been set, so we also
4794 // back that off to make the alternatives equivalent
4795 if (alwaysAskList.size() > 0) {
4796 for (ResolveInfo i : result) {
4797 i.preferredOrder = 0;
4799 result.addAll(alwaysAskList);
4800 includeBrowser = true;
4803 if (includeBrowser) {
4804 // Also add browsers (all of them or only the default one)
4805 if (DEBUG_DOMAIN_VERIFICATION) {
4806 Slog.v(TAG, " ...including browsers in candidate set");
4808 if ((matchFlags & MATCH_ALL) != 0) {
4809 result.addAll(matchAllList);
4811 // Browser/generic handling case. If there's a default browser, go straight
4812 // to that (but only if there is no other higher-priority match).
4813 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4814 int maxMatchPrio = 0;
4815 ResolveInfo defaultBrowserMatch = null;
4816 final int numCandidates = matchAllList.size();
4817 for (int n = 0; n < numCandidates; n++) {
4818 ResolveInfo info = matchAllList.get(n);
4819 // track the highest overall match priority...
4820 if (info.priority > maxMatchPrio) {
4821 maxMatchPrio = info.priority;
4823 // ...and the highest-priority default browser match
4824 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4825 if (defaultBrowserMatch == null
4826 || (defaultBrowserMatch.priority < info.priority)) {
4828 Slog.v(TAG, "Considering default browser match " + info);
4830 defaultBrowserMatch = info;
4834 if (defaultBrowserMatch != null
4835 && defaultBrowserMatch.priority >= maxMatchPrio
4836 && !TextUtils.isEmpty(defaultBrowserPackageName))
4839 Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4841 result.add(defaultBrowserMatch);
4843 result.addAll(matchAllList);
4847 // If there is nothing selected, add all candidates and remove the ones that the user
4848 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4849 if (result.size() == 0) {
4850 result.addAll(candidates);
4851 result.removeAll(neverList);
4855 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4856 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4858 for (ResolveInfo info : result) {
4859 Slog.v(TAG, " + " + info.activityInfo);
4865 // Returns a packed value as a long:
4867 // high 'int'-sized word: link status: undefined/ask/never/always.
4868 // low 'int'-sized word: relative priority among 'always' results.
4869 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4870 long result = ps.getDomainVerificationStatusForUser(userId);
4871 // if none available, get the master status
4872 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4873 if (ps.getIntentFilterVerificationInfo() != null) {
4874 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4880 private ResolveInfo querySkipCurrentProfileIntents(
4881 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4882 int flags, int sourceUserId) {
4883 if (matchingFilters != null) {
4884 int size = matchingFilters.size();
4885 for (int i = 0; i < size; i ++) {
4886 CrossProfileIntentFilter filter = matchingFilters.get(i);
4887 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4888 // Checking if there are activities in the target user that can handle the
4890 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4891 flags, sourceUserId);
4892 if (resolveInfo != null) {
4901 // Return matching ResolveInfo if any for skip current profile intent filters.
4902 private ResolveInfo queryCrossProfileIntents(
4903 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4904 int flags, int sourceUserId) {
4905 if (matchingFilters != null) {
4906 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4907 // match the same intent. For performance reasons, it is better not to
4908 // run queryIntent twice for the same userId
4909 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4910 int size = matchingFilters.size();
4911 for (int i = 0; i < size; i++) {
4912 CrossProfileIntentFilter filter = matchingFilters.get(i);
4913 int targetUserId = filter.getTargetUserId();
4914 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4915 && !alreadyTriedUserIds.get(targetUserId)) {
4916 // Checking if there are activities in the target user that can handle the
4918 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4919 flags, sourceUserId);
4920 if (resolveInfo != null) return resolveInfo;
4921 alreadyTriedUserIds.put(targetUserId, true);
4928 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4929 String resolvedType, int flags, int sourceUserId) {
4930 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4931 resolvedType, flags, filter.getTargetUserId());
4932 if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4933 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4938 private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4939 int sourceUserId, int targetUserId) {
4940 ResolveInfo forwardingResolveInfo = new ResolveInfo();
4942 if (targetUserId == UserHandle.USER_OWNER) {
4943 className = FORWARD_INTENT_TO_USER_OWNER;
4945 className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4947 ComponentName forwardingActivityComponentName = new ComponentName(
4948 mAndroidApplication.packageName, className);
4949 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4951 if (targetUserId == UserHandle.USER_OWNER) {
4952 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4953 forwardingResolveInfo.noResourceId = true;
4955 forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4956 forwardingResolveInfo.priority = 0;
4957 forwardingResolveInfo.preferredOrder = 0;
4958 forwardingResolveInfo.match = 0;
4959 forwardingResolveInfo.isDefault = true;
4960 forwardingResolveInfo.filter = filter;
4961 forwardingResolveInfo.targetUserId = targetUserId;
4962 return forwardingResolveInfo;
4966 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4967 Intent[] specifics, String[] specificTypes, Intent intent,
4968 String resolvedType, int flags, int userId) {
4969 if (!sUserManager.exists(userId)) return Collections.emptyList();
4970 enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4971 false, "query intent activity options");
4972 final String resultsAction = intent.getAction();
4974 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4975 | PackageManager.GET_RESOLVED_FILTER, userId);
4977 if (DEBUG_INTENT_MATCHING) {
4978 Log.v(TAG, "Query " + intent + ": " + results);
4981 int specificsPos = 0;
4984 // todo: note that the algorithm used here is O(N^2). This
4985 // isn't a problem in our current environment, but if we start running
4986 // into situations where we have more than 5 or 10 matches then this
4987 // should probably be changed to something smarter...
4989 // First we go through and resolve each of the specific items
4990 // that were supplied, taking care of removing any corresponding
4991 // duplicate items in the generic resolve list.
4992 if (specifics != null) {
4993 for (int i=0; i<specifics.length; i++) {
4994 final Intent sintent = specifics[i];
4995 if (sintent == null) {
4999 if (DEBUG_INTENT_MATCHING) {
5000 Log.v(TAG, "Specific #" + i + ": " + sintent);
5003 String action = sintent.getAction();
5004 if (resultsAction != null && resultsAction.equals(action)) {
5005 // If this action was explicitly requested, then don't
5006 // remove things that have it.
5010 ResolveInfo ri = null;
5011 ActivityInfo ai = null;
5013 ComponentName comp = sintent.getComponent();
5017 specificTypes != null ? specificTypes[i] : null,
5022 if (ri == mResolveInfo) {
5023 // ACK! Must do something better with this.
5025 ai = ri.activityInfo;
5026 comp = new ComponentName(ai.applicationInfo.packageName,
5029 ai = getActivityInfo(comp, flags, userId);
5035 // Look for any generic query activities that are duplicates
5036 // of this specific one, and remove them from the results.
5037 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5040 for (j=specificsPos; j<N; j++) {
5041 ResolveInfo sri = results.get(j);
5042 if ((sri.activityInfo.name.equals(comp.getClassName())
5043 && sri.activityInfo.applicationInfo.packageName.equals(
5044 comp.getPackageName()))
5045 || (action != null && sri.filter.matchAction(action))) {
5047 if (DEBUG_INTENT_MATCHING) Log.v(
5048 TAG, "Removing duplicate item from " + j
5049 + " due to specific " + specificsPos);
5058 // Add this specific item to its proper place.
5060 ri = new ResolveInfo();
5061 ri.activityInfo = ai;
5063 results.add(specificsPos, ri);
5064 ri.specificIndex = i;
5069 // Now we go through the remaining generic results and remove any
5070 // duplicate actions that are found here.
5072 for (int i=specificsPos; i<N-1; i++) {
5073 final ResolveInfo rii = results.get(i);
5074 if (rii.filter == null) {
5078 // Iterate over all of the actions of this result's intent
5079 // filter... typically this should be just one.
5080 final Iterator<String> it = rii.filter.actionsIterator();
5084 while (it.hasNext()) {
5085 final String action = it.next();
5086 if (resultsAction != null && resultsAction.equals(action)) {
5087 // If this action was explicitly requested, then don't
5088 // remove things that have it.
5091 for (int j=i+1; j<N; j++) {
5092 final ResolveInfo rij = results.get(j);
5093 if (rij.filter != null && rij.filter.hasAction(action)) {
5095 if (DEBUG_INTENT_MATCHING) Log.v(
5096 TAG, "Removing duplicate item from " + j
5097 + " due to action " + action + " at " + i);
5104 // If the caller didn't request filter information, drop it now
5105 // so we don't have to marshall/unmarshall it.
5106 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5111 // Filter out the caller activity if so requested.
5112 if (caller != null) {
5114 for (int i=0; i<N; i++) {
5115 ActivityInfo ainfo = results.get(i).activityInfo;
5116 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5117 && caller.getClassName().equals(ainfo.name)) {
5124 // If the caller didn't request filter information,
5125 // drop them now so we don't have to
5126 // marshall/unmarshall it.
5127 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5129 for (int i=0; i<N; i++) {
5130 results.get(i).filter = null;
5134 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5139 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5141 if (!sUserManager.exists(userId)) return Collections.emptyList();
5142 ComponentName comp = intent.getComponent();
5144 if (intent.getSelector() != null) {
5145 intent = intent.getSelector();
5146 comp = intent.getComponent();
5150 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5151 ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5153 ResolveInfo ri = new ResolveInfo();
5154 ri.activityInfo = ai;
5161 synchronized (mPackages) {
5162 String pkgName = intent.getPackage();
5163 if (pkgName == null) {
5164 return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5166 final PackageParser.Package pkg = mPackages.get(pkgName);
5168 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5176 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5177 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5178 if (!sUserManager.exists(userId)) return null;
5179 if (query != null) {
5180 if (query.size() >= 1) {
5181 // If there is more than one service with the same priority,
5182 // just arbitrarily pick the first one.
5183 return query.get(0);
5190 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5192 if (!sUserManager.exists(userId)) return Collections.emptyList();
5193 ComponentName comp = intent.getComponent();
5195 if (intent.getSelector() != null) {
5196 intent = intent.getSelector();
5197 comp = intent.getComponent();
5201 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5202 final ServiceInfo si = getServiceInfo(comp, flags, userId);
5204 final ResolveInfo ri = new ResolveInfo();
5205 ri.serviceInfo = si;
5212 synchronized (mPackages) {
5213 String pkgName = intent.getPackage();
5214 if (pkgName == null) {
5215 return mServices.queryIntent(intent, resolvedType, flags, userId);
5217 final PackageParser.Package pkg = mPackages.get(pkgName);
5219 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5227 public List<ResolveInfo> queryIntentContentProviders(
5228 Intent intent, String resolvedType, int flags, int userId) {
5229 if (!sUserManager.exists(userId)) return Collections.emptyList();
5230 ComponentName comp = intent.getComponent();
5232 if (intent.getSelector() != null) {
5233 intent = intent.getSelector();
5234 comp = intent.getComponent();
5238 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5239 final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5241 final ResolveInfo ri = new ResolveInfo();
5242 ri.providerInfo = pi;
5249 synchronized (mPackages) {
5250 String pkgName = intent.getPackage();
5251 if (pkgName == null) {
5252 return mProviders.queryIntent(intent, resolvedType, flags, userId);
5254 final PackageParser.Package pkg = mPackages.get(pkgName);
5256 return mProviders.queryIntentForPackage(
5257 intent, resolvedType, flags, pkg.providers, userId);
5264 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5265 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5267 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5270 synchronized (mPackages) {
5271 ArrayList<PackageInfo> list;
5272 if (listUninstalled) {
5273 list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5274 for (PackageSetting ps : mSettings.mPackages.values()) {
5276 if (ps.pkg != null) {
5277 pi = generatePackageInfo(ps.pkg, flags, userId);
5279 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5286 list = new ArrayList<PackageInfo>(mPackages.size());
5287 for (PackageParser.Package p : mPackages.values()) {
5288 PackageInfo pi = generatePackageInfo(p, flags, userId);
5295 return new ParceledListSlice<PackageInfo>(list);
5299 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5300 String[] permissions, boolean[] tmp, int flags, int userId) {
5302 final PermissionsState permissionsState = ps.getPermissionsState();
5303 for (int i=0; i<permissions.length; i++) {
5304 final String permission = permissions[i];
5305 if (permissionsState.hasPermission(permission, userId)) {
5312 if (numMatch == 0) {
5316 if (ps.pkg != null) {
5317 pi = generatePackageInfo(ps.pkg, flags, userId);
5319 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5321 // The above might return null in cases of uninstalled apps or install-state
5322 // skew across users/profiles.
5324 if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5325 if (numMatch == permissions.length) {
5326 pi.requestedPermissions = permissions;
5328 pi.requestedPermissions = new String[numMatch];
5330 for (int i=0; i<permissions.length; i++) {
5332 pi.requestedPermissions[numMatch] = permissions[i];
5343 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5344 String[] permissions, int flags, int userId) {
5345 if (!sUserManager.exists(userId)) return null;
5346 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5349 synchronized (mPackages) {
5350 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5351 boolean[] tmpBools = new boolean[permissions.length];
5352 if (listUninstalled) {
5353 for (PackageSetting ps : mSettings.mPackages.values()) {
5354 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5357 for (PackageParser.Package pkg : mPackages.values()) {
5358 PackageSetting ps = (PackageSetting)pkg.mExtras;
5360 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5366 return new ParceledListSlice<PackageInfo>(list);
5371 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5372 if (!sUserManager.exists(userId)) return null;
5373 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5376 synchronized (mPackages) {
5377 ArrayList<ApplicationInfo> list;
5378 if (listUninstalled) {
5379 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5380 for (PackageSetting ps : mSettings.mPackages.values()) {
5382 if (ps.pkg != null) {
5383 ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5384 ps.readUserState(userId), userId);
5386 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5393 list = new ArrayList<ApplicationInfo>(mPackages.size());
5394 for (PackageParser.Package p : mPackages.values()) {
5395 if (p.mExtras != null) {
5396 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5397 ((PackageSetting)p.mExtras).readUserState(userId), userId);
5405 return new ParceledListSlice<ApplicationInfo>(list);
5409 public List<ApplicationInfo> getPersistentApplications(int flags) {
5410 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5413 synchronized (mPackages) {
5414 final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5415 final int userId = UserHandle.getCallingUserId();
5416 while (i.hasNext()) {
5417 final PackageParser.Package p = i.next();
5418 if (p.applicationInfo != null
5419 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5420 && (!mSafeMode || isSystemApp(p))) {
5421 PackageSetting ps = mSettings.mPackages.get(p.packageName);
5423 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5424 ps.readUserState(userId), userId);
5437 public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5438 if (!sUserManager.exists(userId)) return null;
5440 synchronized (mPackages) {
5441 final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5442 PackageSetting ps = provider != null
5443 ? mSettings.mPackages.get(provider.owner.packageName)
5446 && mSettings.isEnabledLPr(provider.info, flags, userId)
5447 && (!mSafeMode || (provider.info.applicationInfo.flags
5448 &ApplicationInfo.FLAG_SYSTEM) != 0)
5449 ? PackageParser.generateProviderInfo(provider, flags,
5450 ps.readUserState(userId), userId)
5459 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5461 synchronized (mPackages) {
5462 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5463 .entrySet().iterator();
5464 final int userId = UserHandle.getCallingUserId();
5465 while (i.hasNext()) {
5466 Map.Entry<String, PackageParser.Provider> entry = i.next();
5467 PackageParser.Provider p = entry.getValue();
5468 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5470 if (ps != null && p.syncable
5471 && (!mSafeMode || (p.info.applicationInfo.flags
5472 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5473 ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5474 ps.readUserState(userId), userId);
5476 outNames.add(entry.getKey());
5485 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5486 int uid, int flags) {
5487 ArrayList<ProviderInfo> finalList = null;
5489 synchronized (mPackages) {
5490 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5491 final int userId = processName != null ?
5492 UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5493 while (i.hasNext()) {
5494 final PackageParser.Provider p = i.next();
5495 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5496 if (ps != null && p.info.authority != null
5497 && (processName == null
5498 || (p.info.processName.equals(processName)
5499 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5500 && mSettings.isEnabledLPr(p.info, flags, userId)
5502 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5503 if (finalList == null) {
5504 finalList = new ArrayList<ProviderInfo>(3);
5506 ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5507 ps.readUserState(userId), userId);
5509 finalList.add(info);
5515 if (finalList != null) {
5516 Collections.sort(finalList, mProviderInitOrderSorter);
5517 return new ParceledListSlice<ProviderInfo>(finalList);
5524 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5527 synchronized (mPackages) {
5528 final PackageParser.Instrumentation i = mInstrumentation.get(name);
5529 return PackageParser.generateInstrumentationInfo(i, flags);
5534 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5536 ArrayList<InstrumentationInfo> finalList =
5537 new ArrayList<InstrumentationInfo>();
5540 synchronized (mPackages) {
5541 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5542 while (i.hasNext()) {
5543 final PackageParser.Instrumentation p = i.next();
5544 if (targetPackage == null
5545 || targetPackage.equals(p.info.targetPackage)) {
5546 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5558 private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5559 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5560 if (overlays == null) {
5561 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5564 for (PackageParser.Package opkg : overlays.values()) {
5565 // Not much to do if idmap fails: we already logged the error
5566 // and we certainly don't want to abort installation of pkg simply
5567 // because an overlay didn't fit properly. For these reasons,
5568 // ignore the return value of createIdmapForPackagePairLI.
5569 createIdmapForPackagePairLI(pkg, opkg);
5573 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5574 PackageParser.Package opkg) {
5575 if (!opkg.mTrustedOverlay) {
5576 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5577 opkg.baseCodePath + ": overlay not trusted");
5580 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5581 if (overlaySet == null) {
5582 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5583 opkg.baseCodePath + " but target package has no known overlays");
5586 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5587 // TODO: generate idmap for split APKs
5588 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5589 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5590 + opkg.baseCodePath);
5593 PackageParser.Package[] overlayArray =
5594 overlaySet.values().toArray(new PackageParser.Package[0]);
5595 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5596 public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5597 return p1.mOverlayPriority - p2.mOverlayPriority;
5600 Arrays.sort(overlayArray, cmp);
5602 pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5604 for (PackageParser.Package p : overlayArray) {
5605 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5610 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5611 final File[] files = dir.listFiles();
5612 if (ArrayUtils.isEmpty(files)) {
5613 Log.d(TAG, "No files in app dir " + dir);
5617 if (DEBUG_PACKAGE_SCANNING) {
5618 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5619 + " flags=0x" + Integer.toHexString(parseFlags));
5622 for (File file : files) {
5623 final boolean isPackage = (isApkFile(file) || file.isDirectory())
5624 && !PackageInstallerService.isStageName(file.getName());
5626 // Ignore entries which are not packages
5630 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5631 scanFlags, currentTime, null);
5632 } catch (PackageManagerException e) {
5633 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5635 // Delete invalid userdata apps
5636 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5637 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5638 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5639 if (file.isDirectory()) {
5640 mInstaller.rmPackageDir(file.getAbsolutePath());
5649 private static File getSettingsProblemFile() {
5650 File dataDir = Environment.getDataDirectory();
5651 File systemDir = new File(dataDir, "system");
5652 File fname = new File(systemDir, "uiderrors.txt");
5656 static void reportSettingsProblem(int priority, String msg) {
5657 logCriticalInfo(priority, msg);
5660 static void logCriticalInfo(int priority, String msg) {
5661 Slog.println(priority, TAG, msg);
5662 EventLogTags.writePmCriticalInfo(msg);
5664 File fname = getSettingsProblemFile();
5665 FileOutputStream out = new FileOutputStream(fname, true);
5666 PrintWriter pw = new FastPrintWriter(out);
5667 SimpleDateFormat formatter = new SimpleDateFormat();
5668 String dateString = formatter.format(new Date(System.currentTimeMillis()));
5669 pw.println(dateString + ": " + msg);
5671 FileUtils.setPermissions(
5673 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5675 } catch (java.io.IOException e) {
5679 private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5680 PackageParser.Package pkg, File srcFile, int parseFlags)
5681 throws PackageManagerException {
5683 && ps.codePath.equals(srcFile)
5684 && ps.timeStamp == srcFile.lastModified()
5685 && !isCompatSignatureUpdateNeeded(pkg)
5686 && !isRecoverSignatureUpdateNeeded(pkg)) {
5687 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5688 KeySetManagerService ksms = mSettings.mKeySetManagerService;
5689 ArraySet<PublicKey> signingKs;
5690 synchronized (mPackages) {
5691 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5693 if (ps.signatures.mSignatures != null
5694 && ps.signatures.mSignatures.length != 0
5695 && signingKs != null) {
5696 // Optimization: reuse the existing cached certificates
5697 // if the package appears to be unchanged.
5698 pkg.mSignatures = ps.signatures.mSignatures;
5699 pkg.mSigningKeys = signingKs;
5703 Slog.w(TAG, "PackageSetting for " + ps.name
5704 + " is missing signatures. Collecting certs again to recover them.");
5706 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5710 pp.collectCertificates(pkg, parseFlags);
5711 pp.collectManifestDigest(pkg);
5712 } catch (PackageParserException e) {
5713 throw PackageManagerException.from(e);
5718 * Scan a package and return the newly parsed package.
5719 * Returns null in case of errors and the error code is stored in mLastScanError
5721 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5722 long currentTime, UserHandle user) throws PackageManagerException {
5723 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5724 parseFlags |= mDefParseFlags;
5725 PackageParser pp = new PackageParser();
5726 pp.setSeparateProcesses(mSeparateProcesses);
5727 pp.setOnlyCoreApps(mOnlyCore);
5728 pp.setDisplayMetrics(mMetrics);
5730 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5731 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5734 final PackageParser.Package pkg;
5736 pkg = pp.parsePackage(scanFile, parseFlags);
5737 } catch (PackageParserException e) {
5738 throw PackageManagerException.from(e);
5741 PackageSetting ps = null;
5742 PackageSetting updatedPkg;
5744 synchronized (mPackages) {
5745 // Look to see if we already know about this package.
5746 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5747 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5748 // This package has been renamed to its original name. Let's
5750 ps = mSettings.peekPackageLPr(oldName);
5752 // If there was no original package, see one for the real package name.
5754 ps = mSettings.peekPackageLPr(pkg.packageName);
5756 // Check to see if this package could be hiding/updating a system
5757 // package. Must look for it either under the original or real
5758 // package name depending on our state.
5759 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5760 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5762 boolean updatedPkgBetter = false;
5763 // First check if this is a system package that may involve an update
5764 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5765 // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5766 // it needs to drop FLAG_PRIVILEGED.
5767 if (locationIsPrivileged(scanFile)) {
5768 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5770 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5773 if (ps != null && !ps.codePath.equals(scanFile)) {
5774 // The path has changed from what was last scanned... check the
5775 // version of the new path against what we have stored to determine
5777 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5778 if (pkg.mVersionCode <= ps.versionCode) {
5779 // The system package has been updated and the code path does not match
5780 // Ignore entry. Skip it.
5781 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5782 + " ignored: updated version " + ps.versionCode
5783 + " better than this " + pkg.mVersionCode);
5784 if (!updatedPkg.codePath.equals(scanFile)) {
5785 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5786 + ps.name + " changing from " + updatedPkg.codePathString
5787 + " to " + scanFile);
5788 updatedPkg.codePath = scanFile;
5789 updatedPkg.codePathString = scanFile.toString();
5790 updatedPkg.resourcePath = scanFile;
5791 updatedPkg.resourcePathString = scanFile.toString();
5793 updatedPkg.pkg = pkg;
5794 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5795 "Package " + ps.name + " at " + scanFile
5796 + " ignored: updated version " + ps.versionCode
5797 + " better than this " + pkg.mVersionCode);
5799 // The current app on the system partition is better than
5800 // what we have updated to on the data partition; switch
5801 // back to the system partition version.
5802 // At this point, its safely assumed that package installation for
5803 // apps in system partition will go through. If not there won't be a working
5804 // version of the app
5806 synchronized (mPackages) {
5807 // Just remove the loaded entries from package lists.
5808 mPackages.remove(ps.name);
5811 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5812 + " reverting from " + ps.codePathString
5813 + ": new version " + pkg.mVersionCode
5814 + " better than installed " + ps.versionCode);
5816 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5817 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5818 synchronized (mInstallLock) {
5819 args.cleanUpResourcesLI();
5821 synchronized (mPackages) {
5822 mSettings.enableSystemPackageLPw(ps.name);
5824 updatedPkgBetter = true;
5829 if (updatedPkg != null) {
5830 // An updated system app will not have the PARSE_IS_SYSTEM flag set
5832 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5834 // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5835 // flag set initially
5836 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5837 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5841 // Verify certificates against what was last scanned
5842 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5845 * A new system app appeared, but we already had a non-system one of the
5846 * same name installed earlier.
5848 boolean shouldHideSystemApp = false;
5849 if (updatedPkg == null && ps != null
5850 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5852 * Check to make sure the signatures match first. If they don't,
5853 * wipe the installed application and its data.
5855 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5856 != PackageManager.SIGNATURE_MATCH) {
5857 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5858 + " signatures don't match existing userdata copy; removing");
5859 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5863 * If the newly-added system app is an older version than the
5864 * already installed version, hide it. It will be scanned later
5865 * and re-added like an update.
5867 if (pkg.mVersionCode <= ps.versionCode) {
5868 shouldHideSystemApp = true;
5869 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5870 + " but new version " + pkg.mVersionCode + " better than installed "
5871 + ps.versionCode + "; hiding system");
5874 * The newly found system app is a newer version that the
5875 * one previously installed. Simply remove the
5876 * already-installed application and replace it with our own
5877 * while keeping the application data.
5879 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5880 + " reverting from " + ps.codePathString + ": new version "
5881 + pkg.mVersionCode + " better than installed " + ps.versionCode);
5882 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5883 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5884 synchronized (mInstallLock) {
5885 args.cleanUpResourcesLI();
5891 // The apk is forward locked (not public) if its code and resources
5892 // are kept in different files. (except for app in either system or
5894 // TODO grab this value from PackageSettings
5895 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5896 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5897 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5901 // TODO: extend to support forward-locked splits
5902 String resourcePath = null;
5903 String baseResourcePath = null;
5904 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5905 if (ps != null && ps.resourcePathString != null) {
5906 resourcePath = ps.resourcePathString;
5907 baseResourcePath = ps.resourcePathString;
5909 // Should not happen at all. Just log an error.
5910 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5913 resourcePath = pkg.codePath;
5914 baseResourcePath = pkg.baseCodePath;
5917 // Set application objects path explicitly.
5918 pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5919 pkg.applicationInfo.setCodePath(pkg.codePath);
5920 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5921 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5922 pkg.applicationInfo.setResourcePath(resourcePath);
5923 pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5924 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5926 // Note that we invoke the following method only if we are about to unpack an application
5927 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5928 | SCAN_UPDATE_SIGNATURE, currentTime, user);
5931 * If the system app should be overridden by a previously installed
5932 * data, hide the system app now and let the /data/app scan pick it up
5935 if (shouldHideSystemApp) {
5936 synchronized (mPackages) {
5937 mSettings.disableSystemPackageLPw(pkg.packageName);
5944 private static String fixProcessName(String defProcessName,
5945 String processName, int uid) {
5946 if (processName == null) {
5947 return defProcessName;
5952 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5953 throws PackageManagerException {
5954 if (pkgSetting.signatures.mSignatures != null) {
5955 // Already existing package. Make sure signatures match
5956 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5957 == PackageManager.SIGNATURE_MATCH;
5959 match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5960 == PackageManager.SIGNATURE_MATCH;
5963 match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5964 == PackageManager.SIGNATURE_MATCH;
5967 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5968 + pkg.packageName + " signatures do not match the "
5969 + "previously installed version; ignoring!");
5973 // Check for shared user signatures
5974 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5975 // Already existing package. Make sure signatures match
5976 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5977 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5979 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5980 == PackageManager.SIGNATURE_MATCH;
5983 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5984 == PackageManager.SIGNATURE_MATCH;
5987 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5988 "Package " + pkg.packageName
5989 + " has no signatures that match those in shared user "
5990 + pkgSetting.sharedUser.name + "; ignoring!");
5996 * Enforces that only the system UID or root's UID can call a method exposed
5999 * @param message used as message if SecurityException is thrown
6000 * @throws SecurityException if the caller is not system or root
6002 private static final void enforceSystemOrRoot(String message) {
6003 final int uid = Binder.getCallingUid();
6004 if (uid != Process.SYSTEM_UID && uid != 0) {
6005 throw new SecurityException(message);
6010 public void performBootDexOpt() {
6011 enforceSystemOrRoot("Only the system can request dexopt be performed");
6013 // Before everything else, see whether we need to fstrim.
6015 IMountService ms = PackageHelper.getMountService();
6017 final boolean isUpgrade = isUpgrade();
6018 boolean doTrim = isUpgrade;
6020 Slog.w(TAG, "Running disk maintenance immediately due to system update");
6022 final long interval = android.provider.Settings.Global.getLong(
6023 mContext.getContentResolver(),
6024 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6025 DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6027 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6028 if (timeSinceLast > interval) {
6030 Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6031 + "; running immediately");
6036 if (!isFirstBoot()) {
6038 ActivityManagerNative.getDefault().showBootMessage(
6039 mContext.getResources().getString(
6040 R.string.android_upgrading_fstrim), true);
6041 } catch (RemoteException e) {
6044 ms.runMaintenance();
6047 Slog.e(TAG, "Mount service unavailable!");
6049 } catch (RemoteException e) {
6050 // Can't happen; MountService is local
6053 final ArraySet<PackageParser.Package> pkgs;
6054 synchronized (mPackages) {
6055 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6059 // Sort apps by importance for dexopt ordering. Important apps are given more priority
6060 // in case the device runs out of space.
6061 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6062 // Give priority to core apps.
6063 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6064 PackageParser.Package pkg = it.next();
6067 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6069 sortedPkgs.add(pkg);
6073 // Give priority to system apps that listen for pre boot complete.
6074 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6075 ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6076 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6077 PackageParser.Package pkg = it.next();
6078 if (pkgNames.contains(pkg.packageName)) {
6080 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6082 sortedPkgs.add(pkg);
6086 // Give priority to system apps.
6087 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6088 PackageParser.Package pkg = it.next();
6089 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6091 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6093 sortedPkgs.add(pkg);
6097 // Give priority to updated system apps.
6098 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6099 PackageParser.Package pkg = it.next();
6100 if (pkg.isUpdatedSystemApp()) {
6102 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6104 sortedPkgs.add(pkg);
6108 // Give priority to apps that listen for boot complete.
6109 intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6110 pkgNames = getPackageNamesForIntent(intent);
6111 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6112 PackageParser.Package pkg = it.next();
6113 if (pkgNames.contains(pkg.packageName)) {
6115 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6117 sortedPkgs.add(pkg);
6121 // Filter out packages that aren't recently used.
6122 filterRecentlyUsedApps(pkgs);
6123 // Add all remaining apps.
6124 for (PackageParser.Package pkg : pkgs) {
6126 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6128 sortedPkgs.add(pkg);
6131 // If we want to be lazy, filter everything that wasn't recently used.
6133 filterRecentlyUsedApps(sortedPkgs);
6137 int total = sortedPkgs.size();
6138 File dataDir = Environment.getDataDirectory();
6139 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6140 if (lowThreshold == 0) {
6141 throw new IllegalStateException("Invalid low memory threshold");
6143 for (PackageParser.Package pkg : sortedPkgs) {
6144 long usableSpace = dataDir.getUsableSpace();
6145 if (usableSpace < lowThreshold) {
6146 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6149 performBootDexOpt(pkg, ++i, total);
6154 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6155 // Filter out packages that aren't recently used.
6157 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6158 // should do a full dexopt.
6159 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6160 int total = pkgs.size();
6162 long now = System.currentTimeMillis();
6163 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6164 PackageParser.Package pkg = i.next();
6165 long then = pkg.mLastPackageUsageTimeInMills;
6166 if (then + mDexOptLRUThresholdInMills < now) {
6168 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6169 ((then == 0) ? "never" : new Date(then)));
6176 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6181 private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6182 List<ResolveInfo> ris = null;
6184 ris = AppGlobals.getPackageManager().queryIntentReceivers(
6185 intent, null, 0, UserHandle.USER_OWNER);
6186 } catch (RemoteException e) {
6188 ArraySet<String> pkgNames = new ArraySet<String>();
6190 for (ResolveInfo ri : ris) {
6191 pkgNames.add(ri.activityInfo.packageName);
6197 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6199 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6201 if (!isFirstBoot()) {
6203 ActivityManagerNative.getDefault().showBootMessage(
6204 mContext.getResources().getString(R.string.android_upgrading_apk,
6205 curr, total), true);
6206 } catch (RemoteException e) {
6209 PackageParser.Package p = pkg;
6210 synchronized (mInstallLock) {
6211 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6212 false /* force dex */, false /* defer */, true /* include dependencies */);
6217 public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6218 return performDexOpt(packageName, instructionSet, false);
6221 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6222 boolean dexopt = mLazyDexOpt || backgroundDexopt;
6223 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt
6224 if (!dexopt && !updateUsage) {
6225 // We aren't going to dexopt or update usage, so bail early.
6228 PackageParser.Package p;
6229 final String targetInstructionSet;
6230 synchronized (mPackages) {
6231 p = mPackages.get(packageName);
6236 p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6238 mPackageUsage.write(false);
6240 // We aren't going to dexopt, so bail early.
6244 targetInstructionSet = instructionSet != null ? instructionSet :
6245 getPrimaryInstructionSet(p.applicationInfo);
6246 if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6250 long callingId = Binder.clearCallingIdentity();
6252 synchronized (mInstallLock) {
6253 final String[] instructionSets = new String[] { targetInstructionSet };
6254 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6255 false /* forceDex */, false /* defer */, true /* inclDependencies */);
6256 return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6259 Binder.restoreCallingIdentity(callingId);
6263 public ArraySet<String> getPackagesThatNeedDexOpt() {
6264 ArraySet<String> pkgs = null;
6265 synchronized (mPackages) {
6266 for (PackageParser.Package p : mPackages.values()) {
6268 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6270 if (!p.mDexOptPerformed.isEmpty()) {
6274 pkgs = new ArraySet<String>();
6276 pkgs.add(p.packageName);
6282 public void shutdown() {
6283 mPackageUsage.write(true);
6287 public void forceDexOpt(String packageName) {
6288 enforceSystemOrRoot("forceDexOpt");
6290 PackageParser.Package pkg;
6291 synchronized (mPackages) {
6292 pkg = mPackages.get(packageName);
6294 throw new IllegalArgumentException("Missing package: " + packageName);
6298 synchronized (mInstallLock) {
6299 final String[] instructionSets = new String[] {
6300 getPrimaryInstructionSet(pkg.applicationInfo) };
6301 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6302 true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6303 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6304 throw new IllegalStateException("Failed to dexopt: " + res);
6309 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6310 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6311 Slog.w(TAG, "Unable to update from " + oldPkg.name
6312 + " to " + newPkg.packageName
6313 + ": old package not in system partition");
6315 } else if (mPackages.get(oldPkg.name) != null) {
6316 Slog.w(TAG, "Unable to update from " + oldPkg.name
6317 + " to " + newPkg.packageName
6318 + ": old package still exists");
6324 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6325 int[] users = sUserManager.getUserIds();
6326 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6330 for (int user : users) {
6332 res = mInstaller.createUserData(volumeUuid, packageName,
6333 UserHandle.getUid(user, uid), user, seinfo);
6342 private int removeDataDirsLI(String volumeUuid, String packageName) {
6343 int[] users = sUserManager.getUserIds();
6345 for (int user : users) {
6346 int resInner = mInstaller.remove(volumeUuid, packageName, user);
6355 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6356 int[] users = sUserManager.getUserIds();
6358 for (int user : users) {
6359 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6367 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6368 PackageParser.Package changingLib) {
6369 if (file.path != null) {
6370 usesLibraryFiles.add(file.path);
6373 PackageParser.Package p = mPackages.get(file.apk);
6374 if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6375 // If we are doing this while in the middle of updating a library apk,
6376 // then we need to make sure to use that new apk for determining the
6377 // dependencies here. (We haven't yet finished committing the new apk
6378 // to the package manager state.)
6379 if (p == null || p.packageName.equals(changingLib.packageName)) {
6384 usesLibraryFiles.addAll(p.getAllCodePaths());
6388 private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6389 PackageParser.Package changingLib) throws PackageManagerException {
6390 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6391 final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6392 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6393 for (int i=0; i<N; i++) {
6394 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6396 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6397 "Package " + pkg.packageName + " requires unavailable shared library "
6398 + pkg.usesLibraries.get(i) + "; failing!");
6400 addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6402 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6403 for (int i=0; i<N; i++) {
6404 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6406 Slog.w(TAG, "Package " + pkg.packageName
6407 + " desires unavailable shared library "
6408 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6410 addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6413 N = usesLibraryFiles.size();
6415 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6417 pkg.usesLibraryFiles = null;
6422 private static boolean hasString(List<String> list, List<String> which) {
6426 for (int i=list.size()-1; i>=0; i--) {
6427 for (int j=which.size()-1; j>=0; j--) {
6428 if (which.get(j).equals(list.get(i))) {
6436 private void updateAllSharedLibrariesLPw() {
6437 for (PackageParser.Package pkg : mPackages.values()) {
6439 updateSharedLibrariesLPw(pkg, null);
6440 } catch (PackageManagerException e) {
6441 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6446 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6447 PackageParser.Package changingPkg) {
6448 ArrayList<PackageParser.Package> res = null;
6449 for (PackageParser.Package pkg : mPackages.values()) {
6450 if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6451 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6453 res = new ArrayList<PackageParser.Package>();
6457 updateSharedLibrariesLPw(pkg, changingPkg);
6458 } catch (PackageManagerException e) {
6459 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6467 * Derive the value of the {@code cpuAbiOverride} based on the provided
6468 * value and an optional stored value from the package settings.
6470 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6471 String cpuAbiOverride = null;
6473 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6474 cpuAbiOverride = null;
6475 } else if (abiOverride != null) {
6476 cpuAbiOverride = abiOverride;
6477 } else if (settings != null) {
6478 cpuAbiOverride = settings.cpuAbiOverrideString;
6481 return cpuAbiOverride;
6484 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6485 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6486 boolean success = false;
6488 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6493 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6494 removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6499 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6500 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6501 final File scanFile = new File(pkg.codePath);
6502 if (pkg.applicationInfo.getCodePath() == null ||
6503 pkg.applicationInfo.getResourcePath() == null) {
6504 // Bail out. The resource and code paths haven't been set.
6505 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6506 "Code and resource paths haven't been set correctly");
6509 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6510 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6512 // Only allow system apps to be flagged as core apps.
6513 pkg.coreApp = false;
6516 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6517 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6520 if (mCustomResolverComponentName != null &&
6521 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6522 setUpCustomResolverActivity(pkg);
6525 if (pkg.packageName.equals("android")) {
6526 synchronized (mPackages) {
6527 if (mAndroidApplication != null) {
6528 Slog.w(TAG, "*************************************************");
6529 Slog.w(TAG, "Core android package being redefined. Skipping.");
6530 Slog.w(TAG, " file=" + scanFile);
6531 Slog.w(TAG, "*************************************************");
6532 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6533 "Core android package being redefined. Skipping.");
6536 // Set up information for our fall-back user intent resolution activity.
6537 mPlatformPackage = pkg;
6538 pkg.mVersionCode = mSdkVersion;
6539 mAndroidApplication = pkg.applicationInfo;
6541 if (!mResolverReplaced) {
6542 mResolveActivity.applicationInfo = mAndroidApplication;
6543 mResolveActivity.name = ResolverActivity.class.getName();
6544 mResolveActivity.packageName = mAndroidApplication.packageName;
6545 mResolveActivity.processName = "system:ui";
6546 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6547 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6548 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6549 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6550 mResolveActivity.exported = true;
6551 mResolveActivity.enabled = true;
6552 mResolveInfo.activityInfo = mResolveActivity;
6553 mResolveInfo.priority = 0;
6554 mResolveInfo.preferredOrder = 0;
6555 mResolveInfo.match = 0;
6556 mResolveComponentName = new ComponentName(
6557 mAndroidApplication.packageName, mResolveActivity.name);
6562 if (DEBUG_PACKAGE_SCANNING) {
6563 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6564 Log.d(TAG, "Scanning package " + pkg.packageName);
6567 if (mPackages.containsKey(pkg.packageName)
6568 || mSharedLibraries.containsKey(pkg.packageName)) {
6569 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6570 "Application package " + pkg.packageName
6571 + " already installed. Skipping duplicate.");
6574 // If we're only installing presumed-existing packages, require that the
6575 // scanned APK is both already known and at the path previously established
6576 // for it. Previously unknown packages we pick up normally, but if we have an
6577 // a priori expectation about this package's install presence, enforce it.
6578 // With a singular exception for new system packages. When an OTA contains
6579 // a new system package, we allow the codepath to change from a system location
6580 // to the user-installed location. If we don't allow this change, any newer,
6581 // user-installed version of the application will be ignored.
6582 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6583 if (mExpectingBetter.containsKey(pkg.packageName)) {
6584 logCriticalInfo(Log.WARN,
6585 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6587 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6588 if (known != null) {
6589 if (DEBUG_PACKAGE_SCANNING) {
6590 Log.d(TAG, "Examining " + pkg.codePath
6591 + " and requiring known paths " + known.codePathString
6592 + " & " + known.resourcePathString);
6594 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6595 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6596 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6597 "Application package " + pkg.packageName
6598 + " found at " + pkg.applicationInfo.getCodePath()
6599 + " but expected at " + known.codePathString + "; ignoring.");
6605 // Initialize package source and resource directories
6606 File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6607 File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6609 SharedUserSetting suid = null;
6610 PackageSetting pkgSetting = null;
6612 if (!isSystemApp(pkg)) {
6613 // Only system apps can use these features.
6614 pkg.mOriginalPackages = null;
6615 pkg.mRealPackage = null;
6616 pkg.mAdoptPermissions = null;
6620 synchronized (mPackages) {
6621 if (pkg.mSharedUserId != null) {
6622 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6624 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6625 "Creating application package " + pkg.packageName
6626 + " for shared user failed");
6628 if (DEBUG_PACKAGE_SCANNING) {
6629 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6630 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6631 + "): packages=" + suid.packages);
6635 // Check if we are renaming from an original package name.
6636 PackageSetting origPackage = null;
6637 String realName = null;
6638 if (pkg.mOriginalPackages != null) {
6639 // This package may need to be renamed to a previously
6640 // installed name. Let's check on that...
6641 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6642 if (pkg.mOriginalPackages.contains(renamed)) {
6643 // This package had originally been installed as the
6644 // original name, and we have already taken care of
6645 // transitioning to the new one. Just update the new
6646 // one to continue using the old name.
6647 realName = pkg.mRealPackage;
6648 if (!pkg.packageName.equals(renamed)) {
6649 // Callers into this function may have already taken
6650 // care of renaming the package; only do it here if
6651 // it is not already done.
6652 pkg.setPackageName(renamed);
6656 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6657 if ((origPackage = mSettings.peekPackageLPr(
6658 pkg.mOriginalPackages.get(i))) != null) {
6659 // We do have the package already installed under its
6660 // original name... should we use it?
6661 if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6662 // New package is not compatible with original.
6665 } else if (origPackage.sharedUser != null) {
6666 // Make sure uid is compatible between packages.
6667 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6668 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6669 + " to " + pkg.packageName + ": old uid "
6670 + origPackage.sharedUser.name
6671 + " differs from " + pkg.mSharedUserId);
6676 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6677 + pkg.packageName + " to old name " + origPackage.name);
6685 if (mTransferedPackages.contains(pkg.packageName)) {
6686 Slog.w(TAG, "Package " + pkg.packageName
6687 + " was transferred to another, but its .apk remains");
6690 // Just create the setting, don't add it yet. For already existing packages
6691 // the PkgSetting exists already and doesn't have to be created.
6692 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6693 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6694 pkg.applicationInfo.primaryCpuAbi,
6695 pkg.applicationInfo.secondaryCpuAbi,
6696 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6698 if (pkgSetting == null) {
6699 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6700 "Creating application package " + pkg.packageName + " failed");
6703 if (pkgSetting.origPackage != null) {
6704 // If we are first transitioning from an original package,
6705 // fix up the new package's name now. We need to do this after
6706 // looking up the package under its new name, so getPackageLP
6707 // can take care of fiddling things correctly.
6708 pkg.setPackageName(origPackage.name);
6710 // File a report about this.
6711 String msg = "New package " + pkgSetting.realName
6712 + " renamed to replace old package " + pkgSetting.name;
6713 reportSettingsProblem(Log.WARN, msg);
6715 // Make a note of it.
6716 mTransferedPackages.add(origPackage.name);
6718 // No longer need to retain this.
6719 pkgSetting.origPackage = null;
6722 if (realName != null) {
6723 // Make a note of it.
6724 mTransferedPackages.add(pkg.packageName);
6727 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6728 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6731 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6732 // Check all shared libraries and map to their actual file path.
6733 // We only do this here for apps not on a system dir, because those
6734 // are the only ones that can fail an install due to this. We
6735 // will take care of the system apps by updating all of their
6736 // library paths after the scan is done.
6737 updateSharedLibrariesLPw(pkg, null);
6740 if (mFoundPolicyFile) {
6741 SELinuxMMAC.assignSeinfoValue(pkg);
6744 pkg.applicationInfo.uid = pkgSetting.appId;
6745 pkg.mExtras = pkgSetting;
6746 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6747 if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6748 // We just determined the app is signed correctly, so bring
6749 // over the latest parsed certs.
6750 pkgSetting.signatures.mSignatures = pkg.mSignatures;
6752 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6753 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6754 "Package " + pkg.packageName + " upgrade keys do not match the "
6755 + "previously installed version");
6757 pkgSetting.signatures.mSignatures = pkg.mSignatures;
6758 String msg = "System package " + pkg.packageName
6759 + " signature changed; retaining data.";
6760 reportSettingsProblem(Log.WARN, msg);
6765 verifySignaturesLP(pkgSetting, pkg);
6766 // We just determined the app is signed correctly, so bring
6767 // over the latest parsed certs.
6768 pkgSetting.signatures.mSignatures = pkg.mSignatures;
6769 } catch (PackageManagerException e) {
6770 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6773 // The signature has changed, but this package is in the system
6774 // image... let's recover!
6775 pkgSetting.signatures.mSignatures = pkg.mSignatures;
6776 // However... if this package is part of a shared user, but it
6777 // doesn't match the signature of the shared user, let's fail.
6778 // What this means is that you can't change the signatures
6779 // associated with an overall shared user, which doesn't seem all
6780 // that unreasonable.
6781 if (pkgSetting.sharedUser != null) {
6782 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6783 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6784 throw new PackageManagerException(
6785 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6786 "Signature mismatch for shared user : "
6787 + pkgSetting.sharedUser);
6790 // File a report about this.
6791 String msg = "System package " + pkg.packageName
6792 + " signature changed; retaining data.";
6793 reportSettingsProblem(Log.WARN, msg);
6796 // Verify that this new package doesn't have any content providers
6797 // that conflict with existing packages. Only do this if the
6798 // package isn't already installed, since we don't want to break
6799 // things that are installed.
6800 if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6801 final int N = pkg.providers.size();
6803 for (i=0; i<N; i++) {
6804 PackageParser.Provider p = pkg.providers.get(i);
6805 if (p.info.authority != null) {
6806 String names[] = p.info.authority.split(";");
6807 for (int j = 0; j < names.length; j++) {
6808 if (mProvidersByAuthority.containsKey(names[j])) {
6809 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6810 final String otherPackageName =
6811 ((other != null && other.getComponentName() != null) ?
6812 other.getComponentName().getPackageName() : "?");
6813 throw new PackageManagerException(
6814 INSTALL_FAILED_CONFLICTING_PROVIDER,
6815 "Can't install because provider name " + names[j]
6816 + " (in package " + pkg.applicationInfo.packageName
6817 + ") is already used by " + otherPackageName);
6824 if (pkg.mAdoptPermissions != null) {
6825 // This package wants to adopt ownership of permissions from
6827 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6828 final String origName = pkg.mAdoptPermissions.get(i);
6829 final PackageSetting orig = mSettings.peekPackageLPr(origName);
6831 if (verifyPackageUpdateLPr(orig, pkg)) {
6832 Slog.i(TAG, "Adopting permissions from " + origName + " to "
6834 mSettings.transferPermissionsLPw(origName, pkg.packageName);
6841 final String pkgName = pkg.packageName;
6843 final long scanFileTime = scanFile.lastModified();
6844 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6845 pkg.applicationInfo.processName = fixProcessName(
6846 pkg.applicationInfo.packageName,
6847 pkg.applicationInfo.processName,
6848 pkg.applicationInfo.uid);
6851 if (mPlatformPackage == pkg) {
6852 // The system package is special.
6853 dataPath = new File(Environment.getDataDirectory(), "system");
6855 pkg.applicationInfo.dataDir = dataPath.getPath();
6858 // This is a normal package, need to make its data directory.
6859 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6860 UserHandle.USER_OWNER, pkg.packageName);
6862 boolean uidError = false;
6863 if (dataPath.exists()) {
6866 StructStat stat = Os.stat(dataPath.getPath());
6867 currentUid = stat.st_uid;
6868 } catch (ErrnoException e) {
6869 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6872 // If we have mismatched owners for the data path, we have a problem.
6873 if (currentUid != pkg.applicationInfo.uid) {
6874 boolean recovered = false;
6875 if (currentUid == 0) {
6876 // The directory somehow became owned by root. Wow.
6877 // This is probably because the system was stopped while
6878 // installd was in the middle of messing with its libs
6879 // directory. Ask installd to fix that.
6880 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6881 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6884 String msg = "Package " + pkg.packageName
6885 + " unexpectedly changed to uid 0; recovered to " +
6886 + pkg.applicationInfo.uid;
6887 reportSettingsProblem(Log.WARN, msg);
6890 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6891 || (scanFlags&SCAN_BOOTING) != 0)) {
6892 // If this is a system app, we can at least delete its
6893 // current data so the application will still work.
6894 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6896 // TODO: Kill the processes first
6898 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6899 ? "System package " : "Third party package ";
6900 String msg = prefix + pkg.packageName
6901 + " has changed from uid: "
6902 + currentUid + " to "
6903 + pkg.applicationInfo.uid + "; old data erased";
6904 reportSettingsProblem(Log.WARN, msg);
6907 // And now re-install the app.
6908 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6909 pkg.applicationInfo.seinfo);
6911 // Ack should not happen!
6912 msg = prefix + pkg.packageName
6913 + " could not have data directory re-created after delete.";
6914 reportSettingsProblem(Log.WARN, msg);
6915 throw new PackageManagerException(
6916 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6920 mHasSystemUidErrors = true;
6922 } else if (!recovered) {
6923 // If we allow this install to proceed, we will be broken.
6925 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6929 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6930 + pkg.applicationInfo.uid + "/fs_"
6932 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6933 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6934 String msg = "Package " + pkg.packageName
6935 + " has mismatched uid: "
6936 + currentUid + " on disk, "
6937 + pkg.applicationInfo.uid + " in settings";
6939 synchronized (mPackages) {
6940 mSettings.mReadMessages.append(msg);
6941 mSettings.mReadMessages.append('\n');
6943 if (!pkgSetting.uidError) {
6944 reportSettingsProblem(Log.ERROR, msg);
6949 pkg.applicationInfo.dataDir = dataPath.getPath();
6950 if (mShouldRestoreconData) {
6951 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6952 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6953 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6956 if (DEBUG_PACKAGE_SCANNING) {
6957 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6958 Log.v(TAG, "Want this data dir: " + dataPath);
6960 //invoke installer to do the actual installation
6961 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6962 pkg.applicationInfo.seinfo);
6964 // Error from installer
6965 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6966 "Unable to create data dirs [errorCode=" + ret + "]");
6969 if (dataPath.exists()) {
6970 pkg.applicationInfo.dataDir = dataPath.getPath();
6972 Slog.w(TAG, "Unable to create data directory: " + dataPath);
6973 pkg.applicationInfo.dataDir = null;
6977 pkgSetting.uidError = uidError;
6980 final String path = scanFile.getPath();
6981 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6983 if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6984 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6986 // Some system apps still use directory structure for native libraries
6987 // in which case we might end up not detecting abi solely based on apk
6988 // structure. Try to detect abi based on directory structure.
6989 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6990 pkg.applicationInfo.primaryCpuAbi == null) {
6991 setBundledAppAbisAndRoots(pkg, pkgSetting);
6992 setNativeLibraryPaths(pkg);
6996 if ((scanFlags & SCAN_MOVE) != 0) {
6997 // We haven't run dex-opt for this move (since we've moved the compiled output too)
6998 // but we already have this packages package info in the PackageSetting. We just
6999 // use that and derive the native library path based on the new codepath.
7000 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7001 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7004 // Set native library paths again. For moves, the path will be updated based on the
7005 // ABIs we've determined above. For non-moves, the path will be updated based on the
7006 // ABIs we determined during compilation, but the path will depend on the final
7007 // package path (after the rename away from the stage path).
7008 setNativeLibraryPaths(pkg);
7011 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7012 final int[] userIds = sUserManager.getUserIds();
7013 synchronized (mInstallLock) {
7014 // Make sure all user data directories are ready to roll; we're okay
7015 // if they already exist
7016 if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7017 for (int userId : userIds) {
7019 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7020 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7021 pkg.applicationInfo.seinfo);
7026 // Create a native library symlink only if we have native libraries
7027 // and if the native libraries are 32 bit libraries. We do not provide
7028 // this symlink for 64 bit libraries.
7029 if (pkg.applicationInfo.primaryCpuAbi != null &&
7030 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7031 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7032 for (int userId : userIds) {
7033 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7034 nativeLibPath, userId) < 0) {
7035 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7036 "Failed linking native library dir (user=" + userId + ")");
7042 // This is a special case for the "system" package, where the ABI is
7043 // dictated by the zygote configuration (and init.rc). We should keep track
7044 // of this ABI so that we can deal with "normal" applications that run under
7045 // the same UID correctly.
7046 if (mPlatformPackage == pkg) {
7047 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7048 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7051 // If there's a mismatch between the abi-override in the package setting
7052 // and the abiOverride specified for the install. Warn about this because we
7053 // would've already compiled the app without taking the package setting into
7055 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7056 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7057 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7058 " for package: " + pkg.packageName);
7062 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7063 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7064 pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7066 // Copy the derived override back to the parsed package, so that we can
7067 // update the package settings accordingly.
7068 pkg.cpuAbiOverride = cpuAbiOverride;
7070 if (DEBUG_ABI_SELECTION) {
7071 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7072 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7073 + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7076 // Push the derived path down into PackageSettings so we know what to
7077 // clean up at uninstall time.
7078 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7080 if (DEBUG_ABI_SELECTION) {
7081 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7082 " primary=" + pkg.applicationInfo.primaryCpuAbi +
7083 " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7086 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7087 // We don't do this here during boot because we can do it all
7088 // at once after scanning all existing packages.
7090 // We also do this *before* we perform dexopt on this package, so that
7091 // we can avoid redundant dexopts, and also to make sure we've got the
7092 // code and package path correct.
7093 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7094 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7097 if ((scanFlags & SCAN_NO_DEX) == 0) {
7098 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7099 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7100 if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7101 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7104 if (mFactoryTest && pkg.requestedPermissions.contains(
7105 android.Manifest.permission.FACTORY_TEST)) {
7106 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7109 ArrayList<PackageParser.Package> clientLibPkgs = null;
7112 synchronized (mPackages) {
7113 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7114 // Only system apps can add new shared libraries.
7115 if (pkg.libraryNames != null) {
7116 for (int i=0; i<pkg.libraryNames.size(); i++) {
7117 String name = pkg.libraryNames.get(i);
7118 boolean allowed = false;
7119 if (pkg.isUpdatedSystemApp()) {
7120 // New library entries can only be added through the
7121 // system image. This is important to get rid of a lot
7122 // of nasty edge cases: for example if we allowed a non-
7123 // system update of the app to add a library, then uninstalling
7124 // the update would make the library go away, and assumptions
7125 // we made such as through app install filtering would now
7126 // have allowed apps on the device which aren't compatible
7127 // with it. Better to just have the restriction here, be
7128 // conservative, and create many fewer cases that can negatively
7129 // impact the user experience.
7130 final PackageSetting sysPs = mSettings
7131 .getDisabledSystemPkgLPr(pkg.packageName);
7132 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7133 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7134 if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7145 if (!mSharedLibraries.containsKey(name)) {
7146 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7147 } else if (!name.equals(pkg.packageName)) {
7148 Slog.w(TAG, "Package " + pkg.packageName + " library "
7149 + name + " already exists; skipping");
7152 Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7153 + name + " that is not declared on system image; skipping");
7156 if ((scanFlags&SCAN_BOOTING) == 0) {
7157 // If we are not booting, we need to update any applications
7158 // that are clients of our shared library. If we are booting,
7159 // this will all be done once the scan is complete.
7160 clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7166 // We also need to dexopt any apps that are dependent on this library. Note that
7167 // if these fail, we should abort the install since installing the library will
7168 // result in some apps being broken.
7169 if (clientLibPkgs != null) {
7170 if ((scanFlags & SCAN_NO_DEX) == 0) {
7171 for (int i = 0; i < clientLibPkgs.size(); i++) {
7172 PackageParser.Package clientPkg = clientLibPkgs.get(i);
7173 int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7174 null /* instruction sets */, forceDex,
7175 (scanFlags & SCAN_DEFER_DEX) != 0, false);
7176 if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7177 throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7178 "scanPackageLI failed to dexopt clientLibPkgs");
7184 // Request the ActivityManager to kill the process(only for existing packages)
7185 // so that we do not end up in a confused state while the user is still using the older
7186 // version of the application while the new one gets installed.
7187 if ((scanFlags & SCAN_REPLACING) != 0) {
7188 killApplication(pkg.applicationInfo.packageName,
7189 pkg.applicationInfo.uid, "replace pkg");
7192 // Also need to kill any apps that are dependent on the library.
7193 if (clientLibPkgs != null) {
7194 for (int i=0; i<clientLibPkgs.size(); i++) {
7195 PackageParser.Package clientPkg = clientLibPkgs.get(i);
7196 killApplication(clientPkg.applicationInfo.packageName,
7197 clientPkg.applicationInfo.uid, "update lib");
7201 // Make sure we're not adding any bogus keyset info
7202 KeySetManagerService ksms = mSettings.mKeySetManagerService;
7203 ksms.assertScannedPackageValid(pkg);
7206 synchronized (mPackages) {
7207 // We don't expect installation to fail beyond this point
7209 // Add the new setting to mSettings
7210 mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7211 // Add the new setting to mPackages
7212 mPackages.put(pkg.applicationInfo.packageName, pkg);
7213 // Make sure we don't accidentally delete its data.
7214 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7215 while (iter.hasNext()) {
7216 PackageCleanItem item = iter.next();
7217 if (pkgName.equals(item.packageName)) {
7222 // Take care of first install / last update times.
7223 if (currentTime != 0) {
7224 if (pkgSetting.firstInstallTime == 0) {
7225 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7226 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7227 pkgSetting.lastUpdateTime = currentTime;
7229 } else if (pkgSetting.firstInstallTime == 0) {
7230 // We need *something*. Take time time stamp of the file.
7231 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7232 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7233 if (scanFileTime != pkgSetting.timeStamp) {
7234 // A package on the system image has changed; consider this
7236 pkgSetting.lastUpdateTime = scanFileTime;
7240 // Add the package's KeySets to the global KeySetManagerService
7241 ksms.addScannedPackageLPw(pkg);
7243 int N = pkg.providers.size();
7244 StringBuilder r = null;
7246 for (i=0; i<N; i++) {
7247 PackageParser.Provider p = pkg.providers.get(i);
7248 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7249 p.info.processName, pkg.applicationInfo.uid);
7250 mProviders.addProvider(p);
7251 p.syncable = p.info.isSyncable;
7252 if (p.info.authority != null) {
7253 String names[] = p.info.authority.split(";");
7254 p.info.authority = null;
7255 for (int j = 0; j < names.length; j++) {
7256 if (j == 1 && p.syncable) {
7257 // We only want the first authority for a provider to possibly be
7258 // syncable, so if we already added this provider using a different
7259 // authority clear the syncable flag. We copy the provider before
7260 // changing it because the mProviders object contains a reference
7261 // to a provider that we don't want to change.
7262 // Only do this for the second authority since the resulting provider
7263 // object can be the same for all future authorities for this provider.
7264 p = new PackageParser.Provider(p);
7267 if (!mProvidersByAuthority.containsKey(names[j])) {
7268 mProvidersByAuthority.put(names[j], p);
7269 if (p.info.authority == null) {
7270 p.info.authority = names[j];
7272 p.info.authority = p.info.authority + ";" + names[j];
7274 if (DEBUG_PACKAGE_SCANNING) {
7275 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7276 Log.d(TAG, "Registered content provider: " + names[j]
7277 + ", className = " + p.info.name + ", isSyncable = "
7278 + p.info.isSyncable);
7281 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7282 Slog.w(TAG, "Skipping provider name " + names[j] +
7283 " (in package " + pkg.applicationInfo.packageName +
7284 "): name already used by "
7285 + ((other != null && other.getComponentName() != null)
7286 ? other.getComponentName().getPackageName() : "?"));
7290 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7292 r = new StringBuilder(256);
7296 r.append(p.info.name);
7300 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r);
7303 N = pkg.services.size();
7305 for (i=0; i<N; i++) {
7306 PackageParser.Service s = pkg.services.get(i);
7307 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7308 s.info.processName, pkg.applicationInfo.uid);
7309 mServices.addService(s);
7310 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7312 r = new StringBuilder(256);
7316 r.append(s.info.name);
7320 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r);
7323 N = pkg.receivers.size();
7325 for (i=0; i<N; i++) {
7326 PackageParser.Activity a = pkg.receivers.get(i);
7327 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7328 a.info.processName, pkg.applicationInfo.uid);
7329 mReceivers.addActivity(a, "receiver");
7330 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7332 r = new StringBuilder(256);
7336 r.append(a.info.name);
7340 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r);
7343 N = pkg.activities.size();
7345 for (i=0; i<N; i++) {
7346 PackageParser.Activity a = pkg.activities.get(i);
7347 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7348 a.info.processName, pkg.applicationInfo.uid);
7349 mActivities.addActivity(a, "activity");
7350 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7352 r = new StringBuilder(256);
7356 r.append(a.info.name);
7360 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r);
7363 N = pkg.permissionGroups.size();
7365 for (i=0; i<N; i++) {
7366 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7367 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7369 mPermissionGroups.put(pg.info.name, pg);
7370 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7372 r = new StringBuilder(256);
7376 r.append(pg.info.name);
7379 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7380 + pg.info.packageName + " ignored: original from "
7381 + cur.info.packageName);
7382 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7384 r = new StringBuilder(256);
7389 r.append(pg.info.name);
7394 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r);
7397 N = pkg.permissions.size();
7399 for (i=0; i<N; i++) {
7400 PackageParser.Permission p = pkg.permissions.get(i);
7402 // Assume by default that we did not install this permission into the system.
7403 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7405 // Now that permission groups have a special meaning, we ignore permission
7406 // groups for legacy apps to prevent unexpected behavior. In particular,
7407 // permissions for one app being granted to someone just becuase they happen
7408 // to be in a group defined by another app (before this had no implications).
7409 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7410 p.group = mPermissionGroups.get(p.info.group);
7411 // Warn for a permission in an unknown group.
7412 if (p.info.group != null && p.group == null) {
7413 Slog.w(TAG, "Permission " + p.info.name + " from package "
7414 + p.info.packageName + " in an unknown group " + p.info.group);
7418 ArrayMap<String, BasePermission> permissionMap =
7419 p.tree ? mSettings.mPermissionTrees
7420 : mSettings.mPermissions;
7421 BasePermission bp = permissionMap.get(p.info.name);
7423 // Allow system apps to redefine non-system permissions
7424 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7425 final boolean currentOwnerIsSystem = (bp.perm != null
7426 && isSystemApp(bp.perm.owner));
7427 if (isSystemApp(p.owner)) {
7428 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7429 // It's a built-in permission and no owner, take ownership now
7430 bp.packageSetting = pkgSetting;
7432 bp.uid = pkg.applicationInfo.uid;
7433 bp.sourcePackage = p.info.packageName;
7434 p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7435 } else if (!currentOwnerIsSystem) {
7436 String msg = "New decl " + p.owner + " of permission "
7437 + p.info.name + " is system; overriding " + bp.sourcePackage;
7438 reportSettingsProblem(Log.WARN, msg);
7445 bp = new BasePermission(p.info.name, p.info.packageName,
7446 BasePermission.TYPE_NORMAL);
7447 permissionMap.put(p.info.name, bp);
7450 if (bp.perm == null) {
7451 if (bp.sourcePackage == null
7452 || bp.sourcePackage.equals(p.info.packageName)) {
7453 BasePermission tree = findPermissionTreeLP(p.info.name);
7455 || tree.sourcePackage.equals(p.info.packageName)) {
7456 bp.packageSetting = pkgSetting;
7458 bp.uid = pkg.applicationInfo.uid;
7459 bp.sourcePackage = p.info.packageName;
7460 p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7461 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7463 r = new StringBuilder(256);
7467 r.append(p.info.name);
7470 Slog.w(TAG, "Permission " + p.info.name + " from package "
7471 + p.info.packageName + " ignored: base tree "
7472 + tree.name + " is from package "
7473 + tree.sourcePackage);
7476 Slog.w(TAG, "Permission " + p.info.name + " from package "
7477 + p.info.packageName + " ignored: original from "
7478 + bp.sourcePackage);
7480 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7482 r = new StringBuilder(256);
7487 r.append(p.info.name);
7490 bp.protectionLevel = p.info.protectionLevel;
7495 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r);
7498 N = pkg.instrumentation.size();
7500 for (i=0; i<N; i++) {
7501 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7502 a.info.packageName = pkg.applicationInfo.packageName;
7503 a.info.sourceDir = pkg.applicationInfo.sourceDir;
7504 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7505 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7506 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7507 a.info.dataDir = pkg.applicationInfo.dataDir;
7509 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7510 // need other information about the application, like the ABI and what not ?
7511 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7512 mInstrumentation.put(a.getComponentName(), a);
7513 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7515 r = new StringBuilder(256);
7519 r.append(a.info.name);
7523 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r);
7526 if (pkg.protectedBroadcasts != null) {
7527 N = pkg.protectedBroadcasts.size();
7528 for (i=0; i<N; i++) {
7529 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7533 pkgSetting.setTimeStamp(scanFileTime);
7535 // Create idmap files for pairs of (packages, overlay packages).
7536 // Note: "android", ie framework-res.apk, is handled by native layers.
7537 if (pkg.mOverlayTarget != null) {
7538 // This is an overlay package.
7539 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7540 if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7541 mOverlays.put(pkg.mOverlayTarget,
7542 new ArrayMap<String, PackageParser.Package>());
7544 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7545 map.put(pkg.packageName, pkg);
7546 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7547 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7548 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7549 "scanPackageLI failed to createIdmap");
7552 } else if (mOverlays.containsKey(pkg.packageName) &&
7553 !pkg.packageName.equals("android")) {
7554 // This is a regular package, with one or more known overlay packages.
7555 createIdmapsForPackageLI(pkg);
7563 * Derive the ABI of a non-system package located at {@code scanFile}. This information
7564 * is derived purely on the basis of the contents of {@code scanFile} and
7565 * {@code cpuAbiOverride}.
7567 * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7569 public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7570 String cpuAbiOverride, boolean extractLibs)
7571 throws PackageManagerException {
7572 // TODO: We can probably be smarter about this stuff. For installed apps,
7573 // we can calculate this information at install time once and for all. For
7574 // system apps, we can probably assume that this information doesn't change
7575 // after the first boot scan. As things stand, we do lots of unnecessary work.
7577 // Give ourselves some initial paths; we'll come back for another
7578 // pass once we've determined ABI below.
7579 setNativeLibraryPaths(pkg);
7581 // We would never need to extract libs for forward-locked and external packages,
7582 // since the container service will do it for us. We shouldn't attempt to
7583 // extract libs from system app when it was not updated.
7584 if (pkg.isForwardLocked() || isExternal(pkg) ||
7585 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7586 extractLibs = false;
7589 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7590 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7592 NativeLibraryHelper.Handle handle = null;
7594 handle = NativeLibraryHelper.Handle.create(scanFile);
7595 // TODO(multiArch): This can be null for apps that didn't go through the
7596 // usual installation process. We can calculate it again, like we
7597 // do during install time.
7599 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7601 final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7603 // Null out the abis so that they can be recalculated.
7604 pkg.applicationInfo.primaryCpuAbi = null;
7605 pkg.applicationInfo.secondaryCpuAbi = null;
7606 if (isMultiArch(pkg.applicationInfo)) {
7607 // Warn if we've set an abiOverride for multi-lib packages..
7608 // By definition, we need to copy both 32 and 64 bit libraries for
7610 if (pkg.cpuAbiOverride != null
7611 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7612 Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7615 int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7616 int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7617 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7619 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7620 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7621 useIsaSpecificSubdirs);
7623 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7627 maybeThrowExceptionForMultiArchCopy(
7628 "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7630 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7632 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7633 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7634 useIsaSpecificSubdirs);
7636 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7640 maybeThrowExceptionForMultiArchCopy(
7641 "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7644 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7648 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7650 pkg.applicationInfo.secondaryCpuAbi = abi;
7652 pkg.applicationInfo.primaryCpuAbi = abi;
7656 String[] abiList = (cpuAbiOverride != null) ?
7657 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7659 // Enable gross and lame hacks for apps that are built with old
7660 // SDK tools. We must scan their APKs for renderscript bitcode and
7661 // not launch them if it's present. Don't bother checking on devices
7662 // that don't have 64 bit support.
7663 boolean needsRenderScriptOverride = false;
7664 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7665 NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7666 abiList = Build.SUPPORTED_32_BIT_ABIS;
7667 needsRenderScriptOverride = true;
7672 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7673 nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7675 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7678 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7679 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7680 "Error unpackaging native libs for app, errorCode=" + copyRet);
7684 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7685 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7686 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7687 } else if (needsRenderScriptOverride) {
7688 pkg.applicationInfo.primaryCpuAbi = abiList[0];
7691 } catch (IOException ioe) {
7692 Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7694 IoUtils.closeQuietly(handle);
7697 // Now that we've calculated the ABIs and determined if it's an internal app,
7698 // we will go ahead and populate the nativeLibraryPath.
7699 setNativeLibraryPaths(pkg);
7703 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7704 * i.e, so that all packages can be run inside a single process if required.
7706 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7707 * this function will either try and make the ABI for all packages in {@code packagesForUser}
7708 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7709 * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7710 * updating a package that belongs to a shared user.
7712 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7713 * adds unnecessary complexity.
7715 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7716 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7717 String requiredInstructionSet = null;
7718 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7719 requiredInstructionSet = VMRuntime.getInstructionSet(
7720 scannedPackage.applicationInfo.primaryCpuAbi);
7723 PackageSetting requirer = null;
7724 for (PackageSetting ps : packagesForUser) {
7725 // If packagesForUser contains scannedPackage, we skip it. This will happen
7726 // when scannedPackage is an update of an existing package. Without this check,
7727 // we will never be able to change the ABI of any package belonging to a shared
7728 // user, even if it's compatible with other packages.
7729 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7730 if (ps.primaryCpuAbiString == null) {
7734 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7735 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7736 // We have a mismatch between instruction sets (say arm vs arm64) warn about
7737 // this but there's not much we can do.
7738 String errorMessage = "Instruction set mismatch, "
7739 + ((requirer == null) ? "[caller]" : requirer)
7740 + " requires " + requiredInstructionSet + " whereas " + ps
7741 + " requires " + instructionSet;
7742 Slog.w(TAG, errorMessage);
7745 if (requiredInstructionSet == null) {
7746 requiredInstructionSet = instructionSet;
7752 if (requiredInstructionSet != null) {
7754 if (requirer != null) {
7755 // requirer != null implies that either scannedPackage was null or that scannedPackage
7756 // did not require an ABI, in which case we have to adjust scannedPackage to match
7757 // the ABI of the set (which is the same as requirer's ABI)
7758 adjustedAbi = requirer.primaryCpuAbiString;
7759 if (scannedPackage != null) {
7760 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7763 // requirer == null implies that we're updating all ABIs in the set to
7764 // match scannedPackage.
7765 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi;
7768 for (PackageSetting ps : packagesForUser) {
7769 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7770 if (ps.primaryCpuAbiString != null) {
7774 ps.primaryCpuAbiString = adjustedAbi;
7775 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7776 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7777 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7779 int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7780 null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7781 if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7782 ps.primaryCpuAbiString = null;
7783 ps.pkg.applicationInfo.primaryCpuAbi = null;
7786 mInstaller.rmdex(ps.codePathString,
7787 getDexCodeInstructionSet(getPreferredInstructionSet()));
7795 private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7796 synchronized (mPackages) {
7797 mResolverReplaced = true;
7798 // Set up information for custom user intent resolution activity.
7799 mResolveActivity.applicationInfo = pkg.applicationInfo;
7800 mResolveActivity.name = mCustomResolverComponentName.getClassName();
7801 mResolveActivity.packageName = pkg.applicationInfo.packageName;
7802 mResolveActivity.processName = pkg.applicationInfo.packageName;
7803 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7804 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7805 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7806 mResolveActivity.theme = 0;
7807 mResolveActivity.exported = true;
7808 mResolveActivity.enabled = true;
7809 mResolveInfo.activityInfo = mResolveActivity;
7810 mResolveInfo.priority = 0;
7811 mResolveInfo.preferredOrder = 0;
7812 mResolveInfo.match = 0;
7813 mResolveComponentName = mCustomResolverComponentName;
7814 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7815 mResolveComponentName);
7819 private static String calculateBundledApkRoot(final String codePathString) {
7820 final File codePath = new File(codePathString);
7821 final File codeRoot;
7822 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7823 codeRoot = Environment.getRootDirectory();
7824 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7825 codeRoot = Environment.getOemDirectory();
7826 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7827 codeRoot = Environment.getVendorDirectory();
7829 // Unrecognized code path; take its top real segment as the apk root:
7830 // e.g. /something/app/blah.apk => /something
7832 File f = codePath.getCanonicalFile();
7833 File parent = f.getParentFile(); // non-null because codePath is a file
7835 while ((tmp = parent.getParentFile()) != null) {
7840 Slog.w(TAG, "Unrecognized code path "
7841 + codePath + " - using " + codeRoot);
7842 } catch (IOException e) {
7843 // Can't canonicalize the code path -- shenanigans?
7844 Slog.w(TAG, "Can't canonicalize code path " + codePath);
7845 return Environment.getRootDirectory().getPath();
7848 return codeRoot.getPath();
7852 * Derive and set the location of native libraries for the given package,
7853 * which varies depending on where and how the package was installed.
7855 private void setNativeLibraryPaths(PackageParser.Package pkg) {
7856 final ApplicationInfo info = pkg.applicationInfo;
7857 final String codePath = pkg.codePath;
7858 final File codeFile = new File(codePath);
7859 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7860 final boolean asecApp = info.isForwardLocked() || isExternal(info);
7862 info.nativeLibraryRootDir = null;
7863 info.nativeLibraryRootRequiresIsa = false;
7864 info.nativeLibraryDir = null;
7865 info.secondaryNativeLibraryDir = null;
7867 if (isApkFile(codeFile)) {
7868 // Monolithic install
7870 // If "/system/lib64/apkname" exists, assume that is the per-package
7871 // native library directory to use; otherwise use "/system/lib/apkname".
7872 final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7873 final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7874 getPrimaryInstructionSet(info));
7876 // This is a bundled system app so choose the path based on the ABI.
7877 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7878 // is just the default path.
7879 final String apkName = deriveCodePathName(codePath);
7880 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7881 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7882 apkName).getAbsolutePath();
7884 if (info.secondaryCpuAbi != null) {
7885 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7886 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7887 secondaryLibDir, apkName).getAbsolutePath();
7889 } else if (asecApp) {
7890 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7893 final String apkName = deriveCodePathName(codePath);
7894 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7898 info.nativeLibraryRootRequiresIsa = false;
7899 info.nativeLibraryDir = info.nativeLibraryRootDir;
7902 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7903 info.nativeLibraryRootRequiresIsa = true;
7905 info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7906 getPrimaryInstructionSet(info)).getAbsolutePath();
7908 if (info.secondaryCpuAbi != null) {
7909 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7910 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7916 * Calculate the abis and roots for a bundled app. These can uniquely
7917 * be determined from the contents of the system partition, i.e whether
7918 * it contains 64 or 32 bit shared libraries etc. We do not validate any
7919 * of this information, and instead assume that the system was built
7922 private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7923 PackageSetting pkgSetting) {
7924 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7926 // If "/system/lib64/apkname" exists, assume that is the per-package
7927 // native library directory to use; otherwise use "/system/lib/apkname".
7928 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7929 setBundledAppAbi(pkg, apkRoot, apkName);
7930 // pkgSetting might be null during rescan following uninstall of updates
7931 // to a bundled app, so accommodate that possibility. The settings in
7932 // that case will be established later from the parsed package.
7934 // If the settings aren't null, sync them up with what we've just derived.
7935 // note that apkRoot isn't stored in the package settings.
7936 if (pkgSetting != null) {
7937 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7938 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7943 * Deduces the ABI of a bundled app and sets the relevant fields on the
7944 * parsed pkg object.
7946 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7947 * under which system libraries are installed.
7948 * @param apkName the name of the installed package.
7950 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7951 final File codeFile = new File(pkg.codePath);
7953 final boolean has64BitLibs;
7954 final boolean has32BitLibs;
7955 if (isApkFile(codeFile)) {
7956 // Monolithic install
7957 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7958 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7961 final File rootDir = new File(codeFile, LIB_DIR_NAME);
7962 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7963 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7964 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7965 has64BitLibs = (new File(rootDir, isa)).exists();
7967 has64BitLibs = false;
7969 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7970 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7971 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7972 has32BitLibs = (new File(rootDir, isa)).exists();
7974 has32BitLibs = false;
7978 if (has64BitLibs && !has32BitLibs) {
7979 // The package has 64 bit libs, but not 32 bit libs. Its primary
7980 // ABI should be 64 bit. We can safely assume here that the bundled
7981 // native libraries correspond to the most preferred ABI in the list.
7983 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7984 pkg.applicationInfo.secondaryCpuAbi = null;
7985 } else if (has32BitLibs && !has64BitLibs) {
7986 // The package has 32 bit libs but not 64 bit libs. Its primary
7987 // ABI should be 32 bit.
7989 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7990 pkg.applicationInfo.secondaryCpuAbi = null;
7991 } else if (has32BitLibs && has64BitLibs) {
7992 // The application has both 64 and 32 bit bundled libraries. We check
7993 // here that the app declares multiArch support, and warn if it doesn't.
7995 // We will be lenient here and record both ABIs. The primary will be the
7996 // ABI that's higher on the list, i.e, a device that's configured to prefer
7997 // 64 bit apps will see a 64 bit primary ABI,
7999 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8000 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8003 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8004 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8005 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8007 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8008 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8011 pkg.applicationInfo.primaryCpuAbi = null;
8012 pkg.applicationInfo.secondaryCpuAbi = null;
8016 private void killApplication(String pkgName, int appId, String reason) {
8017 // Request the ActivityManager to kill the process(only for existing packages)
8018 // so that we do not end up in a confused state while the user is still using the older
8019 // version of the application while the new one gets installed.
8020 IActivityManager am = ActivityManagerNative.getDefault();
8023 am.killApplicationWithAppId(pkgName, appId, reason);
8024 } catch (RemoteException e) {
8029 void removePackageLI(PackageSetting ps, boolean chatty) {
8030 if (DEBUG_INSTALL) {
8032 Log.d(TAG, "Removing package " + ps.name);
8036 synchronized (mPackages) {
8037 mPackages.remove(ps.name);
8038 final PackageParser.Package pkg = ps.pkg;
8040 cleanPackageDataStructuresLILPw(pkg, chatty);
8045 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8046 if (DEBUG_INSTALL) {
8048 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8052 synchronized (mPackages) {
8053 mPackages.remove(pkg.applicationInfo.packageName);
8054 cleanPackageDataStructuresLILPw(pkg, chatty);
8058 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8059 int N = pkg.providers.size();
8060 StringBuilder r = null;
8062 for (i=0; i<N; i++) {
8063 PackageParser.Provider p = pkg.providers.get(i);
8064 mProviders.removeProvider(p);
8065 if (p.info.authority == null) {
8067 /* There was another ContentProvider with this authority when
8068 * this app was installed so this authority is null,
8069 * Ignore it as we don't have to unregister the provider.
8073 String names[] = p.info.authority.split(";");
8074 for (int j = 0; j < names.length; j++) {
8075 if (mProvidersByAuthority.get(names[j]) == p) {
8076 mProvidersByAuthority.remove(names[j]);
8079 Log.d(TAG, "Unregistered content provider: " + names[j]
8080 + ", className = " + p.info.name + ", isSyncable = "
8081 + p.info.isSyncable);
8085 if (DEBUG_REMOVE && chatty) {
8087 r = new StringBuilder(256);
8091 r.append(p.info.name);
8095 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r);
8098 N = pkg.services.size();
8100 for (i=0; i<N; i++) {
8101 PackageParser.Service s = pkg.services.get(i);
8102 mServices.removeService(s);
8105 r = new StringBuilder(256);
8109 r.append(s.info.name);
8113 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r);
8116 N = pkg.receivers.size();
8118 for (i=0; i<N; i++) {
8119 PackageParser.Activity a = pkg.receivers.get(i);
8120 mReceivers.removeActivity(a, "receiver");
8121 if (DEBUG_REMOVE && chatty) {
8123 r = new StringBuilder(256);
8127 r.append(a.info.name);
8131 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r);
8134 N = pkg.activities.size();
8136 for (i=0; i<N; i++) {
8137 PackageParser.Activity a = pkg.activities.get(i);
8138 mActivities.removeActivity(a, "activity");
8139 if (DEBUG_REMOVE && chatty) {
8141 r = new StringBuilder(256);
8145 r.append(a.info.name);
8149 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r);
8152 N = pkg.permissions.size();
8154 for (i=0; i<N; i++) {
8155 PackageParser.Permission p = pkg.permissions.get(i);
8156 BasePermission bp = mSettings.mPermissions.get(p.info.name);
8158 bp = mSettings.mPermissionTrees.get(p.info.name);
8160 if (bp != null && bp.perm == p) {
8162 if (DEBUG_REMOVE && chatty) {
8164 r = new StringBuilder(256);
8168 r.append(p.info.name);
8171 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8172 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8173 if (appOpPerms != null) {
8174 appOpPerms.remove(pkg.packageName);
8179 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
8182 N = pkg.requestedPermissions.size();
8184 for (i=0; i<N; i++) {
8185 String perm = pkg.requestedPermissions.get(i);
8186 BasePermission bp = mSettings.mPermissions.get(perm);
8187 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8188 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8189 if (appOpPerms != null) {
8190 appOpPerms.remove(pkg.packageName);
8191 if (appOpPerms.isEmpty()) {
8192 mAppOpPermissionPackages.remove(perm);
8198 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
8201 N = pkg.instrumentation.size();
8203 for (i=0; i<N; i++) {
8204 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8205 mInstrumentation.remove(a.getComponentName());
8206 if (DEBUG_REMOVE && chatty) {
8208 r = new StringBuilder(256);
8212 r.append(a.info.name);
8216 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r);
8220 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8221 // Only system apps can hold shared libraries.
8222 if (pkg.libraryNames != null) {
8223 for (i=0; i<pkg.libraryNames.size(); i++) {
8224 String name = pkg.libraryNames.get(i);
8225 SharedLibraryEntry cur = mSharedLibraries.get(name);
8226 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8227 mSharedLibraries.remove(name);
8228 if (DEBUG_REMOVE && chatty) {
8230 r = new StringBuilder(256);
8241 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r);
8245 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8246 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8247 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8254 static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8255 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8256 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8258 private void updatePermissionsLPw(String changingPkg,
8259 PackageParser.Package pkgInfo, int flags) {
8260 // Make sure there are no dangling permission trees.
8261 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8262 while (it.hasNext()) {
8263 final BasePermission bp = it.next();
8264 if (bp.packageSetting == null) {
8265 // We may not yet have parsed the package, so just see if
8266 // we still know about its settings.
8267 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8269 if (bp.packageSetting == null) {
8270 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8271 + " from package " + bp.sourcePackage);
8273 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8274 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8275 Slog.i(TAG, "Removing old permission tree: " + bp.name
8276 + " from package " + bp.sourcePackage);
8277 flags |= UPDATE_PERMISSIONS_ALL;
8283 // Make sure all dynamic permissions have been assigned to a package,
8284 // and make sure there are no dangling permissions.
8285 it = mSettings.mPermissions.values().iterator();
8286 while (it.hasNext()) {
8287 final BasePermission bp = it.next();
8288 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8289 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8290 + bp.name + " pkg=" + bp.sourcePackage
8291 + " info=" + bp.pendingInfo);
8292 if (bp.packageSetting == null && bp.pendingInfo != null) {
8293 final BasePermission tree = findPermissionTreeLP(bp.name);
8294 if (tree != null && tree.perm != null) {
8295 bp.packageSetting = tree.packageSetting;
8296 bp.perm = new PackageParser.Permission(tree.perm.owner,
8297 new PermissionInfo(bp.pendingInfo));
8298 bp.perm.info.packageName = tree.perm.info.packageName;
8299 bp.perm.info.name = bp.name;
8304 if (bp.packageSetting == null) {
8305 // We may not yet have parsed the package, so just see if
8306 // we still know about its settings.
8307 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8309 if (bp.packageSetting == null) {
8310 Slog.w(TAG, "Removing dangling permission: " + bp.name
8311 + " from package " + bp.sourcePackage);
8313 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8314 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8315 Slog.i(TAG, "Removing old permission: " + bp.name
8316 + " from package " + bp.sourcePackage);
8317 flags |= UPDATE_PERMISSIONS_ALL;
8323 // Now update the permissions for all packages, in particular
8324 // replace the granted permissions of the system packages.
8325 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8326 for (PackageParser.Package pkg : mPackages.values()) {
8327 if (pkg != pkgInfo) {
8328 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8334 if (pkgInfo != null) {
8335 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8339 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8340 String packageOfInterest) {
8341 // IMPORTANT: There are two types of permissions: install and runtime.
8342 // Install time permissions are granted when the app is installed to
8343 // all device users and users added in the future. Runtime permissions
8344 // are granted at runtime explicitly to specific users. Normal and signature
8345 // protected permissions are install time permissions. Dangerous permissions
8346 // are install permissions if the app's target SDK is Lollipop MR1 or older,
8347 // otherwise they are runtime permissions. This function does not manage
8348 // runtime permissions except for the case an app targeting Lollipop MR1
8349 // being upgraded to target a newer SDK, in which case dangerous permissions
8350 // are transformed from install time to runtime ones.
8352 final PackageSetting ps = (PackageSetting) pkg.mExtras;
8357 PermissionsState permissionsState = ps.getPermissionsState();
8358 PermissionsState origPermissions = permissionsState;
8360 final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8362 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8364 boolean changedInstallPermission = false;
8367 ps.installPermissionsFixed = false;
8368 if (!ps.isSharedUser()) {
8369 origPermissions = new PermissionsState(permissionsState);
8370 permissionsState.reset();
8374 permissionsState.setGlobalGids(mGlobalGids);
8376 final int N = pkg.requestedPermissions.size();
8377 for (int i=0; i<N; i++) {
8378 final String name = pkg.requestedPermissions.get(i);
8379 final BasePermission bp = mSettings.mPermissions.get(name);
8381 if (DEBUG_INSTALL) {
8382 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8385 if (bp == null || bp.packageSetting == null) {
8386 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8387 Slog.w(TAG, "Unknown permission " + name
8388 + " in package " + pkg.packageName);
8393 final String perm = bp.name;
8394 boolean allowedSig = false;
8395 int grant = GRANT_DENIED;
8397 // Keep track of app op permissions.
8398 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8399 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8401 pkgs = new ArraySet<>();
8402 mAppOpPermissionPackages.put(bp.name, pkgs);
8404 pkgs.add(pkg.packageName);
8407 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8409 case PermissionInfo.PROTECTION_NORMAL: {
8410 // For all apps normal permissions are install time ones.
8411 grant = GRANT_INSTALL;
8414 case PermissionInfo.PROTECTION_DANGEROUS: {
8415 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8416 // For legacy apps dangerous permissions are install time ones.
8417 grant = GRANT_INSTALL_LEGACY;
8418 } else if (origPermissions.hasInstallPermission(bp.name)) {
8419 // For legacy apps that became modern, install becomes runtime.
8420 grant = GRANT_UPGRADE;
8421 } else if (mPromoteSystemApps
8423 && mExistingSystemPackages.contains(ps.name)) {
8424 // For legacy system apps, install becomes runtime.
8425 // We cannot check hasInstallPermission() for system apps since those
8426 // permissions were granted implicitly and not persisted pre-M.
8427 grant = GRANT_UPGRADE;
8429 // For modern apps keep runtime permissions unchanged.
8430 grant = GRANT_RUNTIME;
8434 case PermissionInfo.PROTECTION_SIGNATURE: {
8435 // For all apps signature permissions are install time ones.
8436 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8438 grant = GRANT_INSTALL;
8443 if (DEBUG_INSTALL) {
8444 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8447 if (grant != GRANT_DENIED) {
8448 if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8449 // If this is an existing, non-system package, then
8450 // we can't add any new permissions to it.
8451 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8452 // Except... if this is a permission that was added
8453 // to the platform (note: need to only do this when
8454 // updating the platform).
8455 if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8456 grant = GRANT_DENIED;
8462 case GRANT_INSTALL: {
8463 // Revoke this as runtime permission to handle the case of
8464 // a runtime permission being downgraded to an install one.
8465 for (int userId : UserManagerService.getInstance().getUserIds()) {
8466 if (origPermissions.getRuntimePermissionState(
8467 bp.name, userId) != null) {
8468 // Revoke the runtime permission and clear the flags.
8469 origPermissions.revokeRuntimePermission(bp, userId);
8470 origPermissions.updatePermissionFlags(bp, userId,
8471 PackageManager.MASK_PERMISSION_FLAGS, 0);
8472 // If we revoked a permission permission, we have to write.
8473 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8474 changedRuntimePermissionUserIds, userId);
8477 // Grant an install permission.
8478 if (permissionsState.grantInstallPermission(bp) !=
8479 PermissionsState.PERMISSION_OPERATION_FAILURE) {
8480 changedInstallPermission = true;
8484 case GRANT_INSTALL_LEGACY: {
8485 // Grant an install permission.
8486 if (permissionsState.grantInstallPermission(bp) !=
8487 PermissionsState.PERMISSION_OPERATION_FAILURE) {
8488 changedInstallPermission = true;
8492 case GRANT_RUNTIME: {
8493 // Grant previously granted runtime permissions.
8494 for (int userId : UserManagerService.getInstance().getUserIds()) {
8495 PermissionState permissionState = origPermissions
8496 .getRuntimePermissionState(bp.name, userId);
8497 final int flags = permissionState != null
8498 ? permissionState.getFlags() : 0;
8499 if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8500 if (permissionsState.grantRuntimePermission(bp, userId) ==
8501 PermissionsState.PERMISSION_OPERATION_FAILURE) {
8502 // If we cannot put the permission as it was, we have to write.
8503 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8504 changedRuntimePermissionUserIds, userId);
8507 // Propagate the permission flags.
8508 permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8512 case GRANT_UPGRADE: {
8513 // Grant runtime permissions for a previously held install permission.
8514 PermissionState permissionState = origPermissions
8515 .getInstallPermissionState(bp.name);
8516 final int flags = permissionState != null ? permissionState.getFlags() : 0;
8518 if (origPermissions.revokeInstallPermission(bp)
8519 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8520 // We will be transferring the permission flags, so clear them.
8521 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8522 PackageManager.MASK_PERMISSION_FLAGS, 0);
8523 changedInstallPermission = true;
8526 // If the permission is not to be promoted to runtime we ignore it and
8527 // also its other flags as they are not applicable to install permissions.
8528 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8529 for (int userId : currentUserIds) {
8530 if (permissionsState.grantRuntimePermission(bp, userId) !=
8531 PermissionsState.PERMISSION_OPERATION_FAILURE) {
8532 // Transfer the permission flags.
8533 permissionsState.updatePermissionFlags(bp, userId,
8535 // If we granted the permission, we have to write.
8536 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8537 changedRuntimePermissionUserIds, userId);
8544 if (packageOfInterest == null
8545 || packageOfInterest.equals(pkg.packageName)) {
8546 Slog.w(TAG, "Not granting permission " + perm
8547 + " to package " + pkg.packageName
8548 + " because it was previously installed without");
8553 if (permissionsState.revokeInstallPermission(bp) !=
8554 PermissionsState.PERMISSION_OPERATION_FAILURE) {
8555 // Also drop the permission flags.
8556 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8557 PackageManager.MASK_PERMISSION_FLAGS, 0);
8558 changedInstallPermission = true;
8559 Slog.i(TAG, "Un-granting permission " + perm
8560 + " from package " + pkg.packageName
8561 + " (protectionLevel=" + bp.protectionLevel
8562 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8564 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8565 // Don't print warning for app op permissions, since it is fine for them
8566 // not to be granted, there is a UI for the user to decide.
8567 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8568 Slog.w(TAG, "Not granting permission " + perm
8569 + " to package " + pkg.packageName
8570 + " (protectionLevel=" + bp.protectionLevel
8571 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8578 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8579 !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8580 // This is the first that we have heard about this package, so the
8581 // permissions we have now selected are fixed until explicitly
8583 ps.installPermissionsFixed = true;
8586 // Persist the runtime permissions state for users with changes.
8587 for (int userId : changedRuntimePermissionUserIds) {
8588 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8592 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8593 boolean allowed = false;
8594 final int NP = PackageParser.NEW_PERMISSIONS.length;
8595 for (int ip=0; ip<NP; ip++) {
8596 final PackageParser.NewPermissionInfo npi
8597 = PackageParser.NEW_PERMISSIONS[ip];
8598 if (npi.name.equals(perm)
8599 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8601 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8609 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8610 BasePermission bp, PermissionsState origPermissions) {
8612 allowed = (compareSignatures(
8613 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8614 == PackageManager.SIGNATURE_MATCH)
8615 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8616 == PackageManager.SIGNATURE_MATCH);
8617 if (!allowed && (bp.protectionLevel
8618 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8619 if (isSystemApp(pkg)) {
8620 // For updated system applications, a system permission
8621 // is granted only if it had been defined by the original application.
8622 if (pkg.isUpdatedSystemApp()) {
8623 final PackageSetting sysPs = mSettings
8624 .getDisabledSystemPkgLPr(pkg.packageName);
8625 if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8626 // If the original was granted this permission, we take
8627 // that grant decision as read and propagate it to the
8629 if (sysPs.isPrivileged()) {
8633 // The system apk may have been updated with an older
8634 // version of the one on the data partition, but which
8635 // granted a new system permission that it didn't have
8636 // before. In this case we do want to allow the app to
8637 // now get the new permission if the ancestral apk is
8638 // privileged to get it.
8639 if (sysPs.pkg != null && sysPs.isPrivileged()) {
8641 j<sysPs.pkg.requestedPermissions.size(); j++) {
8643 sysPs.pkg.requestedPermissions.get(j))) {
8651 allowed = isPrivilegedApp(pkg);
8656 if (!allowed && (bp.protectionLevel
8657 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8658 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8659 // If this was a previously normal/dangerous permission that got moved
8660 // to a system permission as part of the runtime permission redesign, then
8661 // we still want to blindly grant it to old apps.
8664 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8665 && pkg.packageName.equals(mRequiredInstallerPackage)) {
8666 // If this permission is to be granted to the system installer and
8667 // this app is an installer, then it gets the permission.
8670 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8671 && pkg.packageName.equals(mRequiredVerifierPackage)) {
8672 // If this permission is to be granted to the system verifier and
8673 // this app is a verifier, then it gets the permission.
8676 if (!allowed && (bp.protectionLevel
8677 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8678 && isSystemApp(pkg)) {
8679 // Any pre-installed system app is allowed to get this permission.
8682 if (!allowed && (bp.protectionLevel
8683 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8684 // For development permissions, a development permission
8685 // is granted only if it was already granted.
8686 allowed = origPermissions.hasInstallPermission(perm);
8692 final class ActivityIntentResolver
8693 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8694 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8695 boolean defaultOnly, int userId) {
8696 if (!sUserManager.exists(userId)) return null;
8697 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8698 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8701 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8703 if (!sUserManager.exists(userId)) return null;
8705 return super.queryIntent(intent, resolvedType,
8706 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8709 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8710 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8711 if (!sUserManager.exists(userId)) return null;
8712 if (packageActivities == null) {
8716 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8717 final int N = packageActivities.size();
8718 ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8719 new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8721 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8722 for (int i = 0; i < N; ++i) {
8723 intentFilters = packageActivities.get(i).intents;
8724 if (intentFilters != null && intentFilters.size() > 0) {
8725 PackageParser.ActivityIntentInfo[] array =
8726 new PackageParser.ActivityIntentInfo[intentFilters.size()];
8727 intentFilters.toArray(array);
8731 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8735 * Finds a privileged activity that matches the specified activity names.
8737 private PackageParser.Activity findMatchingActivity(
8738 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
8739 for (PackageParser.Activity sysActivity : activityList) {
8740 if (sysActivity.info.name.equals(activityInfo.name)) {
8743 if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
8746 if (sysActivity.info.targetActivity != null) {
8747 if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
8750 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
8758 public class IterGenerator<E> {
8759 public Iterator<E> generate(ActivityIntentInfo info) {
8764 public class ActionIterGenerator extends IterGenerator<String> {
8766 public Iterator<String> generate(ActivityIntentInfo info) {
8767 return info.actionsIterator();
8771 public class CategoriesIterGenerator extends IterGenerator<String> {
8773 public Iterator<String> generate(ActivityIntentInfo info) {
8774 return info.categoriesIterator();
8778 public class SchemesIterGenerator extends IterGenerator<String> {
8780 public Iterator<String> generate(ActivityIntentInfo info) {
8781 return info.schemesIterator();
8785 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
8787 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
8788 return info.authoritiesIterator();
8793 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
8794 * MODIFIED. Do not pass in a list that should not be changed.
8796 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
8797 IterGenerator<T> generator, Iterator<T> searchIterator) {
8798 // loop through the set of actions; every one must be found in the intent filter
8799 while (searchIterator.hasNext()) {
8800 // we must have at least one filter in the list to consider a match
8801 if (intentList.size() == 0) {
8805 final T searchAction = searchIterator.next();
8807 // loop through the set of intent filters
8808 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
8809 while (intentIter.hasNext()) {
8810 final ActivityIntentInfo intentInfo = intentIter.next();
8811 boolean selectionFound = false;
8813 // loop through the intent filter's selection criteria; at least one
8814 // of them must match the searched criteria
8815 final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
8816 while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
8817 final T intentSelection = intentSelectionIter.next();
8818 if (intentSelection != null && intentSelection.equals(searchAction)) {
8819 selectionFound = true;
8824 // the selection criteria wasn't found in this filter's set; this filter
8825 // is not a potential match
8826 if (!selectionFound) {
8827 intentIter.remove();
8834 * Adjusts the priority of the given intent filter according to policy.
8837 * <li>The priority for unbundled updates to system applications is capped to the
8838 * priority defined on the system partition</li>
8841 private void adjustPriority(
8842 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
8843 // nothing to do; priority is fine as-is
8844 if (intent.getPriority() <= 0) {
8848 final ActivityInfo activityInfo = intent.activity.info;
8849 final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
8851 final boolean systemApp = applicationInfo.isSystemApp();
8853 // non-system applications can never define a priority >0
8854 Slog.w(TAG, "Non-system app; cap priority to 0;"
8855 + " package: " + applicationInfo.packageName
8856 + " activity: " + intent.activity.className
8857 + " origPrio: " + intent.getPriority());
8858 intent.setPriority(0);
8862 if (systemActivities == null) {
8863 // the system package is not disabled; we're parsing the system partition
8864 // apps on the system image get whatever priority they request
8868 // system app unbundled update ... try to find the same activity
8869 final PackageParser.Activity foundActivity =
8870 findMatchingActivity(systemActivities, activityInfo);
8871 if (foundActivity == null) {
8872 // this is a new activity; it cannot obtain >0 priority
8873 if (DEBUG_FILTERS) {
8874 Slog.i(TAG, "New activity; cap priority to 0;"
8875 + " package: " + applicationInfo.packageName
8876 + " activity: " + intent.activity.className
8877 + " origPrio: " + intent.getPriority());
8879 intent.setPriority(0);
8883 // found activity, now check for filter equivalence
8885 // a shallow copy is enough; we modify the list, not its contents
8886 final List<ActivityIntentInfo> intentListCopy =
8887 new ArrayList<>(foundActivity.intents);
8888 final List<ActivityIntentInfo> foundFilters = findFilters(intent);
8890 // find matching action subsets
8891 final Iterator<String> actionsIterator = intent.actionsIterator();
8892 if (actionsIterator != null) {
8893 getIntentListSubset(
8894 intentListCopy, new ActionIterGenerator(), actionsIterator);
8895 if (intentListCopy.size() == 0) {
8896 // no more intents to match; we're not equivalent
8897 if (DEBUG_FILTERS) {
8898 Slog.i(TAG, "Mismatched action; cap priority to 0;"
8899 + " package: " + applicationInfo.packageName
8900 + " activity: " + intent.activity.className
8901 + " origPrio: " + intent.getPriority());
8903 intent.setPriority(0);
8908 // find matching category subsets
8909 final Iterator<String> categoriesIterator = intent.categoriesIterator();
8910 if (categoriesIterator != null) {
8911 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
8912 categoriesIterator);
8913 if (intentListCopy.size() == 0) {
8914 // no more intents to match; we're not equivalent
8915 if (DEBUG_FILTERS) {
8916 Slog.i(TAG, "Mismatched category; cap priority to 0;"
8917 + " package: " + applicationInfo.packageName
8918 + " activity: " + intent.activity.className
8919 + " origPrio: " + intent.getPriority());
8921 intent.setPriority(0);
8926 // find matching schemes subsets
8927 final Iterator<String> schemesIterator = intent.schemesIterator();
8928 if (schemesIterator != null) {
8929 getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
8931 if (intentListCopy.size() == 0) {
8932 // no more intents to match; we're not equivalent
8933 if (DEBUG_FILTERS) {
8934 Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
8935 + " package: " + applicationInfo.packageName
8936 + " activity: " + intent.activity.className
8937 + " origPrio: " + intent.getPriority());
8939 intent.setPriority(0);
8944 // find matching authorities subsets
8945 final Iterator<IntentFilter.AuthorityEntry>
8946 authoritiesIterator = intent.authoritiesIterator();
8947 if (authoritiesIterator != null) {
8948 getIntentListSubset(intentListCopy,
8949 new AuthoritiesIterGenerator(),
8950 authoritiesIterator);
8951 if (intentListCopy.size() == 0) {
8952 // no more intents to match; we're not equivalent
8953 if (DEBUG_FILTERS) {
8954 Slog.i(TAG, "Mismatched authority; cap priority to 0;"
8955 + " package: " + applicationInfo.packageName
8956 + " activity: " + intent.activity.className
8957 + " origPrio: " + intent.getPriority());
8959 intent.setPriority(0);
8964 // we found matching filter(s); app gets the max priority of all intents
8965 int cappedPriority = 0;
8966 for (int i = intentListCopy.size() - 1; i >= 0; --i) {
8967 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
8969 if (intent.getPriority() > cappedPriority) {
8970 if (DEBUG_FILTERS) {
8971 Slog.i(TAG, "Found matching filter(s);"
8972 + " cap priority to " + cappedPriority + ";"
8973 + " package: " + applicationInfo.packageName
8974 + " activity: " + intent.activity.className
8975 + " origPrio: " + intent.getPriority());
8977 intent.setPriority(cappedPriority);
8980 // all this for nothing; the requested priority was <= what was on the system
8983 public final void addActivity(PackageParser.Activity a, String type) {
8984 final boolean systemApp = a.info.applicationInfo.isSystemApp();
8985 mActivities.put(a.getComponentName(), a);
8986 if (DEBUG_SHOW_INFO)
8988 TAG, " " + type + " " +
8989 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8990 if (DEBUG_SHOW_INFO)
8991 Log.v(TAG, " Class=" + a.info.name);
8992 final int NI = a.intents.size();
8993 for (int j=0; j<NI; j++) {
8994 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8995 if ("activity".equals(type)) {
8996 final PackageSetting ps =
8997 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
8998 final List<PackageParser.Activity> systemActivities =
8999 ps != null && ps.pkg != null ? ps.pkg.activities : null;
9000 adjustPriority(systemActivities, intent);
9002 if (DEBUG_SHOW_INFO) {
9003 Log.v(TAG, " IntentFilter:");
9004 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
9006 if (!intent.debugCheck()) {
9007 Log.w(TAG, "==> For Activity " + a.info.name);
9013 public final void removeActivity(PackageParser.Activity a, String type) {
9014 mActivities.remove(a.getComponentName());
9015 if (DEBUG_SHOW_INFO) {
9016 Log.v(TAG, " " + type + " "
9017 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9018 : a.info.name) + ":");
9019 Log.v(TAG, " Class=" + a.info.name);
9021 final int NI = a.intents.size();
9022 for (int j=0; j<NI; j++) {
9023 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9024 if (DEBUG_SHOW_INFO) {
9025 Log.v(TAG, " IntentFilter:");
9026 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
9028 removeFilter(intent);
9033 protected boolean allowFilterResult(
9034 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9035 ActivityInfo filterAi = filter.activity.info;
9036 for (int i=dest.size()-1; i>=0; i--) {
9037 ActivityInfo destAi = dest.get(i).activityInfo;
9038 if (destAi.name == filterAi.name
9039 && destAi.packageName == filterAi.packageName) {
9047 protected ActivityIntentInfo[] newArray(int size) {
9048 return new ActivityIntentInfo[size];
9052 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9053 if (!sUserManager.exists(userId)) return true;
9054 PackageParser.Package p = filter.activity.owner;
9056 PackageSetting ps = (PackageSetting)p.mExtras;
9058 // System apps are never considered stopped for purposes of
9059 // filtering, because there may be no way for the user to
9060 // actually re-launch them.
9061 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9062 && ps.getStopped(userId);
9069 protected boolean isPackageForFilter(String packageName,
9070 PackageParser.ActivityIntentInfo info) {
9071 return packageName.equals(info.activity.owner.packageName);
9075 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9076 int match, int userId) {
9077 if (!sUserManager.exists(userId)) return null;
9078 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
9081 final PackageParser.Activity activity = info.activity;
9082 if (mSafeMode && (activity.info.applicationInfo.flags
9083 &ApplicationInfo.FLAG_SYSTEM) == 0) {
9086 PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9090 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9091 ps.readUserState(userId), userId);
9095 final ResolveInfo res = new ResolveInfo();
9096 res.activityInfo = ai;
9097 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9101 res.handleAllWebDataURI = info.handleAllWebDataURI();
9103 res.priority = info.getPriority();
9104 res.preferredOrder = activity.owner.mPreferredOrder;
9105 //System.out.println("Result: " + res.activityInfo.className +
9106 // " = " + res.priority);
9108 res.isDefault = info.hasDefault;
9109 res.labelRes = info.labelRes;
9110 res.nonLocalizedLabel = info.nonLocalizedLabel;
9111 if (userNeedsBadging(userId)) {
9112 res.noResourceId = true;
9114 res.icon = info.icon;
9116 res.iconResourceId = info.icon;
9117 res.system = res.activityInfo.applicationInfo.isSystemApp();
9122 protected void sortResults(List<ResolveInfo> results) {
9123 Collections.sort(results, mResolvePrioritySorter);
9127 protected void dumpFilter(PrintWriter out, String prefix,
9128 PackageParser.ActivityIntentInfo filter) {
9129 out.print(prefix); out.print(
9130 Integer.toHexString(System.identityHashCode(filter.activity)));
9132 filter.activity.printComponentShortName(out);
9133 out.print(" filter ");
9134 out.println(Integer.toHexString(System.identityHashCode(filter)));
9138 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9139 return filter.activity;
9142 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9143 PackageParser.Activity activity = (PackageParser.Activity)label;
9144 out.print(prefix); out.print(
9145 Integer.toHexString(System.identityHashCode(activity)));
9147 activity.printComponentShortName(out);
9149 out.print(" ("); out.print(count); out.print(" filters)");
9154 // Keys are String (activity class name), values are Activity.
9155 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9156 = new ArrayMap<ComponentName, PackageParser.Activity>();
9160 private final class ServiceIntentResolver
9161 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9162 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9163 boolean defaultOnly, int userId) {
9164 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9165 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9168 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9170 if (!sUserManager.exists(userId)) return null;
9172 return super.queryIntent(intent, resolvedType,
9173 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9176 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9177 int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9178 if (!sUserManager.exists(userId)) return null;
9179 if (packageServices == null) {
9183 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9184 final int N = packageServices.size();
9185 ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9186 new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9188 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9189 for (int i = 0; i < N; ++i) {
9190 intentFilters = packageServices.get(i).intents;
9191 if (intentFilters != null && intentFilters.size() > 0) {
9192 PackageParser.ServiceIntentInfo[] array =
9193 new PackageParser.ServiceIntentInfo[intentFilters.size()];
9194 intentFilters.toArray(array);
9198 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9201 public final void addService(PackageParser.Service s) {
9202 mServices.put(s.getComponentName(), s);
9203 if (DEBUG_SHOW_INFO) {
9205 + (s.info.nonLocalizedLabel != null
9206 ? s.info.nonLocalizedLabel : s.info.name) + ":");
9207 Log.v(TAG, " Class=" + s.info.name);
9209 final int NI = s.intents.size();
9211 for (j=0; j<NI; j++) {
9212 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9213 if (DEBUG_SHOW_INFO) {
9214 Log.v(TAG, " IntentFilter:");
9215 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
9217 if (!intent.debugCheck()) {
9218 Log.w(TAG, "==> For Service " + s.info.name);
9224 public final void removeService(PackageParser.Service s) {
9225 mServices.remove(s.getComponentName());
9226 if (DEBUG_SHOW_INFO) {
9227 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null
9228 ? s.info.nonLocalizedLabel : s.info.name) + ":");
9229 Log.v(TAG, " Class=" + s.info.name);
9231 final int NI = s.intents.size();
9233 for (j=0; j<NI; j++) {
9234 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9235 if (DEBUG_SHOW_INFO) {
9236 Log.v(TAG, " IntentFilter:");
9237 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
9239 removeFilter(intent);
9244 protected boolean allowFilterResult(
9245 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9246 ServiceInfo filterSi = filter.service.info;
9247 for (int i=dest.size()-1; i>=0; i--) {
9248 ServiceInfo destAi = dest.get(i).serviceInfo;
9249 if (destAi.name == filterSi.name
9250 && destAi.packageName == filterSi.packageName) {
9258 protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9259 return new PackageParser.ServiceIntentInfo[size];
9263 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9264 if (!sUserManager.exists(userId)) return true;
9265 PackageParser.Package p = filter.service.owner;
9267 PackageSetting ps = (PackageSetting)p.mExtras;
9269 // System apps are never considered stopped for purposes of
9270 // filtering, because there may be no way for the user to
9271 // actually re-launch them.
9272 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9273 && ps.getStopped(userId);
9280 protected boolean isPackageForFilter(String packageName,
9281 PackageParser.ServiceIntentInfo info) {
9282 return packageName.equals(info.service.owner.packageName);
9286 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9287 int match, int userId) {
9288 if (!sUserManager.exists(userId)) return null;
9289 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9290 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9293 final PackageParser.Service service = info.service;
9294 if (mSafeMode && (service.info.applicationInfo.flags
9295 &ApplicationInfo.FLAG_SYSTEM) == 0) {
9298 PackageSetting ps = (PackageSetting) service.owner.mExtras;
9302 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9303 ps.readUserState(userId), userId);
9307 final ResolveInfo res = new ResolveInfo();
9308 res.serviceInfo = si;
9309 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9310 res.filter = filter;
9312 res.priority = info.getPriority();
9313 res.preferredOrder = service.owner.mPreferredOrder;
9315 res.isDefault = info.hasDefault;
9316 res.labelRes = info.labelRes;
9317 res.nonLocalizedLabel = info.nonLocalizedLabel;
9318 res.icon = info.icon;
9319 res.system = res.serviceInfo.applicationInfo.isSystemApp();
9324 protected void sortResults(List<ResolveInfo> results) {
9325 Collections.sort(results, mResolvePrioritySorter);
9329 protected void dumpFilter(PrintWriter out, String prefix,
9330 PackageParser.ServiceIntentInfo filter) {
9331 out.print(prefix); out.print(
9332 Integer.toHexString(System.identityHashCode(filter.service)));
9334 filter.service.printComponentShortName(out);
9335 out.print(" filter ");
9336 out.println(Integer.toHexString(System.identityHashCode(filter)));
9340 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9341 return filter.service;
9344 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9345 PackageParser.Service service = (PackageParser.Service)label;
9346 out.print(prefix); out.print(
9347 Integer.toHexString(System.identityHashCode(service)));
9349 service.printComponentShortName(out);
9351 out.print(" ("); out.print(count); out.print(" filters)");
9356 // List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9357 // final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9358 // final List<ResolveInfo> retList = Lists.newArrayList();
9359 // while (i.hasNext()) {
9360 // final ResolveInfo resolveInfo = (ResolveInfo) i;
9361 // if (isEnabledLP(resolveInfo.serviceInfo)) {
9362 // retList.add(resolveInfo);
9368 // Keys are String (activity class name), values are Activity.
9369 private final ArrayMap<ComponentName, PackageParser.Service> mServices
9370 = new ArrayMap<ComponentName, PackageParser.Service>();
9374 private final class ProviderIntentResolver
9375 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9376 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9377 boolean defaultOnly, int userId) {
9378 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9379 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9382 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9384 if (!sUserManager.exists(userId))
9387 return super.queryIntent(intent, resolvedType,
9388 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9391 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9392 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9393 if (!sUserManager.exists(userId))
9395 if (packageProviders == null) {
9399 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9400 final int N = packageProviders.size();
9401 ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9402 new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9404 ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9405 for (int i = 0; i < N; ++i) {
9406 intentFilters = packageProviders.get(i).intents;
9407 if (intentFilters != null && intentFilters.size() > 0) {
9408 PackageParser.ProviderIntentInfo[] array =
9409 new PackageParser.ProviderIntentInfo[intentFilters.size()];
9410 intentFilters.toArray(array);
9414 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9417 public final void addProvider(PackageParser.Provider p) {
9418 if (mProviders.containsKey(p.getComponentName())) {
9419 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9423 mProviders.put(p.getComponentName(), p);
9424 if (DEBUG_SHOW_INFO) {
9426 + (p.info.nonLocalizedLabel != null
9427 ? p.info.nonLocalizedLabel : p.info.name) + ":");
9428 Log.v(TAG, " Class=" + p.info.name);
9430 final int NI = p.intents.size();
9432 for (j = 0; j < NI; j++) {
9433 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9434 if (DEBUG_SHOW_INFO) {
9435 Log.v(TAG, " IntentFilter:");
9436 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
9438 if (!intent.debugCheck()) {
9439 Log.w(TAG, "==> For Provider " + p.info.name);
9445 public final void removeProvider(PackageParser.Provider p) {
9446 mProviders.remove(p.getComponentName());
9447 if (DEBUG_SHOW_INFO) {
9448 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null
9449 ? p.info.nonLocalizedLabel : p.info.name) + ":");
9450 Log.v(TAG, " Class=" + p.info.name);
9452 final int NI = p.intents.size();
9454 for (j = 0; j < NI; j++) {
9455 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9456 if (DEBUG_SHOW_INFO) {
9457 Log.v(TAG, " IntentFilter:");
9458 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
9460 removeFilter(intent);
9465 protected boolean allowFilterResult(
9466 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9467 ProviderInfo filterPi = filter.provider.info;
9468 for (int i = dest.size() - 1; i >= 0; i--) {
9469 ProviderInfo destPi = dest.get(i).providerInfo;
9470 if (destPi.name == filterPi.name
9471 && destPi.packageName == filterPi.packageName) {
9479 protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9480 return new PackageParser.ProviderIntentInfo[size];
9484 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9485 if (!sUserManager.exists(userId))
9487 PackageParser.Package p = filter.provider.owner;
9489 PackageSetting ps = (PackageSetting) p.mExtras;
9491 // System apps are never considered stopped for purposes of
9492 // filtering, because there may be no way for the user to
9493 // actually re-launch them.
9494 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9495 && ps.getStopped(userId);
9502 protected boolean isPackageForFilter(String packageName,
9503 PackageParser.ProviderIntentInfo info) {
9504 return packageName.equals(info.provider.owner.packageName);
9508 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9509 int match, int userId) {
9510 if (!sUserManager.exists(userId))
9512 final PackageParser.ProviderIntentInfo info = filter;
9513 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9516 final PackageParser.Provider provider = info.provider;
9517 if (mSafeMode && (provider.info.applicationInfo.flags
9518 & ApplicationInfo.FLAG_SYSTEM) == 0) {
9521 PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9525 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9526 ps.readUserState(userId), userId);
9530 final ResolveInfo res = new ResolveInfo();
9531 res.providerInfo = pi;
9532 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9533 res.filter = filter;
9535 res.priority = info.getPriority();
9536 res.preferredOrder = provider.owner.mPreferredOrder;
9538 res.isDefault = info.hasDefault;
9539 res.labelRes = info.labelRes;
9540 res.nonLocalizedLabel = info.nonLocalizedLabel;
9541 res.icon = info.icon;
9542 res.system = res.providerInfo.applicationInfo.isSystemApp();
9547 protected void sortResults(List<ResolveInfo> results) {
9548 Collections.sort(results, mResolvePrioritySorter);
9552 protected void dumpFilter(PrintWriter out, String prefix,
9553 PackageParser.ProviderIntentInfo filter) {
9556 Integer.toHexString(System.identityHashCode(filter.provider)));
9558 filter.provider.printComponentShortName(out);
9559 out.print(" filter ");
9560 out.println(Integer.toHexString(System.identityHashCode(filter)));
9564 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9565 return filter.provider;
9568 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9569 PackageParser.Provider provider = (PackageParser.Provider)label;
9570 out.print(prefix); out.print(
9571 Integer.toHexString(System.identityHashCode(provider)));
9573 provider.printComponentShortName(out);
9575 out.print(" ("); out.print(count); out.print(" filters)");
9580 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9581 = new ArrayMap<ComponentName, PackageParser.Provider>();
9585 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9586 new Comparator<ResolveInfo>() {
9587 public int compare(ResolveInfo r1, ResolveInfo r2) {
9588 int v1 = r1.priority;
9589 int v2 = r2.priority;
9590 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9592 return (v1 > v2) ? -1 : 1;
9594 v1 = r1.preferredOrder;
9595 v2 = r2.preferredOrder;
9597 return (v1 > v2) ? -1 : 1;
9599 if (r1.isDefault != r2.isDefault) {
9600 return r1.isDefault ? -1 : 1;
9604 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9606 return (v1 > v2) ? -1 : 1;
9608 if (r1.system != r2.system) {
9609 return r1.system ? -1 : 1;
9615 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9616 new Comparator<ProviderInfo>() {
9617 public int compare(ProviderInfo p1, ProviderInfo p2) {
9618 final int v1 = p1.initOrder;
9619 final int v2 = p2.initOrder;
9620 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9624 final void sendPackageBroadcast(final String action, final String pkg,
9625 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9626 final int[] userIds) {
9627 mHandler.post(new Runnable() {
9631 final IActivityManager am = ActivityManagerNative.getDefault();
9632 if (am == null) return;
9633 final int[] resolvedUserIds;
9634 if (userIds == null) {
9635 resolvedUserIds = am.getRunningUserIds();
9637 resolvedUserIds = userIds;
9639 for (int id : resolvedUserIds) {
9640 final Intent intent = new Intent(action,
9641 pkg != null ? Uri.fromParts("package", pkg, null) : null);
9642 if (extras != null) {
9643 intent.putExtras(extras);
9645 if (targetPkg != null) {
9646 intent.setPackage(targetPkg);
9648 // Modify the UID when posting to other users
9649 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9650 if (uid > 0 && UserHandle.getUserId(uid) != id) {
9651 uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9652 intent.putExtra(Intent.EXTRA_UID, uid);
9654 intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9655 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9656 if (DEBUG_BROADCASTS) {
9657 RuntimeException here = new RuntimeException("here");
9658 here.fillInStackTrace();
9659 Slog.d(TAG, "Sending to user " + id + ": "
9660 + intent.toShortString(false, true, false, false)
9661 + " " + intent.getExtras(), here);
9663 am.broadcastIntent(null, intent, null, finishedReceiver,
9664 0, null, null, null, android.app.AppOpsManager.OP_NONE,
9665 null, finishedReceiver != null, false, id);
9667 } catch (RemoteException ex) {
9674 * Check if the external storage media is available. This is true if there
9675 * is a mounted external storage medium or if the external storage is
9678 private boolean isExternalMediaAvailable() {
9679 return mMediaMounted || Environment.isExternalStorageEmulated();
9683 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9685 synchronized (mPackages) {
9686 if (!isExternalMediaAvailable()) {
9687 // If the external storage is no longer mounted at this point,
9688 // the caller may not have been able to delete all of this
9689 // packages files and can not delete any more. Bail.
9692 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9693 if (lastPackage != null) {
9694 pkgs.remove(lastPackage);
9696 if (pkgs.size() > 0) {
9703 void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9704 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9705 userId, andCode ? 1 : 0, packageName);
9709 if (mPostSystemReadyMessages == null) {
9710 mPostSystemReadyMessages = new ArrayList<>();
9712 mPostSystemReadyMessages.add(msg);
9716 void startCleaningPackages() {
9718 synchronized (mPackages) {
9719 if (!isExternalMediaAvailable()) {
9722 if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9726 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9727 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9728 IActivityManager am = ActivityManagerNative.getDefault();
9731 am.startService(null, intent, null, mContext.getOpPackageName(),
9732 UserHandle.USER_OWNER);
9733 } catch (RemoteException e) {
9739 public void installPackage(String originPath, IPackageInstallObserver2 observer,
9740 int installFlags, String installerPackageName, VerificationParams verificationParams,
9741 String packageAbiOverride) {
9742 installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9743 verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9747 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9748 int installFlags, String installerPackageName, VerificationParams verificationParams,
9749 String packageAbiOverride, int userId) {
9750 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9752 final int callingUid = Binder.getCallingUid();
9753 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9755 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9757 if (observer != null) {
9758 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9760 } catch (RemoteException re) {
9765 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9766 installFlags |= PackageManager.INSTALL_FROM_ADB;
9769 // Caller holds INSTALL_PACKAGES permission, so we're less strict
9770 // about installerPackageName.
9772 installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9773 installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9777 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9778 user = UserHandle.ALL;
9780 user = new UserHandle(userId);
9783 // Only system components can circumvent runtime permissions when installing.
9784 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9785 && mContext.checkCallingOrSelfPermission(Manifest.permission
9786 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9787 throw new SecurityException("You need the "
9788 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9789 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9792 verificationParams.setInstallerUid(callingUid);
9794 final File originFile = new File(originPath);
9795 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9797 final Message msg = mHandler.obtainMessage(INIT_COPY);
9798 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9799 null, verificationParams, user, packageAbiOverride, null);
9800 mHandler.sendMessage(msg);
9803 void installStage(String packageName, File stagedDir, String stagedCid,
9804 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9805 String installerPackageName, int installerUid, UserHandle user) {
9806 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9807 params.referrerUri, installerUid, null);
9808 verifParams.setInstallerUid(installerUid);
9810 final OriginInfo origin;
9811 if (stagedDir != null) {
9812 origin = OriginInfo.fromStagedFile(stagedDir);
9814 origin = OriginInfo.fromStagedContainer(stagedCid);
9817 final Message msg = mHandler.obtainMessage(INIT_COPY);
9818 msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9819 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9820 params.grantedRuntimePermissions);
9821 mHandler.sendMessage(msg);
9824 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9825 Bundle extras = new Bundle(1);
9826 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9828 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9829 packageName, extras, null, null, new int[] {userId});
9831 IActivityManager am = ActivityManagerNative.getDefault();
9832 final boolean isSystem =
9833 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9834 if (isSystem && am.isUserRunning(userId, false)) {
9835 // The just-installed/enabled app is bundled on the system, so presumed
9836 // to be able to run automatically without needing an explicit launch.
9837 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9838 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9839 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9840 .setPackage(packageName);
9841 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9842 android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9844 } catch (RemoteException e) {
9846 Slog.w(TAG, "Unable to bootstrap installed package", e);
9851 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9853 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9854 PackageSetting pkgSetting;
9855 final int uid = Binder.getCallingUid();
9856 enforceCrossUserPermission(uid, userId, true, true,
9857 "setApplicationHiddenSetting for user " + userId);
9859 if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9860 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9864 long callingId = Binder.clearCallingIdentity();
9866 boolean sendAdded = false;
9867 boolean sendRemoved = false;
9869 synchronized (mPackages) {
9870 pkgSetting = mSettings.mPackages.get(packageName);
9871 if (pkgSetting == null) {
9874 if (pkgSetting.getHidden(userId) != hidden) {
9875 pkgSetting.setHidden(hidden, userId);
9876 mSettings.writePackageRestrictionsLPr(userId);
9885 sendPackageAddedForUser(packageName, pkgSetting, userId);
9889 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9891 sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9895 Binder.restoreCallingIdentity(callingId);
9900 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9902 final PackageRemovedInfo info = new PackageRemovedInfo();
9903 info.removedPackage = packageName;
9904 info.removedUsers = new int[] {userId};
9905 info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9906 info.sendBroadcast(false, false, false);
9910 * Returns true if application is not found or there was an error. Otherwise it returns
9911 * the hidden state of the package for the given user.
9914 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9915 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9916 enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9917 false, "getApplicationHidden for user " + userId);
9918 PackageSetting pkgSetting;
9919 long callingId = Binder.clearCallingIdentity();
9922 synchronized (mPackages) {
9923 pkgSetting = mSettings.mPackages.get(packageName);
9924 if (pkgSetting == null) {
9927 return pkgSetting.getHidden(userId);
9930 Binder.restoreCallingIdentity(callingId);
9938 public int installExistingPackageAsUser(String packageName, int userId) {
9939 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9941 PackageSetting pkgSetting;
9942 final int uid = Binder.getCallingUid();
9943 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9945 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9946 return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9949 long callingId = Binder.clearCallingIdentity();
9951 boolean sendAdded = false;
9954 synchronized (mPackages) {
9955 pkgSetting = mSettings.mPackages.get(packageName);
9956 if (pkgSetting == null) {
9957 return PackageManager.INSTALL_FAILED_INVALID_URI;
9959 if (!pkgSetting.getInstalled(userId)) {
9960 pkgSetting.setInstalled(true, userId);
9961 pkgSetting.setHidden(false, userId);
9962 mSettings.writePackageRestrictionsLPr(userId);
9968 sendPackageAddedForUser(packageName, pkgSetting, userId);
9971 Binder.restoreCallingIdentity(callingId);
9974 return PackageManager.INSTALL_SUCCEEDED;
9977 boolean isUserRestricted(int userId, String restrictionKey) {
9978 Bundle restrictions = sUserManager.getUserRestrictions(userId);
9979 if (restrictions.getBoolean(restrictionKey, false)) {
9980 Log.w(TAG, "User is restricted: " + restrictionKey);
9987 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9988 mContext.enforceCallingOrSelfPermission(
9989 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9990 "Only package verification agents can verify applications");
9992 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9993 final PackageVerificationResponse response = new PackageVerificationResponse(
9994 verificationCode, Binder.getCallingUid());
9997 mHandler.sendMessage(msg);
10001 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10002 long millisecondsToDelay) {
10003 mContext.enforceCallingOrSelfPermission(
10004 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10005 "Only package verification agents can extend verification timeouts");
10007 final PackageVerificationState state = mPendingVerification.get(id);
10008 final PackageVerificationResponse response = new PackageVerificationResponse(
10009 verificationCodeAtTimeout, Binder.getCallingUid());
10011 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10012 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10014 if (millisecondsToDelay < 0) {
10015 millisecondsToDelay = 0;
10017 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10018 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10019 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10022 if ((state != null) && !state.timeoutExtended()) {
10023 state.extendTimeout();
10025 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10027 msg.obj = response;
10028 mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10032 private void broadcastPackageVerified(int verificationId, Uri packageUri,
10033 int verificationCode, UserHandle user) {
10034 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10035 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10036 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10037 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10038 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10040 mContext.sendBroadcastAsUser(intent, user,
10041 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10044 private ComponentName matchComponentForVerifier(String packageName,
10045 List<ResolveInfo> receivers) {
10046 ActivityInfo targetReceiver = null;
10048 final int NR = receivers.size();
10049 for (int i = 0; i < NR; i++) {
10050 final ResolveInfo info = receivers.get(i);
10051 if (info.activityInfo == null) {
10055 if (packageName.equals(info.activityInfo.packageName)) {
10056 targetReceiver = info.activityInfo;
10061 if (targetReceiver == null) {
10065 return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10068 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10069 List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10070 if (pkgInfo.verifiers.length == 0) {
10074 final int N = pkgInfo.verifiers.length;
10075 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10076 for (int i = 0; i < N; i++) {
10077 final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10079 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10081 if (comp == null) {
10085 final int verifierUid = getUidForVerifier(verifierInfo);
10086 if (verifierUid == -1) {
10090 if (DEBUG_VERIFY) {
10091 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10092 + " with the correct signature");
10094 sufficientVerifiers.add(comp);
10095 verificationState.addSufficientVerifier(verifierUid);
10098 return sufficientVerifiers;
10101 private int getUidForVerifier(VerifierInfo verifierInfo) {
10102 synchronized (mPackages) {
10103 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10106 } else if (pkg.mSignatures.length != 1) {
10107 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10108 + " has more than one signature; ignoring");
10113 * If the public key of the package's signature does not match
10114 * our expected public key, then this is a different package and
10118 final byte[] expectedPublicKey;
10120 final Signature verifierSig = pkg.mSignatures[0];
10121 final PublicKey publicKey = verifierSig.getPublicKey();
10122 expectedPublicKey = publicKey.getEncoded();
10123 } catch (CertificateException e) {
10127 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10129 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10130 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10131 + " does not have the expected public key; ignoring");
10135 return pkg.applicationInfo.uid;
10140 public void finishPackageInstall(int token) {
10141 enforceSystemOrRoot("Only the system is allowed to finish installs");
10143 if (DEBUG_INSTALL) {
10144 Slog.v(TAG, "BM finishing package install for " + token);
10147 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10148 mHandler.sendMessage(msg);
10152 * Get the verification agent timeout.
10154 * @return verification timeout in milliseconds
10156 private long getVerificationTimeout() {
10157 return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10158 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10159 DEFAULT_VERIFICATION_TIMEOUT);
10163 * Get the default verification agent response code.
10165 * @return default verification response code
10167 private int getDefaultVerificationResponse() {
10168 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10169 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10170 DEFAULT_VERIFICATION_RESPONSE);
10174 * Check whether or not package verification has been enabled.
10176 * @return true if verification should be performed
10178 private boolean isVerificationEnabled(int userId, int installFlags) {
10179 if (!DEFAULT_VERIFY_ENABLE) {
10183 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10185 // Check if installing from ADB
10186 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10187 // Do not run verification in a test harness environment
10188 if (ActivityManager.isRunningInTestHarness()) {
10191 if (ensureVerifyAppsEnabled) {
10194 // Check if the developer does not want package verification for ADB installs
10195 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10196 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10201 if (ensureVerifyAppsEnabled) {
10205 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10206 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10210 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10211 throws RemoteException {
10212 mContext.enforceCallingOrSelfPermission(
10213 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10214 "Only intentfilter verification agents can verify applications");
10216 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10217 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10218 Binder.getCallingUid(), verificationCode, failedDomains);
10220 msg.obj = response;
10221 mHandler.sendMessage(msg);
10225 public int getIntentVerificationStatus(String packageName, int userId) {
10226 synchronized (mPackages) {
10227 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10232 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10233 mContext.enforceCallingOrSelfPermission(
10234 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10236 boolean result = false;
10237 synchronized (mPackages) {
10238 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10241 scheduleWritePackageRestrictionsLocked(userId);
10247 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10248 synchronized (mPackages) {
10249 return mSettings.getIntentFilterVerificationsLPr(packageName);
10254 public List<IntentFilter> getAllIntentFilters(String packageName) {
10255 if (TextUtils.isEmpty(packageName)) {
10256 return Collections.<IntentFilter>emptyList();
10258 synchronized (mPackages) {
10259 PackageParser.Package pkg = mPackages.get(packageName);
10260 if (pkg == null || pkg.activities == null) {
10261 return Collections.<IntentFilter>emptyList();
10263 final int count = pkg.activities.size();
10264 ArrayList<IntentFilter> result = new ArrayList<>();
10265 for (int n=0; n<count; n++) {
10266 PackageParser.Activity activity = pkg.activities.get(n);
10267 if (activity.intents != null || activity.intents.size() > 0) {
10268 result.addAll(activity.intents);
10276 public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10277 mContext.enforceCallingOrSelfPermission(
10278 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10280 synchronized (mPackages) {
10281 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10282 if (packageName != null) {
10283 result |= updateIntentVerificationStatus(packageName,
10284 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10286 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10287 packageName, userId);
10294 public String getDefaultBrowserPackageName(int userId) {
10295 synchronized (mPackages) {
10296 return mSettings.getDefaultBrowserPackageNameLPw(userId);
10301 * Get the "allow unknown sources" setting.
10303 * @return the current "allow unknown sources" setting
10305 private int getUnknownSourcesSettings() {
10306 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10307 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10312 public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10313 final int uid = Binder.getCallingUid();
10315 synchronized (mPackages) {
10316 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10317 if (targetPackageSetting == null) {
10318 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10321 PackageSetting installerPackageSetting;
10322 if (installerPackageName != null) {
10323 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10324 if (installerPackageSetting == null) {
10325 throw new IllegalArgumentException("Unknown installer package: "
10326 + installerPackageName);
10329 installerPackageSetting = null;
10332 Signature[] callerSignature;
10333 Object obj = mSettings.getUserIdLPr(uid);
10335 if (obj instanceof SharedUserSetting) {
10336 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10337 } else if (obj instanceof PackageSetting) {
10338 callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10340 throw new SecurityException("Bad object " + obj + " for uid " + uid);
10343 throw new SecurityException("Unknown calling uid " + uid);
10346 // Verify: can't set installerPackageName to a package that is
10347 // not signed with the same cert as the caller.
10348 if (installerPackageSetting != null) {
10349 if (compareSignatures(callerSignature,
10350 installerPackageSetting.signatures.mSignatures)
10351 != PackageManager.SIGNATURE_MATCH) {
10352 throw new SecurityException(
10353 "Caller does not have same cert as new installer package "
10354 + installerPackageName);
10358 // Verify: if target already has an installer package, it must
10359 // be signed with the same cert as the caller.
10360 if (targetPackageSetting.installerPackageName != null) {
10361 PackageSetting setting = mSettings.mPackages.get(
10362 targetPackageSetting.installerPackageName);
10363 // If the currently set package isn't valid, then it's always
10364 // okay to change it.
10365 if (setting != null) {
10366 if (compareSignatures(callerSignature,
10367 setting.signatures.mSignatures)
10368 != PackageManager.SIGNATURE_MATCH) {
10369 throw new SecurityException(
10370 "Caller does not have same cert as old installer package "
10371 + targetPackageSetting.installerPackageName);
10377 targetPackageSetting.installerPackageName = installerPackageName;
10378 scheduleWriteSettingsLocked();
10382 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10383 // Queue up an async operation since the package installation may take a little while.
10384 mHandler.post(new Runnable() {
10385 public void run() {
10386 mHandler.removeCallbacks(this);
10387 // Result object to be returned
10388 PackageInstalledInfo res = new PackageInstalledInfo();
10389 res.returnCode = currentStatus;
10392 res.removedInfo = new PackageRemovedInfo();
10393 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10394 args.doPreInstall(res.returnCode);
10395 synchronized (mInstallLock) {
10396 installPackageLI(args, res);
10398 args.doPostInstall(res.returnCode, res.uid);
10401 // A restore should be performed at this point if (a) the install
10402 // succeeded, (b) the operation is not an update, and (c) the new
10403 // package has not opted out of backup participation.
10404 final boolean update = res.removedInfo.removedPackage != null;
10405 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10406 boolean doRestore = !update
10407 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10409 // Set up the post-install work request bookkeeping. This will be used
10410 // and cleaned up by the post-install event handling regardless of whether
10411 // there's a restore pass performed. Token values are >= 1.
10413 if (mNextInstallToken < 0) mNextInstallToken = 1;
10414 token = mNextInstallToken++;
10416 PostInstallData data = new PostInstallData(args, res);
10417 mRunningInstalls.put(token, data);
10418 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10420 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10421 // Pass responsibility to the Backup Manager. It will perform a
10422 // restore if appropriate, then pass responsibility back to the
10423 // Package Manager to run the post-install observer callbacks
10425 IBackupManager bm = IBackupManager.Stub.asInterface(
10426 ServiceManager.getService(Context.BACKUP_SERVICE));
10428 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10429 + " to BM for possible restore");
10431 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10432 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10436 } catch (RemoteException e) {
10437 // can't happen; the backup manager is local
10438 } catch (Exception e) {
10439 Slog.e(TAG, "Exception trying to enqueue restore", e);
10443 Slog.e(TAG, "Backup Manager not found!");
10449 // No restore possible, or the Backup Manager was mysteriously not
10450 // available -- just fire the post-install work request directly.
10451 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10452 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10453 mHandler.sendMessage(msg);
10459 private abstract class HandlerParams {
10460 private static final int MAX_RETRIES = 4;
10463 * Number of times startCopy() has been attempted and had a non-fatal
10466 private int mRetries = 0;
10468 /** User handle for the user requesting the information or installation. */
10469 private final UserHandle mUser;
10471 HandlerParams(UserHandle user) {
10475 UserHandle getUser() {
10479 final boolean startCopy() {
10482 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10484 if (++mRetries > MAX_RETRIES) {
10485 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10486 mHandler.sendEmptyMessage(MCS_GIVE_UP);
10487 handleServiceError();
10493 } catch (RemoteException e) {
10494 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10495 mHandler.sendEmptyMessage(MCS_RECONNECT);
10498 handleReturnCode();
10502 final void serviceError() {
10503 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10504 handleServiceError();
10505 handleReturnCode();
10508 abstract void handleStartCopy() throws RemoteException;
10509 abstract void handleServiceError();
10510 abstract void handleReturnCode();
10513 class MeasureParams extends HandlerParams {
10514 private final PackageStats mStats;
10515 private boolean mSuccess;
10517 private final IPackageStatsObserver mObserver;
10519 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10520 super(new UserHandle(stats.userHandle));
10521 mObserver = observer;
10526 public String toString() {
10527 return "MeasureParams{"
10528 + Integer.toHexString(System.identityHashCode(this))
10529 + " " + mStats.packageName + "}";
10533 void handleStartCopy() throws RemoteException {
10534 synchronized (mInstallLock) {
10535 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10539 final boolean mounted;
10540 if (Environment.isExternalStorageEmulated()) {
10543 final String status = Environment.getExternalStorageState();
10544 mounted = (Environment.MEDIA_MOUNTED.equals(status)
10545 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10549 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10551 mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10552 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10554 mStats.externalDataSize = calculateDirectorySize(mContainerService,
10555 userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10557 // Always subtract cache size, since it's a subdirectory
10558 mStats.externalDataSize -= mStats.externalCacheSize;
10560 mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10561 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10563 mStats.externalObbSize = calculateDirectorySize(mContainerService,
10564 userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10570 void handleReturnCode() {
10571 if (mObserver != null) {
10573 mObserver.onGetStatsCompleted(mStats, mSuccess);
10574 } catch (RemoteException e) {
10575 Slog.i(TAG, "Observer no longer exists.");
10581 void handleServiceError() {
10582 Slog.e(TAG, "Could not measure application " + mStats.packageName
10583 + " external storage");
10587 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10588 throws RemoteException {
10590 for (File path : paths) {
10591 result += mcs.calculateDirectorySize(path.getAbsolutePath());
10596 private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10597 for (File path : paths) {
10599 mcs.clearDirectory(path.getAbsolutePath());
10600 } catch (RemoteException e) {
10605 static class OriginInfo {
10607 * Location where install is coming from, before it has been
10608 * copied/renamed into place. This could be a single monolithic APK
10609 * file, or a cluster directory. This location may be untrusted.
10615 * Flag indicating that {@link #file} or {@link #cid} has already been
10616 * staged, meaning downstream users don't need to defensively copy the
10619 final boolean staged;
10622 * Flag indicating that {@link #file} or {@link #cid} is an already
10623 * installed app that is being moved.
10625 final boolean existing;
10627 final String resolvedPath;
10628 final File resolvedFile;
10630 static OriginInfo fromNothing() {
10631 return new OriginInfo(null, null, false, false);
10634 static OriginInfo fromUntrustedFile(File file) {
10635 return new OriginInfo(file, null, false, false);
10638 static OriginInfo fromExistingFile(File file) {
10639 return new OriginInfo(file, null, false, true);
10642 static OriginInfo fromStagedFile(File file) {
10643 return new OriginInfo(file, null, true, false);
10646 static OriginInfo fromStagedContainer(String cid) {
10647 return new OriginInfo(null, cid, true, false);
10650 private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10653 this.staged = staged;
10654 this.existing = existing;
10657 resolvedPath = PackageHelper.getSdDir(cid);
10658 resolvedFile = new File(resolvedPath);
10659 } else if (file != null) {
10660 resolvedPath = file.getAbsolutePath();
10661 resolvedFile = file;
10663 resolvedPath = null;
10664 resolvedFile = null;
10671 final String fromUuid;
10672 final String toUuid;
10673 final String packageName;
10674 final String dataAppName;
10676 final String seinfo;
10678 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10679 String dataAppName, int appId, String seinfo) {
10680 this.moveId = moveId;
10681 this.fromUuid = fromUuid;
10682 this.toUuid = toUuid;
10683 this.packageName = packageName;
10684 this.dataAppName = dataAppName;
10685 this.appId = appId;
10686 this.seinfo = seinfo;
10690 class InstallParams extends HandlerParams {
10691 final OriginInfo origin;
10692 final MoveInfo move;
10693 final IPackageInstallObserver2 observer;
10695 final String installerPackageName;
10696 final String volumeUuid;
10697 final VerificationParams verificationParams;
10698 private InstallArgs mArgs;
10700 final String packageAbiOverride;
10701 final String[] grantedRuntimePermissions;
10704 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10705 int installFlags, String installerPackageName, String volumeUuid,
10706 VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10707 String[] grantedPermissions) {
10709 this.origin = origin;
10711 this.observer = observer;
10712 this.installFlags = installFlags;
10713 this.installerPackageName = installerPackageName;
10714 this.volumeUuid = volumeUuid;
10715 this.verificationParams = verificationParams;
10716 this.packageAbiOverride = packageAbiOverride;
10717 this.grantedRuntimePermissions = grantedPermissions;
10721 public String toString() {
10722 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10723 + " file=" + origin.file + " cid=" + origin.cid + "}";
10726 public ManifestDigest getManifestDigest() {
10727 if (verificationParams == null) {
10730 return verificationParams.getManifestDigest();
10733 private int installLocationPolicy(PackageInfoLite pkgLite) {
10734 String packageName = pkgLite.packageName;
10735 int installLocation = pkgLite.installLocation;
10736 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10738 synchronized (mPackages) {
10739 PackageParser.Package pkg = mPackages.get(packageName);
10741 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10742 // Check for downgrading.
10743 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10745 checkDowngrade(pkg, pkgLite);
10746 } catch (PackageManagerException e) {
10747 Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10748 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10751 // Check for updated system application.
10752 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10754 Slog.w(TAG, "Cannot install update to system app on sdcard");
10755 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10757 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10760 // Install flag overrides everything.
10761 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10763 // If current upgrade specifies particular preference
10764 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10765 // Application explicitly specified internal.
10766 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10767 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10768 // App explictly prefers external. Let policy decide
10770 // Prefer previous location
10771 if (isExternal(pkg)) {
10772 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10774 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10778 // Invalid install. Return error code
10779 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10783 // All the special cases have been taken care of.
10784 // Return result based on recommended install location.
10786 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10788 return pkgLite.recommendedInstallLocation;
10792 * Invoke remote method to get package information and install
10793 * location values. Override install location based on default
10794 * policy if needed and then create install arguments based
10795 * on the install location.
10797 public void handleStartCopy() throws RemoteException {
10798 int ret = PackageManager.INSTALL_SUCCEEDED;
10800 // If we're already staged, we've firmly committed to an install location
10801 if (origin.staged) {
10802 if (origin.file != null) {
10803 installFlags |= PackageManager.INSTALL_INTERNAL;
10804 installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10805 } else if (origin.cid != null) {
10806 installFlags |= PackageManager.INSTALL_EXTERNAL;
10807 installFlags &= ~PackageManager.INSTALL_INTERNAL;
10809 throw new IllegalStateException("Invalid stage location");
10813 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10814 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10816 PackageInfoLite pkgLite = null;
10818 if (onInt && onSd) {
10819 // Check if both bits are set.
10820 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10821 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10823 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10824 packageAbiOverride);
10827 * If we have too little free space, try to free cache
10828 * before giving up.
10830 if (!origin.staged && pkgLite.recommendedInstallLocation
10831 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10832 // TODO: focus freeing disk space on the target device
10833 final StorageManager storage = StorageManager.from(mContext);
10834 final long lowThreshold = storage.getStorageLowBytes(
10835 Environment.getDataDirectory());
10837 final long sizeBytes = mContainerService.calculateInstalledSize(
10838 origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10840 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10841 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10842 installFlags, packageAbiOverride);
10846 * The cache free must have deleted the file we
10847 * downloaded to install.
10849 * TODO: fix the "freeCache" call to not delete
10850 * the file we care about.
10852 if (pkgLite.recommendedInstallLocation
10853 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10854 pkgLite.recommendedInstallLocation
10855 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10860 if (ret == PackageManager.INSTALL_SUCCEEDED) {
10861 int loc = pkgLite.recommendedInstallLocation;
10862 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10863 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10864 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10865 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10866 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10867 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10868 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10869 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10870 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10871 ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10872 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10873 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10875 // Override with defaults if needed.
10876 loc = installLocationPolicy(pkgLite);
10877 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10878 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10879 } else if (!onSd && !onInt) {
10880 // Override install location with flags
10881 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10882 // Set the flag to install on external media.
10883 installFlags |= PackageManager.INSTALL_EXTERNAL;
10884 installFlags &= ~PackageManager.INSTALL_INTERNAL;
10886 // Make sure the flag for installing on external
10888 installFlags |= PackageManager.INSTALL_INTERNAL;
10889 installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10895 final InstallArgs args = createInstallArgs(this);
10898 if (ret == PackageManager.INSTALL_SUCCEEDED) {
10900 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10901 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10903 int userIdentifier = getUser().getIdentifier();
10904 if (userIdentifier == UserHandle.USER_ALL
10905 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10906 userIdentifier = UserHandle.USER_OWNER;
10910 * Determine if we have any installed package verifiers. If we
10911 * do, then we'll defer to them to verify the packages.
10913 final int requiredUid = mRequiredVerifierPackage == null ? -1
10914 : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10915 if (!origin.existing && requiredUid != -1
10916 && isVerificationEnabled(userIdentifier, installFlags)) {
10917 final Intent verification = new Intent(
10918 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10919 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10920 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10921 PACKAGE_MIME_TYPE);
10922 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10924 final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10925 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10926 0 /* TODO: Which userId? */);
10928 if (DEBUG_VERIFY) {
10929 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10930 + verification.toString() + " with " + pkgLite.verifiers.length
10931 + " optional verifiers");
10934 final int verificationId = mPendingVerificationToken++;
10936 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10938 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10939 installerPackageName);
10941 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10944 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10945 pkgLite.packageName);
10947 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10948 pkgLite.versionCode);
10950 if (verificationParams != null) {
10951 if (verificationParams.getVerificationURI() != null) {
10952 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10953 verificationParams.getVerificationURI());
10955 if (verificationParams.getOriginatingURI() != null) {
10956 verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10957 verificationParams.getOriginatingURI());
10959 if (verificationParams.getReferrer() != null) {
10960 verification.putExtra(Intent.EXTRA_REFERRER,
10961 verificationParams.getReferrer());
10963 if (verificationParams.getOriginatingUid() >= 0) {
10964 verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10965 verificationParams.getOriginatingUid());
10967 if (verificationParams.getInstallerUid() >= 0) {
10968 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10969 verificationParams.getInstallerUid());
10973 final PackageVerificationState verificationState = new PackageVerificationState(
10974 requiredUid, args);
10976 mPendingVerification.append(verificationId, verificationState);
10978 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10979 receivers, verificationState);
10981 // Apps installed for "all" users use the device owner to verify the app
10982 UserHandle verifierUser = getUser();
10983 if (verifierUser == UserHandle.ALL) {
10984 verifierUser = UserHandle.OWNER;
10988 * If any sufficient verifiers were listed in the package
10989 * manifest, attempt to ask them.
10991 if (sufficientVerifiers != null) {
10992 final int N = sufficientVerifiers.size();
10994 Slog.i(TAG, "Additional verifiers required, but none installed.");
10995 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10997 for (int i = 0; i < N; i++) {
10998 final ComponentName verifierComponent = sufficientVerifiers.get(i);
11000 final Intent sufficientIntent = new Intent(verification);
11001 sufficientIntent.setComponent(verifierComponent);
11002 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11007 final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11008 mRequiredVerifierPackage, receivers);
11009 if (ret == PackageManager.INSTALL_SUCCEEDED
11010 && mRequiredVerifierPackage != null) {
11012 * Send the intent to the required verification agent,
11013 * but only start the verification timeout after the
11014 * target BroadcastReceivers have run.
11016 verification.setComponent(requiredVerifierComponent);
11017 mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11018 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11019 new BroadcastReceiver() {
11021 public void onReceive(Context context, Intent intent) {
11022 final Message msg = mHandler
11023 .obtainMessage(CHECK_PENDING_VERIFICATION);
11024 msg.arg1 = verificationId;
11025 mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11027 }, null, 0, null, null);
11030 * We don't want the copy to proceed until verification
11031 * succeeds, so null out this field.
11037 * No package verification is enabled, so immediately start
11038 * the remote call to initiate copy using temporary file.
11040 ret = args.copyApk(mContainerService, true);
11048 void handleReturnCode() {
11049 // If mArgs is null, then MCS couldn't be reached. When it
11050 // reconnects, it will try again to install. At that point, this
11052 if (mArgs != null) {
11053 processPendingInstall(mArgs, mRet);
11058 void handleServiceError() {
11059 mArgs = createInstallArgs(this);
11060 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11063 public boolean isForwardLocked() {
11064 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11069 * Used during creation of InstallArgs
11071 * @param installFlags package installation flags
11072 * @return true if should be installed on external storage
11074 private static boolean installOnExternalAsec(int installFlags) {
11075 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11078 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11085 * Used during creation of InstallArgs
11087 * @param installFlags package installation flags
11088 * @return true if should be installed as forward locked
11090 private static boolean installForwardLocked(int installFlags) {
11091 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11094 private InstallArgs createInstallArgs(InstallParams params) {
11095 if (params.move != null) {
11096 return new MoveInstallArgs(params);
11097 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11098 return new AsecInstallArgs(params);
11100 return new FileInstallArgs(params);
11105 * Create args that describe an existing installed package. Typically used
11106 * when cleaning up old installs, or used as a move source.
11108 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11109 String resourcePath, String[] instructionSets) {
11110 final boolean isInAsec;
11111 if (installOnExternalAsec(installFlags)) {
11112 /* Apps on SD card are always in ASEC containers. */
11114 } else if (installForwardLocked(installFlags)
11115 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11117 * Forward-locked apps are only in ASEC containers if they're the
11126 return new AsecInstallArgs(codePath, instructionSets,
11127 installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11129 return new FileInstallArgs(codePath, resourcePath, instructionSets);
11133 static abstract class InstallArgs {
11134 /** @see InstallParams#origin */
11135 final OriginInfo origin;
11136 /** @see InstallParams#move */
11137 final MoveInfo move;
11139 final IPackageInstallObserver2 observer;
11140 // Always refers to PackageManager flags only
11141 final int installFlags;
11142 final String installerPackageName;
11143 final String volumeUuid;
11144 final ManifestDigest manifestDigest;
11145 final UserHandle user;
11146 final String abiOverride;
11147 final String[] installGrantPermissions;
11149 // The list of instruction sets supported by this app. This is currently
11150 // only used during the rmdex() phase to clean up resources. We can get rid of this
11151 // if we move dex files under the common app path.
11152 /* nullable */ String[] instructionSets;
11154 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11155 int installFlags, String installerPackageName, String volumeUuid,
11156 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11157 String abiOverride, String[] installGrantPermissions) {
11158 this.origin = origin;
11160 this.installFlags = installFlags;
11161 this.observer = observer;
11162 this.installerPackageName = installerPackageName;
11163 this.volumeUuid = volumeUuid;
11164 this.manifestDigest = manifestDigest;
11166 this.instructionSets = instructionSets;
11167 this.abiOverride = abiOverride;
11168 this.installGrantPermissions = installGrantPermissions;
11171 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11172 abstract int doPreInstall(int status);
11175 * Rename package into final resting place. All paths on the given
11176 * scanned package should be updated to reflect the rename.
11178 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11179 abstract int doPostInstall(int status, int uid);
11181 /** @see PackageSettingBase#codePathString */
11182 abstract String getCodePath();
11183 /** @see PackageSettingBase#resourcePathString */
11184 abstract String getResourcePath();
11186 // Need installer lock especially for dex file removal.
11187 abstract void cleanUpResourcesLI();
11188 abstract boolean doPostDeleteLI(boolean delete);
11191 * Called before the source arguments are copied. This is used mostly
11192 * for MoveParams when it needs to read the source file to put it in the
11196 return PackageManager.INSTALL_SUCCEEDED;
11200 * Called after the source arguments are copied. This is used mostly for
11201 * MoveParams when it needs to read the source file to put it in the
11204 int doPostCopy(int uid) {
11205 return PackageManager.INSTALL_SUCCEEDED;
11208 protected boolean isFwdLocked() {
11209 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11212 protected boolean isExternalAsec() {
11213 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11216 UserHandle getUser() {
11221 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11222 if (!allCodePaths.isEmpty()) {
11223 if (instructionSets == null) {
11224 throw new IllegalStateException("instructionSet == null");
11226 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11227 for (String codePath : allCodePaths) {
11228 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11229 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11231 Slog.w(TAG, "Couldn't remove dex file for package: "
11232 + " at location " + codePath + ", retcode=" + retCode);
11233 // we don't consider this to be a failure of the core package deletion
11241 * Logic to handle installation of non-ASEC applications, including copying
11242 * and renaming logic.
11244 class FileInstallArgs extends InstallArgs {
11245 private File codeFile;
11246 private File resourceFile;
11248 // Example topology:
11249 // /data/app/com.example/base.apk
11250 // /data/app/com.example/split_foo.apk
11251 // /data/app/com.example/lib/arm/libfoo.so
11252 // /data/app/com.example/lib/arm64/libfoo.so
11253 // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11256 FileInstallArgs(InstallParams params) {
11257 super(params.origin, params.move, params.observer, params.installFlags,
11258 params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11259 params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11260 params.grantedRuntimePermissions);
11261 if (isFwdLocked()) {
11262 throw new IllegalArgumentException("Forward locking only supported in ASEC");
11266 /** Existing install */
11267 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11268 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11270 this.codeFile = (codePath != null) ? new File(codePath) : null;
11271 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11274 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11275 if (origin.staged) {
11276 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11277 codeFile = origin.file;
11278 resourceFile = origin.file;
11279 return PackageManager.INSTALL_SUCCEEDED;
11283 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11284 codeFile = tempDir;
11285 resourceFile = tempDir;
11286 } catch (IOException e) {
11287 Slog.w(TAG, "Failed to create copy file: " + e);
11288 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11291 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11293 public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11294 if (!FileUtils.isValidExtFilename(name)) {
11295 throw new IllegalArgumentException("Invalid filename: " + name);
11298 final File file = new File(codeFile, name);
11299 final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11300 O_RDWR | O_CREAT, 0644);
11301 Os.chmod(file.getAbsolutePath(), 0644);
11302 return new ParcelFileDescriptor(fd);
11303 } catch (ErrnoException e) {
11304 throw new RemoteException("Failed to open: " + e.getMessage());
11309 int ret = PackageManager.INSTALL_SUCCEEDED;
11310 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11311 if (ret != PackageManager.INSTALL_SUCCEEDED) {
11312 Slog.e(TAG, "Failed to copy package");
11316 final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11317 NativeLibraryHelper.Handle handle = null;
11319 handle = NativeLibraryHelper.Handle.create(codeFile);
11320 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11322 } catch (IOException e) {
11323 Slog.e(TAG, "Copying native libraries failed", e);
11324 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11326 IoUtils.closeQuietly(handle);
11332 int doPreInstall(int status) {
11333 if (status != PackageManager.INSTALL_SUCCEEDED) {
11339 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11340 if (status != PackageManager.INSTALL_SUCCEEDED) {
11345 final File targetDir = codeFile.getParentFile();
11346 final File beforeCodeFile = codeFile;
11347 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11349 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11351 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11352 } catch (ErrnoException e) {
11353 Slog.w(TAG, "Failed to rename", e);
11357 if (!SELinux.restoreconRecursive(afterCodeFile)) {
11358 Slog.w(TAG, "Failed to restorecon");
11362 // Reflect the rename internally
11363 codeFile = afterCodeFile;
11364 resourceFile = afterCodeFile;
11366 // Reflect the rename in scanned details
11367 pkg.codePath = afterCodeFile.getAbsolutePath();
11368 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11370 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11371 pkg.splitCodePaths);
11373 // Reflect the rename in app info
11374 pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11375 pkg.applicationInfo.setCodePath(pkg.codePath);
11376 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11377 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11378 pkg.applicationInfo.setResourcePath(pkg.codePath);
11379 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11380 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11385 int doPostInstall(int status, int uid) {
11386 if (status != PackageManager.INSTALL_SUCCEEDED) {
11393 String getCodePath() {
11394 return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11398 String getResourcePath() {
11399 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11402 private boolean cleanUp() {
11403 if (codeFile == null || !codeFile.exists()) {
11407 if (codeFile.isDirectory()) {
11408 mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11413 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11414 resourceFile.delete();
11420 void cleanUpResourcesLI() {
11421 // Try enumerating all code paths before deleting
11422 List<String> allCodePaths = Collections.EMPTY_LIST;
11423 if (codeFile != null && codeFile.exists()) {
11425 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11426 allCodePaths = pkg.getAllCodePaths();
11427 } catch (PackageParserException e) {
11428 // Ignored; we tried our best
11433 removeDexFiles(allCodePaths, instructionSets);
11436 boolean doPostDeleteLI(boolean delete) {
11437 // XXX err, shouldn't we respect the delete flag?
11438 cleanUpResourcesLI();
11443 private boolean isAsecExternal(String cid) {
11444 final String asecPath = PackageHelper.getSdFilesystem(cid);
11445 return !asecPath.startsWith(mAsecInternalPath);
11448 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11449 PackageManagerException {
11451 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11452 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11453 throw new PackageManagerException(copyRet, message);
11459 * Extract the MountService "container ID" from the full code path of an
11462 static String cidFromCodePath(String fullCodePath) {
11463 int eidx = fullCodePath.lastIndexOf("/");
11464 String subStr1 = fullCodePath.substring(0, eidx);
11465 int sidx = subStr1.lastIndexOf("/");
11466 return subStr1.substring(sidx+1, eidx);
11470 * Logic to handle installation of ASEC applications, including copying and
11473 class AsecInstallArgs extends InstallArgs {
11474 static final String RES_FILE_NAME = "pkg.apk";
11475 static final String PUBLIC_RES_FILE_NAME = "res.zip";
11478 String packagePath;
11479 String resourcePath;
11482 AsecInstallArgs(InstallParams params) {
11483 super(params.origin, params.move, params.observer, params.installFlags,
11484 params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11485 params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11486 params.grantedRuntimePermissions);
11489 /** Existing install */
11490 AsecInstallArgs(String fullCodePath, String[] instructionSets,
11491 boolean isExternal, boolean isForwardLocked) {
11492 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11493 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11494 instructionSets, null, null);
11495 // Hackily pretend we're still looking at a full code path
11496 if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11497 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11500 // Extract cid from fullCodePath
11501 int eidx = fullCodePath.lastIndexOf("/");
11502 String subStr1 = fullCodePath.substring(0, eidx);
11503 int sidx = subStr1.lastIndexOf("/");
11504 cid = subStr1.substring(sidx+1, eidx);
11505 setMountPath(subStr1);
11508 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11509 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11510 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11511 instructionSets, null, null);
11513 setMountPath(PackageHelper.getSdDir(cid));
11516 void createCopyFile() {
11517 cid = mInstallerService.allocateExternalStageCidLegacy();
11520 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11521 if (origin.staged) {
11522 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11524 setMountPath(PackageHelper.getSdDir(cid));
11525 return PackageManager.INSTALL_SUCCEEDED;
11532 * Pre-emptively destroy the container since it's destroyed if
11533 * copying fails due to it existing anyway.
11535 PackageHelper.destroySdDir(cid);
11538 final String newMountPath = imcs.copyPackageToContainer(
11539 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11540 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11542 if (newMountPath != null) {
11543 setMountPath(newMountPath);
11544 return PackageManager.INSTALL_SUCCEEDED;
11546 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11551 String getCodePath() {
11552 return packagePath;
11556 String getResourcePath() {
11557 return resourcePath;
11560 int doPreInstall(int status) {
11561 if (status != PackageManager.INSTALL_SUCCEEDED) {
11562 // Destroy container
11563 PackageHelper.destroySdDir(cid);
11565 boolean mounted = PackageHelper.isContainerMounted(cid);
11567 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11568 Process.SYSTEM_UID);
11569 if (newMountPath != null) {
11570 setMountPath(newMountPath);
11572 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11579 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11580 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11581 String newMountPath = null;
11582 if (PackageHelper.isContainerMounted(cid)) {
11583 // Unmount the container
11584 if (!PackageHelper.unMountSdDir(cid)) {
11585 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11589 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11590 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11591 " which might be stale. Will try to clean up.");
11592 // Clean up the stale container and proceed to recreate.
11593 if (!PackageHelper.destroySdDir(newCacheId)) {
11594 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11597 // Successfully cleaned up stale container. Try to rename again.
11598 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11599 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11600 + " inspite of cleaning it up.");
11604 if (!PackageHelper.isContainerMounted(newCacheId)) {
11605 Slog.w(TAG, "Mounting container " + newCacheId);
11606 newMountPath = PackageHelper.mountSdDir(newCacheId,
11607 getEncryptKey(), Process.SYSTEM_UID);
11609 newMountPath = PackageHelper.getSdDir(newCacheId);
11611 if (newMountPath == null) {
11612 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
11615 Log.i(TAG, "Succesfully renamed " + cid +
11616 " to " + newCacheId +
11617 " at new path: " + newMountPath);
11620 final File beforeCodeFile = new File(packagePath);
11621 setMountPath(newMountPath);
11622 final File afterCodeFile = new File(packagePath);
11624 // Reflect the rename in scanned details
11625 pkg.codePath = afterCodeFile.getAbsolutePath();
11626 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11628 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11629 pkg.splitCodePaths);
11631 // Reflect the rename in app info
11632 pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11633 pkg.applicationInfo.setCodePath(pkg.codePath);
11634 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11635 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11636 pkg.applicationInfo.setResourcePath(pkg.codePath);
11637 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11638 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11643 private void setMountPath(String mountPath) {
11644 final File mountFile = new File(mountPath);
11646 final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11647 if (monolithicFile.exists()) {
11648 packagePath = monolithicFile.getAbsolutePath();
11649 if (isFwdLocked()) {
11650 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11652 resourcePath = packagePath;
11655 packagePath = mountFile.getAbsolutePath();
11656 resourcePath = packagePath;
11660 int doPostInstall(int status, int uid) {
11661 if (status != PackageManager.INSTALL_SUCCEEDED) {
11664 final int groupOwner;
11665 final String protectedFile;
11666 if (isFwdLocked()) {
11667 groupOwner = UserHandle.getSharedAppGid(uid);
11668 protectedFile = RES_FILE_NAME;
11671 protectedFile = null;
11674 if (uid < Process.FIRST_APPLICATION_UID
11675 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11676 Slog.e(TAG, "Failed to finalize " + cid);
11677 PackageHelper.destroySdDir(cid);
11678 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11681 boolean mounted = PackageHelper.isContainerMounted(cid);
11683 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11689 private void cleanUp() {
11690 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11692 // Destroy secure container
11693 PackageHelper.destroySdDir(cid);
11696 private List<String> getAllCodePaths() {
11697 final File codeFile = new File(getCodePath());
11698 if (codeFile != null && codeFile.exists()) {
11700 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11701 return pkg.getAllCodePaths();
11702 } catch (PackageParserException e) {
11703 // Ignored; we tried our best
11706 return Collections.EMPTY_LIST;
11709 void cleanUpResourcesLI() {
11710 // Enumerate all code paths before deleting
11711 cleanUpResourcesLI(getAllCodePaths());
11714 private void cleanUpResourcesLI(List<String> allCodePaths) {
11716 removeDexFiles(allCodePaths, instructionSets);
11719 String getPackageName() {
11720 return getAsecPackageName(cid);
11723 boolean doPostDeleteLI(boolean delete) {
11724 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11725 final List<String> allCodePaths = getAllCodePaths();
11726 boolean mounted = PackageHelper.isContainerMounted(cid);
11729 if (PackageHelper.unMountSdDir(cid)) {
11733 if (!mounted && delete) {
11734 cleanUpResourcesLI(allCodePaths);
11741 if (isFwdLocked()) {
11742 if (!PackageHelper.fixSdPermissions(cid,
11743 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11744 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11748 return PackageManager.INSTALL_SUCCEEDED;
11752 int doPostCopy(int uid) {
11753 if (isFwdLocked()) {
11754 if (uid < Process.FIRST_APPLICATION_UID
11755 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11757 Slog.e(TAG, "Failed to finalize " + cid);
11758 PackageHelper.destroySdDir(cid);
11759 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11763 return PackageManager.INSTALL_SUCCEEDED;
11768 * Logic to handle movement of existing installed applications.
11770 class MoveInstallArgs extends InstallArgs {
11771 private File codeFile;
11772 private File resourceFile;
11775 MoveInstallArgs(InstallParams params) {
11776 super(params.origin, params.move, params.observer, params.installFlags,
11777 params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11778 params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11779 params.grantedRuntimePermissions);
11782 int copyApk(IMediaContainerService imcs, boolean temp) {
11783 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11784 + move.fromUuid + " to " + move.toUuid);
11785 synchronized (mInstaller) {
11786 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11787 move.dataAppName, move.appId, move.seinfo) != 0) {
11788 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11792 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11793 resourceFile = codeFile;
11794 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11796 return PackageManager.INSTALL_SUCCEEDED;
11799 int doPreInstall(int status) {
11800 if (status != PackageManager.INSTALL_SUCCEEDED) {
11801 cleanUp(move.toUuid);
11806 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11807 if (status != PackageManager.INSTALL_SUCCEEDED) {
11808 cleanUp(move.toUuid);
11812 // Reflect the move in app info
11813 pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11814 pkg.applicationInfo.setCodePath(pkg.codePath);
11815 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11816 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11817 pkg.applicationInfo.setResourcePath(pkg.codePath);
11818 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11819 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11824 int doPostInstall(int status, int uid) {
11825 if (status == PackageManager.INSTALL_SUCCEEDED) {
11826 cleanUp(move.fromUuid);
11828 cleanUp(move.toUuid);
11834 String getCodePath() {
11835 return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11839 String getResourcePath() {
11840 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11843 private boolean cleanUp(String volumeUuid) {
11844 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11846 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11847 synchronized (mInstallLock) {
11848 // Clean up both app data and code
11849 removeDataDirsLI(volumeUuid, move.packageName);
11850 if (codeFile.isDirectory()) {
11851 mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11859 void cleanUpResourcesLI() {
11860 throw new UnsupportedOperationException();
11863 boolean doPostDeleteLI(boolean delete) {
11864 throw new UnsupportedOperationException();
11868 static String getAsecPackageName(String packageCid) {
11869 int idx = packageCid.lastIndexOf("-");
11873 return packageCid.substring(0, idx);
11876 // Utility method used to create code paths based on package name and available index.
11877 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11878 String idxStr = "";
11880 // Fall back to default value of idx=1 if prefix is not
11881 // part of oldCodePath
11882 if (oldCodePath != null) {
11883 String subStr = oldCodePath;
11884 // Drop the suffix right away
11885 if (suffix != null && subStr.endsWith(suffix)) {
11886 subStr = subStr.substring(0, subStr.length() - suffix.length());
11888 // If oldCodePath already contains prefix find out the
11889 // ending index to either increment or decrement.
11890 int sidx = subStr.lastIndexOf(prefix);
11892 subStr = subStr.substring(sidx + prefix.length());
11893 if (subStr != null) {
11894 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11895 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11898 idx = Integer.parseInt(subStr);
11904 } catch(NumberFormatException e) {
11909 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11910 return prefix + idxStr;
11913 private File getNextCodePath(File targetDir, String packageName) {
11917 result = new File(targetDir, packageName + "-" + suffix);
11919 } while (result.exists());
11923 // Utility method that returns the relative package path with respect
11924 // to the installation directory. Like say for /data/data/com.test-1.apk
11925 // string com.test-1 is returned.
11926 static String deriveCodePathName(String codePath) {
11927 if (codePath == null) {
11930 final File codeFile = new File(codePath);
11931 final String name = codeFile.getName();
11932 if (codeFile.isDirectory()) {
11934 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11935 final int lastDot = name.lastIndexOf('.');
11936 return name.substring(0, lastDot);
11938 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11943 class PackageInstalledInfo {
11946 // The set of users that originally had this package installed.
11948 // The set of users that now have this package installed.
11950 PackageParser.Package pkg;
11953 PackageRemovedInfo removedInfo;
11955 public void setError(int code, String msg) {
11961 public void setError(String msg, PackageParserException e) {
11962 returnCode = e.error;
11963 returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11964 Slog.w(TAG, msg, e);
11967 public void setError(String msg, PackageManagerException e) {
11968 returnCode = e.error;
11969 returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11970 Slog.w(TAG, msg, e);
11973 // In some error cases we want to convey more info back to the observer
11974 String origPackage;
11975 String origPermission;
11979 * Install a non-existing package.
11981 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11982 UserHandle user, String installerPackageName, String volumeUuid,
11983 PackageInstalledInfo res) {
11984 // Remember this for later, in case we need to rollback this install
11985 String pkgName = pkg.packageName;
11987 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11988 final boolean dataDirExists = Environment
11989 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11990 synchronized(mPackages) {
11991 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11992 // A package with the same name is already installed, though
11993 // it has been renamed to an older name. The package we
11994 // are trying to install should be installed as an update to
11995 // the existing one, but that has not been requested, so bail.
11996 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11997 + " without first uninstalling package running as "
11998 + mSettings.mRenamedPackages.get(pkgName));
12001 if (mPackages.containsKey(pkgName)) {
12002 // Don't allow installation over an existing package with the same name.
12003 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12004 + " without first uninstalling.");
12010 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
12011 System.currentTimeMillis(), user);
12013 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12014 // delete the partially installed application. the data directory will have to be
12015 // restored if it was already existing
12016 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12017 // remove package from internal structures. Note that we want deletePackageX to
12018 // delete the package data and cache directories that it created in
12019 // scanPackageLocked, unless those directories existed before we even tried to
12021 deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12022 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12023 res.removedInfo, true);
12026 } catch (PackageManagerException e) {
12027 res.setError("Package couldn't be installed in " + pkg.codePath, e);
12031 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12032 // Can't rotate keys during boot or if sharedUser.
12033 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12034 || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12037 // app is using upgradeKeySets; make sure all are valid
12038 KeySetManagerService ksms = mSettings.mKeySetManagerService;
12039 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12040 for (int i = 0; i < upgradeKeySets.length; i++) {
12041 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12042 Slog.wtf(TAG, "Package "
12043 + (oldPs.name != null ? oldPs.name : "<null>")
12044 + " contains upgrade-key-set reference to unknown key-set: "
12045 + upgradeKeySets[i]
12046 + " reverting to signatures check.");
12053 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12054 // Upgrade keysets are being used. Determine if new package has a superset of the
12056 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12057 KeySetManagerService ksms = mSettings.mKeySetManagerService;
12058 for (int i = 0; i < upgradeKeySets.length; i++) {
12059 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12060 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12067 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12068 UserHandle user, String installerPackageName, String volumeUuid,
12069 PackageInstalledInfo res) {
12070 final PackageParser.Package oldPackage;
12071 final String pkgName = pkg.packageName;
12072 final int[] allUsers;
12073 final boolean[] perUserInstalled;
12075 // First find the old package info and check signatures
12076 synchronized(mPackages) {
12077 oldPackage = mPackages.get(pkgName);
12078 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12079 final PackageSetting ps = mSettings.mPackages.get(pkgName);
12080 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12081 if(!checkUpgradeKeySetLP(ps, pkg)) {
12082 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12083 "New package not signed by keys specified by upgrade-keysets: "
12088 // default to original signature matching
12089 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12090 != PackageManager.SIGNATURE_MATCH) {
12091 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12092 "New package has a different signature: " + pkgName);
12097 // In case of rollback, remember per-user/profile install state
12098 allUsers = sUserManager.getUserIds();
12099 perUserInstalled = new boolean[allUsers.length];
12100 for (int i = 0; i < allUsers.length; i++) {
12101 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12105 boolean sysPkg = (isSystemApp(oldPackage));
12107 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12108 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12110 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12111 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12115 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12116 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12117 int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12118 String volumeUuid, PackageInstalledInfo res) {
12119 String pkgName = deletedPackage.packageName;
12120 boolean deletedPkg = true;
12121 boolean updatedSettings = false;
12123 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12125 long origUpdateTime;
12126 if (pkg.mExtras != null) {
12127 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12129 origUpdateTime = 0;
12132 // First delete the existing package while retaining the data directory
12133 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12134 res.removedInfo, true)) {
12135 // If the existing package wasn't successfully deleted
12136 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12137 deletedPkg = false;
12139 // Successfully deleted the old package; proceed with replace.
12141 // If deleted package lived in a container, give users a chance to
12142 // relinquish resources before killing.
12143 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12144 if (DEBUG_INSTALL) {
12145 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12147 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12148 final ArrayList<String> pkgList = new ArrayList<String>(1);
12149 pkgList.add(deletedPackage.applicationInfo.packageName);
12150 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12153 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12155 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
12156 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12157 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12158 perUserInstalled, res, user);
12159 updatedSettings = true;
12160 } catch (PackageManagerException e) {
12161 res.setError("Package couldn't be installed in " + pkg.codePath, e);
12165 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12166 // remove package from internal structures. Note that we want deletePackageX to
12167 // delete the package data and cache directories that it created in
12168 // scanPackageLocked, unless those directories existed before we even tried to
12170 if(updatedSettings) {
12171 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12173 pkgName, null, true, allUsers, perUserInstalled,
12174 PackageManager.DELETE_KEEP_DATA,
12175 res.removedInfo, true);
12177 // Since we failed to install the new package we need to restore the old
12178 // package that we deleted.
12180 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12181 File restoreFile = new File(deletedPackage.codePath);
12182 // Parse old package
12183 boolean oldExternal = isExternal(deletedPackage);
12184 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
12185 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12186 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12187 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12189 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
12190 } catch (PackageManagerException e) {
12191 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12195 // Restore of old package succeeded. Update permissions.
12197 synchronized (mPackages) {
12198 updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12199 UPDATE_PERMISSIONS_ALL);
12200 // can downgrade to reader
12201 mSettings.writeLPr();
12203 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12208 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12209 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12210 int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12211 String volumeUuid, PackageInstalledInfo res) {
12212 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12213 + ", old=" + deletedPackage);
12214 boolean disabledSystem = false;
12215 boolean updatedSettings = false;
12216 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12217 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12219 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12221 String packageName = deletedPackage.packageName;
12222 if (packageName == null) {
12223 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12224 "Attempt to delete null packageName.");
12227 PackageParser.Package oldPkg;
12228 PackageSetting oldPkgSetting;
12230 synchronized (mPackages) {
12231 oldPkg = mPackages.get(packageName);
12232 oldPkgSetting = mSettings.mPackages.get(packageName);
12233 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12234 (oldPkgSetting == null)) {
12235 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12236 "Couldn't find package:" + packageName + " information");
12241 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12243 res.removedInfo.uid = oldPkg.applicationInfo.uid;
12244 res.removedInfo.removedPackage = packageName;
12245 // Remove existing system package
12246 removePackageLI(oldPkgSetting, true);
12248 synchronized (mPackages) {
12249 disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12250 if (!disabledSystem && deletedPackage != null) {
12251 // We didn't need to disable the .apk as a current system package,
12252 // which means we are replacing another update that is already
12253 // installed. We need to make sure to delete the older one's .apk.
12254 res.removedInfo.args = createInstallArgsForExisting(0,
12255 deletedPackage.applicationInfo.getCodePath(),
12256 deletedPackage.applicationInfo.getResourcePath(),
12257 getAppDexInstructionSets(deletedPackage.applicationInfo));
12259 res.removedInfo.args = null;
12263 // Successfully disabled the old package. Now proceed with re-installation
12264 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12266 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12267 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12269 PackageParser.Package newPackage = null;
12271 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
12272 if (newPackage.mExtras != null) {
12273 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12274 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12275 newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12277 // is the update attempting to change shared user? that isn't going to work...
12278 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12279 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12280 "Forbidding shared user change from " + oldPkgSetting.sharedUser
12281 + " to " + newPkgSetting.sharedUser);
12282 updatedSettings = true;
12286 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12287 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12288 perUserInstalled, res, user);
12289 updatedSettings = true;
12292 } catch (PackageManagerException e) {
12293 res.setError("Package couldn't be installed in " + pkg.codePath, e);
12296 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12297 // Re installation failed. Restore old information
12298 // Remove new pkg information
12299 if (newPackage != null) {
12300 removeInstalledPackageLI(newPackage, true);
12302 // Add back the old system package
12304 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12305 } catch (PackageManagerException e) {
12306 Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12308 // Restore the old system information in Settings
12309 synchronized (mPackages) {
12310 if (disabledSystem) {
12311 mSettings.enableSystemPackageLPw(packageName);
12313 if (updatedSettings) {
12314 mSettings.setInstallerPackageName(packageName,
12315 oldPkgSetting.installerPackageName);
12317 mSettings.writeLPr();
12322 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12323 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12325 String pkgName = newPackage.packageName;
12326 synchronized (mPackages) {
12327 //write settings. the installStatus will be incomplete at this stage.
12328 //note that the new package setting would have already been
12329 //added to mPackages. It hasn't been persisted yet.
12330 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12331 mSettings.writeLPr();
12334 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12336 synchronized (mPackages) {
12337 updatePermissionsLPw(newPackage.packageName, newPackage,
12338 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12339 ? UPDATE_PERMISSIONS_ALL : 0));
12340 // For system-bundled packages, we assume that installing an upgraded version
12341 // of the package implies that the user actually wants to run that new code,
12342 // so we enable the package.
12343 PackageSetting ps = mSettings.mPackages.get(pkgName);
12345 if (isSystemApp(newPackage)) {
12346 // NB: implicit assumption that system package upgrades apply to all users
12347 if (DEBUG_INSTALL) {
12348 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12350 if (res.origUsers != null) {
12351 for (int userHandle : res.origUsers) {
12352 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12353 userHandle, installerPackageName);
12356 // Also convey the prior install/uninstall state
12357 if (allUsers != null && perUserInstalled != null) {
12358 for (int i = 0; i < allUsers.length; i++) {
12359 if (DEBUG_INSTALL) {
12360 Slog.d(TAG, " user " + allUsers[i]
12361 + " => " + perUserInstalled[i]);
12363 ps.setInstalled(perUserInstalled[i], allUsers[i]);
12365 // these install state changes will be persisted in the
12366 // upcoming call to mSettings.writeLPr().
12369 // It's implied that when a user requests installation, they want the app to be
12370 // installed and enabled.
12371 int userId = user.getIdentifier();
12372 if (userId != UserHandle.USER_ALL) {
12373 ps.setInstalled(true, userId);
12374 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12377 res.name = pkgName;
12378 res.uid = newPackage.applicationInfo.uid;
12379 res.pkg = newPackage;
12380 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12381 mSettings.setInstallerPackageName(pkgName, installerPackageName);
12382 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12383 //to update install status
12384 mSettings.writeLPr();
12388 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12389 final int installFlags = args.installFlags;
12390 final String installerPackageName = args.installerPackageName;
12391 final String volumeUuid = args.volumeUuid;
12392 final File tmpPackageFile = new File(args.getCodePath());
12393 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12394 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12395 || (args.volumeUuid != null));
12396 boolean replace = false;
12397 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12398 if (args.move != null) {
12399 // moving a complete application; perfom an initial scan on the new install location
12400 scanFlags |= SCAN_INITIAL;
12402 // Result object to be returned
12403 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12405 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12406 // Retrieve PackageSettings and parse package
12407 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12408 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12409 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12410 PackageParser pp = new PackageParser();
12411 pp.setSeparateProcesses(mSeparateProcesses);
12412 pp.setDisplayMetrics(mMetrics);
12414 final PackageParser.Package pkg;
12416 pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12417 } catch (PackageParserException e) {
12418 res.setError("Failed parse during installPackageLI", e);
12422 // Mark that we have an install time CPU ABI override.
12423 pkg.cpuAbiOverride = args.abiOverride;
12425 String pkgName = res.name = pkg.packageName;
12426 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12427 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12428 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12434 pp.collectCertificates(pkg, parseFlags);
12435 pp.collectManifestDigest(pkg);
12436 } catch (PackageParserException e) {
12437 res.setError("Failed collect during installPackageLI", e);
12441 /* If the installer passed in a manifest digest, compare it now. */
12442 if (args.manifestDigest != null) {
12443 if (DEBUG_INSTALL) {
12444 final String parsedManifest = pkg.manifestDigest == null ? "null"
12445 : pkg.manifestDigest.toString();
12446 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12450 if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12451 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12454 } else if (DEBUG_INSTALL) {
12455 final String parsedManifest = pkg.manifestDigest == null
12456 ? "null" : pkg.manifestDigest.toString();
12457 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12460 // Get rid of all references to package scan path via parser.
12462 String oldCodePath = null;
12463 boolean systemApp = false;
12464 synchronized (mPackages) {
12465 // Check if installing already existing package
12466 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12467 String oldName = mSettings.mRenamedPackages.get(pkgName);
12468 if (pkg.mOriginalPackages != null
12469 && pkg.mOriginalPackages.contains(oldName)
12470 && mPackages.containsKey(oldName)) {
12471 // This package is derived from an original package,
12472 // and this device has been updating from that original
12473 // name. We must continue using the original name, so
12474 // rename the new package here.
12475 pkg.setPackageName(oldName);
12476 pkgName = pkg.packageName;
12478 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12479 + oldName + " pkgName=" + pkgName);
12480 } else if (mPackages.containsKey(pkgName)) {
12481 // This package, under its official name, already exists
12482 // on the device; we should replace it.
12484 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12487 // Prevent apps opting out from runtime permissions
12489 PackageParser.Package oldPackage = mPackages.get(pkgName);
12490 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12491 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12492 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12493 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12494 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12495 "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12496 + " doesn't support runtime permissions but the old"
12497 + " target SDK " + oldTargetSdk + " does.");
12503 PackageSetting ps = mSettings.mPackages.get(pkgName);
12505 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12507 // Quick sanity check that we're signed correctly if updating;
12508 // we'll check this again later when scanning, but we want to
12509 // bail early here before tripping over redefined permissions.
12510 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12511 if (!checkUpgradeKeySetLP(ps, pkg)) {
12512 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12513 + pkg.packageName + " upgrade keys do not match the "
12514 + "previously installed version");
12519 verifySignaturesLP(ps, pkg);
12520 } catch (PackageManagerException e) {
12521 res.setError(e.error, e.getMessage());
12526 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12527 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12528 systemApp = (ps.pkg.applicationInfo.flags &
12529 ApplicationInfo.FLAG_SYSTEM) != 0;
12531 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12534 // Check whether the newly-scanned package wants to define an already-defined perm
12535 int N = pkg.permissions.size();
12536 for (int i = N-1; i >= 0; i--) {
12537 PackageParser.Permission perm = pkg.permissions.get(i);
12538 BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12540 // If the defining package is signed with our cert, it's okay. This
12541 // also includes the "updating the same package" case, of course.
12542 // "updating same package" could also involve key-rotation.
12543 final boolean sigsOk;
12544 if (bp.sourcePackage.equals(pkg.packageName)
12545 && (bp.packageSetting instanceof PackageSetting)
12546 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12548 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12550 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12551 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12554 // If the owning package is the system itself, we log but allow
12555 // install to proceed; we fail the install on all other permission
12557 if (!bp.sourcePackage.equals("android")) {
12558 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12559 + pkg.packageName + " attempting to redeclare permission "
12560 + perm.info.name + " already owned by " + bp.sourcePackage);
12561 res.origPermission = perm.info.name;
12562 res.origPackage = bp.sourcePackage;
12565 Slog.w(TAG, "Package " + pkg.packageName
12566 + " attempting to redeclare system permission "
12567 + perm.info.name + "; ignoring new declaration");
12568 pkg.permissions.remove(i);
12576 if (systemApp && onExternal) {
12577 // Disable updates to system apps on sdcard
12578 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12579 "Cannot install updates to system apps on sdcard");
12583 if (args.move != null) {
12584 // We did an in-place move, so dex is ready to roll
12585 scanFlags |= SCAN_NO_DEX;
12586 scanFlags |= SCAN_MOVE;
12588 synchronized (mPackages) {
12589 final PackageSetting ps = mSettings.mPackages.get(pkgName);
12591 res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12592 "Missing settings for moved package " + pkgName);
12595 // We moved the entire application as-is, so bring over the
12596 // previously derived ABI information.
12597 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12598 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12601 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12602 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12603 scanFlags |= SCAN_NO_DEX;
12606 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12607 true /* extract libs */);
12608 } catch (PackageManagerException pme) {
12609 Slog.e(TAG, "Error deriving application ABI", pme);
12610 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12614 // Run dexopt before old package gets removed, to minimize time when app is unavailable
12615 int result = mPackageDexOptimizer
12616 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12617 false /* defer */, false /* inclDependencies */);
12618 if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12619 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12624 if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12625 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12629 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12632 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12633 installerPackageName, volumeUuid, res);
12635 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12636 args.user, installerPackageName, volumeUuid, res);
12638 synchronized (mPackages) {
12639 final PackageSetting ps = mSettings.mPackages.get(pkgName);
12641 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12646 private void startIntentFilterVerifications(int userId, boolean replacing,
12647 PackageParser.Package pkg) {
12648 if (mIntentFilterVerifierComponent == null) {
12649 Slog.w(TAG, "No IntentFilter verification will not be done as "
12650 + "there is no IntentFilterVerifier available!");
12654 final int verifierUid = getPackageUid(
12655 mIntentFilterVerifierComponent.getPackageName(),
12656 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12658 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12659 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12660 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12661 mHandler.sendMessage(msg);
12664 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12665 PackageParser.Package pkg) {
12666 int size = pkg.activities.size();
12668 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12669 "No activity, so no need to verify any IntentFilter!");
12673 final boolean hasDomainURLs = hasDomainURLs(pkg);
12674 if (!hasDomainURLs) {
12675 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12676 "No domain URLs, so no need to verify any IntentFilter!");
12680 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12681 + " if any IntentFilter from the " + size
12682 + " Activities needs verification ...");
12685 final String packageName = pkg.packageName;
12687 synchronized (mPackages) {
12688 // If this is a new install and we see that we've already run verification for this
12689 // package, we have nothing to do: it means the state was restored from backup.
12691 IntentFilterVerificationInfo ivi =
12692 mSettings.getIntentFilterVerificationLPr(packageName);
12694 if (DEBUG_DOMAIN_VERIFICATION) {
12695 Slog.i(TAG, "Package " + packageName+ " already verified: status="
12696 + ivi.getStatusString());
12702 // If any filters need to be verified, then all need to be.
12703 boolean needToVerify = false;
12704 for (PackageParser.Activity a : pkg.activities) {
12705 for (ActivityIntentInfo filter : a.intents) {
12706 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12707 if (DEBUG_DOMAIN_VERIFICATION) {
12708 Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12710 needToVerify = true;
12716 if (needToVerify) {
12717 final int verificationId = mIntentFilterVerificationToken++;
12718 for (PackageParser.Activity a : pkg.activities) {
12719 for (ActivityIntentInfo filter : a.intents) {
12720 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12721 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12722 "Verification needed for IntentFilter:" + filter.toString());
12723 mIntentFilterVerifier.addOneIntentFilterVerification(
12724 verifierUid, userId, verificationId, filter, packageName);
12733 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12734 + " IntentFilter verification" + (count > 1 ? "s" : "")
12735 + " for userId:" + userId);
12736 mIntentFilterVerifier.startVerifications(userId);
12738 if (DEBUG_DOMAIN_VERIFICATION) {
12739 Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12744 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12745 final ComponentName cn = filter.activity.getComponentName();
12746 final String packageName = cn.getPackageName();
12748 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12753 int status = ivi.getStatus();
12755 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12756 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12765 private static boolean isMultiArch(PackageSetting ps) {
12766 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12769 private static boolean isMultiArch(ApplicationInfo info) {
12770 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12773 private static boolean isExternal(PackageParser.Package pkg) {
12774 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12777 private static boolean isExternal(PackageSetting ps) {
12778 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12781 private static boolean isExternal(ApplicationInfo info) {
12782 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12785 private static boolean isSystemApp(PackageParser.Package pkg) {
12786 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12789 private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12790 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12793 private static boolean hasDomainURLs(PackageParser.Package pkg) {
12794 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12797 private static boolean isSystemApp(PackageSetting ps) {
12798 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12801 private static boolean isUpdatedSystemApp(PackageSetting ps) {
12802 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12805 private int packageFlagsToInstallFlags(PackageSetting ps) {
12806 int installFlags = 0;
12807 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12808 // This existing package was an external ASEC install when we have
12809 // the external flag without a UUID
12810 installFlags |= PackageManager.INSTALL_EXTERNAL;
12812 if (ps.isForwardLocked()) {
12813 installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12815 return installFlags;
12818 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12819 if (isExternal(pkg)) {
12820 if (TextUtils.isEmpty(pkg.volumeUuid)) {
12821 return mSettings.getExternalVersion();
12823 return mSettings.findOrCreateVersion(pkg.volumeUuid);
12826 return mSettings.getInternalVersion();
12830 private void deleteTempPackageFiles() {
12831 final FilenameFilter filter = new FilenameFilter() {
12832 public boolean accept(File dir, String name) {
12833 return name.startsWith("vmdl") && name.endsWith(".tmp");
12836 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12842 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12844 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12849 public void deletePackage(final String packageName,
12850 final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12851 mContext.enforceCallingOrSelfPermission(
12852 android.Manifest.permission.DELETE_PACKAGES, null);
12853 Preconditions.checkNotNull(packageName);
12854 Preconditions.checkNotNull(observer);
12855 final int uid = Binder.getCallingUid();
12856 if (UserHandle.getUserId(uid) != userId) {
12857 mContext.enforceCallingPermission(
12858 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12859 "deletePackage for user " + userId);
12861 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12863 observer.onPackageDeleted(packageName,
12864 PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12865 } catch (RemoteException re) {
12870 boolean uninstallBlocked = false;
12871 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12872 int[] users = sUserManager.getUserIds();
12873 for (int i = 0; i < users.length; ++i) {
12874 if (getBlockUninstallForUser(packageName, users[i])) {
12875 uninstallBlocked = true;
12880 uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12882 if (uninstallBlocked) {
12884 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12886 } catch (RemoteException re) {
12891 if (DEBUG_REMOVE) {
12892 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12894 // Queue up an async operation since the package deletion may take a little while.
12895 mHandler.post(new Runnable() {
12896 public void run() {
12897 mHandler.removeCallbacks(this);
12898 final int returnCode = deletePackageX(packageName, userId, flags);
12899 if (observer != null) {
12901 observer.onPackageDeleted(packageName, returnCode, null);
12902 } catch (RemoteException e) {
12903 Log.i(TAG, "Observer no longer exists.");
12910 private boolean isPackageDeviceAdmin(String packageName, int userId) {
12911 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12912 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12915 if (dpm.isDeviceOwner(packageName)) {
12919 if (userId == UserHandle.USER_ALL) {
12920 users = sUserManager.getUserIds();
12922 users = new int[]{userId};
12924 for (int i = 0; i < users.length; ++i) {
12925 if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12930 } catch (RemoteException e) {
12936 * This method is an internal method that could be get invoked either
12937 * to delete an installed package or to clean up a failed installation.
12938 * After deleting an installed package, a broadcast is sent to notify any
12939 * listeners that the package has been installed. For cleaning up a failed
12940 * installation, the broadcast is not necessary since the package's
12941 * installation wouldn't have sent the initial broadcast either
12942 * The key steps in deleting a package are
12943 * deleting the package information in internal structures like mPackages,
12944 * deleting the packages base directories through installd
12945 * updating mSettings to reflect current status
12946 * persisting settings for later use
12947 * sending a broadcast if necessary
12949 private int deletePackageX(String packageName, int userId, int flags) {
12950 final PackageRemovedInfo info = new PackageRemovedInfo();
12953 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12954 ? UserHandle.ALL : new UserHandle(userId);
12956 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12957 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12958 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12961 boolean removedForAllUsers = false;
12962 boolean systemUpdate = false;
12964 // for the uninstall-updates case and restricted profiles, remember the per-
12965 // userhandle installed state
12967 boolean[] perUserInstalled;
12968 synchronized (mPackages) {
12969 PackageSetting ps = mSettings.mPackages.get(packageName);
12970 allUsers = sUserManager.getUserIds();
12971 perUserInstalled = new boolean[allUsers.length];
12972 for (int i = 0; i < allUsers.length; i++) {
12973 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12977 synchronized (mInstallLock) {
12978 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12979 res = deletePackageLI(packageName, removeForUser,
12980 true, allUsers, perUserInstalled,
12981 flags | REMOVE_CHATTY, info, true);
12982 systemUpdate = info.isRemovedPackageSystemUpdate;
12983 if (res && !systemUpdate && mPackages.get(packageName) == null) {
12984 removedForAllUsers = true;
12986 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12987 + " removedForAllUsers=" + removedForAllUsers);
12991 info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12993 // If the removed package was a system update, the old system package
12994 // was re-enabled; we need to broadcast this information
12995 if (systemUpdate) {
12996 Bundle extras = new Bundle(1);
12997 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12998 ? info.removedAppId : info.uid);
12999 extras.putBoolean(Intent.EXTRA_REPLACING, true);
13001 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13002 extras, null, null, null);
13003 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13004 extras, null, null, null);
13005 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13006 null, packageName, null, null);
13009 // Force a gc here.
13010 Runtime.getRuntime().gc();
13011 // Delete the resources here after sending the broadcast to let
13012 // other processes clean up before deleting resources.
13013 if (info.args != null) {
13014 synchronized (mInstallLock) {
13015 info.args.doPostDeleteLI(true);
13019 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13022 class PackageRemovedInfo {
13023 String removedPackage;
13025 int removedAppId = -1;
13026 int[] removedUsers = null;
13027 boolean isRemovedPackageSystemUpdate = false;
13028 // Clean up resources deleted packages.
13029 InstallArgs args = null;
13031 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13032 Bundle extras = new Bundle(1);
13033 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13034 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13036 extras.putBoolean(Intent.EXTRA_REPLACING, true);
13038 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13039 if (removedPackage != null) {
13040 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13041 extras, null, null, removedUsers);
13042 if (fullRemove && !replacing) {
13043 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13044 extras, null, null, removedUsers);
13047 if (removedAppId >= 0) {
13048 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
13055 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13056 * flag is not set, the data directory is removed as well.
13057 * make sure this flag is set for partially installed apps. If not its meaningless to
13058 * delete a partially installed application.
13060 private void removePackageDataLI(PackageSetting ps,
13061 int[] allUserHandles, boolean[] perUserInstalled,
13062 PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13063 String packageName = ps.name;
13064 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13065 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13066 // Retrieve object to delete permissions for shared user later on
13067 final PackageSetting deletedPs;
13069 synchronized (mPackages) {
13070 deletedPs = mSettings.mPackages.get(packageName);
13071 if (outInfo != null) {
13072 outInfo.removedPackage = packageName;
13073 outInfo.removedUsers = deletedPs != null
13074 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13078 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13079 removeDataDirsLI(ps.volumeUuid, packageName);
13080 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13083 synchronized (mPackages) {
13084 if (deletedPs != null) {
13085 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13086 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13087 clearDefaultBrowserIfNeeded(packageName);
13088 if (outInfo != null) {
13089 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13090 outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13092 updatePermissionsLPw(deletedPs.name, null, 0);
13093 if (deletedPs.sharedUser != null) {
13094 // Remove permissions associated with package. Since runtime
13095 // permissions are per user we have to kill the removed package
13096 // or packages running under the shared user of the removed
13097 // package if revoking the permissions requested only by the removed
13098 // package is successful and this causes a change in gids.
13099 for (int userId : UserManagerService.getInstance().getUserIds()) {
13100 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13102 if (userIdToKill == UserHandle.USER_ALL
13103 || userIdToKill >= UserHandle.USER_OWNER) {
13104 // If gids changed for this user, kill all affected packages.
13105 mHandler.post(new Runnable() {
13107 public void run() {
13108 // This has to happen with no lock held.
13109 killApplication(deletedPs.name, deletedPs.appId,
13110 KILL_APP_REASON_GIDS_CHANGED);
13117 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13119 // make sure to preserve per-user disabled state if this removal was just
13120 // a downgrade of a system app to the factory package
13121 if (allUserHandles != null && perUserInstalled != null) {
13122 if (DEBUG_REMOVE) {
13123 Slog.d(TAG, "Propagating install state across downgrade");
13125 for (int i = 0; i < allUserHandles.length; i++) {
13126 if (DEBUG_REMOVE) {
13127 Slog.d(TAG, " user " + allUserHandles[i]
13128 + " => " + perUserInstalled[i]);
13130 ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13134 // can downgrade to reader
13135 if (writeSettings) {
13136 // Save settings now
13137 mSettings.writeLPr();
13140 if (outInfo != null) {
13141 // A user ID was deleted here. Go through all users and remove it
13143 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13147 static boolean locationIsPrivileged(File path) {
13149 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13150 .getCanonicalPath();
13151 return path.getCanonicalPath().startsWith(privilegedAppDir);
13152 } catch (IOException e) {
13153 Slog.e(TAG, "Unable to access code path " + path);
13159 * Tries to delete system package.
13161 private boolean deleteSystemPackageLI(PackageSetting newPs,
13162 int[] allUserHandles, boolean[] perUserInstalled,
13163 int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13164 final boolean applyUserRestrictions
13165 = (allUserHandles != null) && (perUserInstalled != null);
13166 PackageSetting disabledPs = null;
13167 // Confirm if the system package has been updated
13168 // An updated system app can be deleted. This will also have to restore
13169 // the system pkg from system partition
13171 synchronized (mPackages) {
13172 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13174 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13175 + " disabledPs=" + disabledPs);
13176 if (disabledPs == null) {
13177 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13179 } else if (DEBUG_REMOVE) {
13180 Slog.d(TAG, "Deleting system pkg from data partition");
13182 if (DEBUG_REMOVE) {
13183 if (applyUserRestrictions) {
13184 Slog.d(TAG, "Remembering install states:");
13185 for (int i = 0; i < allUserHandles.length; i++) {
13186 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13190 // Delete the updated package
13191 outInfo.isRemovedPackageSystemUpdate = true;
13192 if (disabledPs.versionCode < newPs.versionCode) {
13193 // Delete data for downgrades
13194 flags &= ~PackageManager.DELETE_KEEP_DATA;
13196 // Preserve data by setting flag
13197 flags |= PackageManager.DELETE_KEEP_DATA;
13199 boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13200 allUserHandles, perUserInstalled, outInfo, writeSettings);
13205 synchronized (mPackages) {
13206 // Reinstate the old system package
13207 mSettings.enableSystemPackageLPw(newPs.name);
13208 // Remove any native libraries from the upgraded package.
13209 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13211 // Install the system package
13212 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13213 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13214 if (locationIsPrivileged(disabledPs.codePath)) {
13215 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13218 final PackageParser.Package newPkg;
13220 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13221 } catch (PackageManagerException e) {
13222 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13227 synchronized (mPackages) {
13228 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13230 // Propagate the permissions state as we do not want to drop on the floor
13231 // runtime permissions. The update permissions method below will take
13232 // care of removing obsolete permissions and grant install permissions.
13233 ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13234 updatePermissionsLPw(newPkg.packageName, newPkg,
13235 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13237 if (applyUserRestrictions) {
13238 if (DEBUG_REMOVE) {
13239 Slog.d(TAG, "Propagating install state across reinstall");
13241 for (int i = 0; i < allUserHandles.length; i++) {
13242 if (DEBUG_REMOVE) {
13243 Slog.d(TAG, " user " + allUserHandles[i]
13244 + " => " + perUserInstalled[i]);
13246 ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13248 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13250 // Regardless of writeSettings we need to ensure that this restriction
13251 // state propagation is persisted
13252 mSettings.writeAllUsersPackageRestrictionsLPr();
13254 // can downgrade to reader here
13255 if (writeSettings) {
13256 mSettings.writeLPr();
13262 private boolean deleteInstalledPackageLI(PackageSetting ps,
13263 boolean deleteCodeAndResources, int flags,
13264 int[] allUserHandles, boolean[] perUserInstalled,
13265 PackageRemovedInfo outInfo, boolean writeSettings) {
13266 if (outInfo != null) {
13267 outInfo.uid = ps.appId;
13270 // Delete package data from internal structures and also remove data if flag is set
13271 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13273 // Delete application code and resources
13274 if (deleteCodeAndResources && (outInfo != null)) {
13275 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13276 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13277 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13283 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13285 mContext.enforceCallingOrSelfPermission(
13286 android.Manifest.permission.DELETE_PACKAGES, null);
13287 synchronized (mPackages) {
13288 PackageSetting ps = mSettings.mPackages.get(packageName);
13290 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13293 if (!ps.getInstalled(userId)) {
13294 // Can't block uninstall for an app that is not installed or enabled.
13295 Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13298 ps.setBlockUninstall(blockUninstall, userId);
13299 mSettings.writePackageRestrictionsLPr(userId);
13305 public boolean getBlockUninstallForUser(String packageName, int userId) {
13306 synchronized (mPackages) {
13307 PackageSetting ps = mSettings.mPackages.get(packageName);
13309 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13312 return ps.getBlockUninstall(userId);
13317 * This method handles package deletion in general
13319 private boolean deletePackageLI(String packageName, UserHandle user,
13320 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13321 int flags, PackageRemovedInfo outInfo,
13322 boolean writeSettings) {
13323 if (packageName == null) {
13324 Slog.w(TAG, "Attempt to delete null packageName.");
13327 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13329 boolean dataOnly = false;
13330 int removeUser = -1;
13332 synchronized (mPackages) {
13333 ps = mSettings.mPackages.get(packageName);
13335 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13338 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13339 && user.getIdentifier() != UserHandle.USER_ALL) {
13340 // The caller is asking that the package only be deleted for a single
13341 // user. To do this, we just mark its uninstalled state and delete
13342 // its data. If this is a system app, we only allow this to happen if
13343 // they have set the special DELETE_SYSTEM_APP which requests different
13344 // semantics than normal for uninstalling system apps.
13345 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13346 final int userId = user.getIdentifier();
13347 ps.setUserState(userId,
13348 COMPONENT_ENABLED_STATE_DEFAULT,
13351 true, //notLaunched
13354 false, // blockUninstall
13355 ps.readUserState(userId).domainVerificationStatus, 0);
13356 if (!isSystemApp(ps)) {
13357 if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13358 // Other user still have this package installed, so all
13359 // we need to do is clear this user's data and save that
13360 // it is uninstalled.
13361 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13362 removeUser = user.getIdentifier();
13364 scheduleWritePackageRestrictionsLocked(removeUser);
13366 // We need to set it back to 'installed' so the uninstall
13367 // broadcasts will be sent correctly.
13368 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13369 ps.setInstalled(true, user.getIdentifier());
13372 // This is a system app, so we assume that the
13373 // other users still have this package installed, so all
13374 // we need to do is clear this user's data and save that
13375 // it is uninstalled.
13376 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13377 removeUser = user.getIdentifier();
13379 scheduleWritePackageRestrictionsLocked(removeUser);
13384 if (removeUser >= 0) {
13385 // From above, we determined that we are deleting this only
13386 // for a single user. Continue the work here.
13387 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13388 if (outInfo != null) {
13389 outInfo.removedPackage = packageName;
13390 outInfo.removedAppId = appId;
13391 outInfo.removedUsers = new int[] {removeUser};
13393 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13394 removeKeystoreDataIfNeeded(removeUser, appId);
13395 schedulePackageCleaning(packageName, removeUser, false);
13396 synchronized (mPackages) {
13397 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13398 scheduleWritePackageRestrictionsLocked(removeUser);
13400 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13406 // Delete application data first
13407 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13408 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13412 boolean ret = false;
13413 if (isSystemApp(ps)) {
13414 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13415 // When an updated system application is deleted we delete the existing resources as well and
13416 // fall back to existing code in system partition
13417 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13418 flags, outInfo, writeSettings);
13420 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13421 // Kill application pre-emptively especially for apps on sd.
13422 killApplication(packageName, ps.appId, "uninstall pkg");
13423 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13424 allUserHandles, perUserInstalled,
13425 outInfo, writeSettings);
13431 private final class ClearStorageConnection implements ServiceConnection {
13432 IMediaContainerService mContainerService;
13435 public void onServiceConnected(ComponentName name, IBinder service) {
13436 synchronized (this) {
13437 mContainerService = IMediaContainerService.Stub.asInterface(service);
13443 public void onServiceDisconnected(ComponentName name) {
13447 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13448 final boolean mounted;
13449 if (Environment.isExternalStorageEmulated()) {
13452 final String status = Environment.getExternalStorageState();
13454 mounted = status.equals(Environment.MEDIA_MOUNTED)
13455 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13462 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13464 if (userId == UserHandle.USER_ALL) {
13465 users = sUserManager.getUserIds();
13467 users = new int[] { userId };
13469 final ClearStorageConnection conn = new ClearStorageConnection();
13470 if (mContext.bindServiceAsUser(
13471 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13473 for (int curUser : users) {
13474 long timeout = SystemClock.uptimeMillis() + 5000;
13475 synchronized (conn) {
13476 long now = SystemClock.uptimeMillis();
13477 while (conn.mContainerService == null && now < timeout) {
13479 conn.wait(timeout - now);
13480 } catch (InterruptedException e) {
13484 if (conn.mContainerService == null) {
13488 final UserEnvironment userEnv = new UserEnvironment(curUser);
13489 clearDirectory(conn.mContainerService,
13490 userEnv.buildExternalStorageAppCacheDirs(packageName));
13492 clearDirectory(conn.mContainerService,
13493 userEnv.buildExternalStorageAppDataDirs(packageName));
13494 clearDirectory(conn.mContainerService,
13495 userEnv.buildExternalStorageAppMediaDirs(packageName));
13499 mContext.unbindService(conn);
13505 public void clearApplicationUserData(final String packageName,
13506 final IPackageDataObserver observer, final int userId) {
13507 mContext.enforceCallingOrSelfPermission(
13508 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13509 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13510 // Queue up an async operation since the package deletion may take a little while.
13511 mHandler.post(new Runnable() {
13512 public void run() {
13513 mHandler.removeCallbacks(this);
13514 final boolean succeeded;
13515 synchronized (mInstallLock) {
13516 succeeded = clearApplicationUserDataLI(packageName, userId);
13518 clearExternalStorageDataSync(packageName, userId, true);
13520 // invoke DeviceStorageMonitor's update method to clear any notifications
13521 DeviceStorageMonitorInternal
13522 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13527 if(observer != null) {
13529 observer.onRemoveCompleted(packageName, succeeded);
13530 } catch (RemoteException e) {
13531 Log.i(TAG, "Observer no longer exists.");
13533 } //end if observer
13538 private boolean clearApplicationUserDataLI(String packageName, int userId) {
13539 if (packageName == null) {
13540 Slog.w(TAG, "Attempt to delete null packageName.");
13544 // Try finding details about the requested package
13545 PackageParser.Package pkg;
13546 synchronized (mPackages) {
13547 pkg = mPackages.get(packageName);
13549 final PackageSetting ps = mSettings.mPackages.get(packageName);
13556 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13560 PackageSetting ps = (PackageSetting) pkg.mExtras;
13561 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13564 // Always delete data directories for package, even if we found no other
13565 // record of app. This helps users recover from UID mismatches without
13566 // resorting to a full data wipe.
13567 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13569 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13573 final int appId = pkg.applicationInfo.uid;
13574 removeKeystoreDataIfNeeded(userId, appId);
13576 // Create a native library symlink only if we have native libraries
13577 // and if the native libraries are 32 bit libraries. We do not provide
13578 // this symlink for 64 bit libraries.
13579 if (pkg.applicationInfo.primaryCpuAbi != null &&
13580 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13581 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13582 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13583 nativeLibPath, userId) < 0) {
13584 Slog.w(TAG, "Failed linking native library dir");
13593 * Reverts user permission state changes (permissions and flags) in
13594 * all packages for a given user.
13596 * @param userId The device user for which to do a reset.
13598 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13599 final int packageCount = mPackages.size();
13600 for (int i = 0; i < packageCount; i++) {
13601 PackageParser.Package pkg = mPackages.valueAt(i);
13602 PackageSetting ps = (PackageSetting) pkg.mExtras;
13603 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13608 * Reverts user permission state changes (permissions and flags).
13610 * @param ps The package for which to reset.
13611 * @param userId The device user for which to do a reset.
13613 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13614 final PackageSetting ps, final int userId) {
13615 if (ps.pkg == null) {
13619 final int userSettableFlags = FLAG_PERMISSION_USER_SET
13620 | FLAG_PERMISSION_USER_FIXED
13621 | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13623 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13624 | FLAG_PERMISSION_POLICY_FIXED;
13626 boolean writeInstallPermissions = false;
13627 boolean writeRuntimePermissions = false;
13629 final int permissionCount = ps.pkg.requestedPermissions.size();
13630 for (int i = 0; i < permissionCount; i++) {
13631 String permission = ps.pkg.requestedPermissions.get(i);
13633 BasePermission bp = mSettings.mPermissions.get(permission);
13638 // If shared user we just reset the state to which only this app contributed.
13639 if (ps.sharedUser != null) {
13640 boolean used = false;
13641 final int packageCount = ps.sharedUser.packages.size();
13642 for (int j = 0; j < packageCount; j++) {
13643 PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13644 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13645 && pkg.pkg.requestedPermissions.contains(permission)) {
13655 PermissionsState permissionsState = ps.getPermissionsState();
13657 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13659 // Always clear the user settable flags.
13660 final boolean hasInstallState = permissionsState.getInstallPermissionState(
13662 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13663 if (hasInstallState) {
13664 writeInstallPermissions = true;
13666 writeRuntimePermissions = true;
13670 // Below is only runtime permission handling.
13671 if (!bp.isRuntime()) {
13675 // Never clobber system or policy.
13676 if ((oldFlags & policyOrSystemFlags) != 0) {
13680 // If this permission was granted by default, make sure it is.
13681 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13682 if (permissionsState.grantRuntimePermission(bp, userId)
13683 != PERMISSION_OPERATION_FAILURE) {
13684 writeRuntimePermissions = true;
13687 // Otherwise, reset the permission.
13688 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13689 switch (revokeResult) {
13690 case PERMISSION_OPERATION_SUCCESS: {
13691 writeRuntimePermissions = true;
13694 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13695 writeRuntimePermissions = true;
13696 final int appId = ps.appId;
13697 mHandler.post(new Runnable() {
13699 public void run() {
13700 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13708 // Synchronously write as we are taking permissions away.
13709 if (writeRuntimePermissions) {
13710 mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13713 // Synchronously write as we are taking permissions away.
13714 if (writeInstallPermissions) {
13715 mSettings.writeLPr();
13720 * Remove entries from the keystore daemon. Will only remove it if the
13721 * {@code appId} is valid.
13723 private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13728 final KeyStore keyStore = KeyStore.getInstance();
13729 if (keyStore != null) {
13730 if (userId == UserHandle.USER_ALL) {
13731 for (final int individual : sUserManager.getUserIds()) {
13732 keyStore.clearUid(UserHandle.getUid(individual, appId));
13735 keyStore.clearUid(UserHandle.getUid(userId, appId));
13738 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13743 public void deleteApplicationCacheFiles(final String packageName,
13744 final IPackageDataObserver observer) {
13745 mContext.enforceCallingOrSelfPermission(
13746 android.Manifest.permission.DELETE_CACHE_FILES, null);
13747 // Queue up an async operation since the package deletion may take a little while.
13748 final int userId = UserHandle.getCallingUserId();
13749 mHandler.post(new Runnable() {
13750 public void run() {
13751 mHandler.removeCallbacks(this);
13752 final boolean succeded;
13753 synchronized (mInstallLock) {
13754 succeded = deleteApplicationCacheFilesLI(packageName, userId);
13756 clearExternalStorageDataSync(packageName, userId, false);
13757 if (observer != null) {
13759 observer.onRemoveCompleted(packageName, succeded);
13760 } catch (RemoteException e) {
13761 Log.i(TAG, "Observer no longer exists.");
13763 } //end if observer
13768 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13769 if (packageName == null) {
13770 Slog.w(TAG, "Attempt to delete null packageName.");
13773 PackageParser.Package p;
13774 synchronized (mPackages) {
13775 p = mPackages.get(packageName);
13778 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13781 final ApplicationInfo applicationInfo = p.applicationInfo;
13782 if (applicationInfo == null) {
13783 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13786 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13788 Slog.w(TAG, "Couldn't remove cache files for package: "
13789 + packageName + " u" + userId);
13796 public void getPackageSizeInfo(final String packageName, int userHandle,
13797 final IPackageStatsObserver observer) {
13798 mContext.enforceCallingOrSelfPermission(
13799 android.Manifest.permission.GET_PACKAGE_SIZE, null);
13800 if (packageName == null) {
13801 throw new IllegalArgumentException("Attempt to get size of null packageName");
13804 PackageStats stats = new PackageStats(packageName, userHandle);
13807 * Queue up an async operation since the package measurement may take a
13810 Message msg = mHandler.obtainMessage(INIT_COPY);
13811 msg.obj = new MeasureParams(stats, observer);
13812 mHandler.sendMessage(msg);
13815 private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13816 PackageStats pStats) {
13817 if (packageName == null) {
13818 Slog.w(TAG, "Attempt to get size of null packageName.");
13821 PackageParser.Package p;
13822 boolean dataOnly = false;
13823 String libDirRoot = null;
13824 String asecPath = null;
13825 PackageSetting ps = null;
13826 synchronized (mPackages) {
13827 p = mPackages.get(packageName);
13828 ps = mSettings.mPackages.get(packageName);
13831 if((ps == null) || (ps.pkg == null)) {
13832 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13838 libDirRoot = ps.legacyNativeLibraryPathString;
13840 if (p != null && (isExternal(p) || p.isForwardLocked())) {
13841 final long token = Binder.clearCallingIdentity();
13843 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13844 if (secureContainerId != null) {
13845 asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13848 Binder.restoreCallingIdentity(token);
13852 String publicSrcDir = null;
13854 final ApplicationInfo applicationInfo = p.applicationInfo;
13855 if (applicationInfo == null) {
13856 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13859 if (p.isForwardLocked()) {
13860 publicSrcDir = applicationInfo.getBaseResourcePath();
13863 // TODO: extend to measure size of split APKs
13864 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13865 // not just the first level.
13866 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13867 // just the primary.
13868 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13869 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13870 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13875 // Fix-up for forward-locked applications in ASEC containers.
13876 if (!isExternal(p)) {
13877 pStats.codeSize += pStats.externalCodeSize;
13878 pStats.externalCodeSize = 0L;
13886 public void addPackageToPreferred(String packageName) {
13887 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13891 public void removePackageFromPreferred(String packageName) {
13892 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13896 public List<PackageInfo> getPreferredPackages(int flags) {
13897 return new ArrayList<PackageInfo>();
13900 private int getUidTargetSdkVersionLockedLPr(int uid) {
13901 Object obj = mSettings.getUserIdLPr(uid);
13902 if (obj instanceof SharedUserSetting) {
13903 final SharedUserSetting sus = (SharedUserSetting) obj;
13904 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13905 final Iterator<PackageSetting> it = sus.packages.iterator();
13906 while (it.hasNext()) {
13907 final PackageSetting ps = it.next();
13908 if (ps.pkg != null) {
13909 int v = ps.pkg.applicationInfo.targetSdkVersion;
13910 if (v < vers) vers = v;
13914 } else if (obj instanceof PackageSetting) {
13915 final PackageSetting ps = (PackageSetting) obj;
13916 if (ps.pkg != null) {
13917 return ps.pkg.applicationInfo.targetSdkVersion;
13920 return Build.VERSION_CODES.CUR_DEVELOPMENT;
13924 public void addPreferredActivity(IntentFilter filter, int match,
13925 ComponentName[] set, ComponentName activity, int userId) {
13926 addPreferredActivityInternal(filter, match, set, activity, true, userId,
13927 "Adding preferred");
13930 private void addPreferredActivityInternal(IntentFilter filter, int match,
13931 ComponentName[] set, ComponentName activity, boolean always, int userId,
13934 int callingUid = Binder.getCallingUid();
13935 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13936 if (filter.countActions() == 0) {
13937 Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13940 synchronized (mPackages) {
13941 if (mContext.checkCallingOrSelfPermission(
13942 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13943 != PackageManager.PERMISSION_GRANTED) {
13944 if (getUidTargetSdkVersionLockedLPr(callingUid)
13945 < Build.VERSION_CODES.FROYO) {
13946 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13950 mContext.enforceCallingOrSelfPermission(
13951 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13954 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13955 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13957 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
13958 pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13959 scheduleWritePackageRestrictionsLocked(userId);
13964 public void replacePreferredActivity(IntentFilter filter, int match,
13965 ComponentName[] set, ComponentName activity, int userId) {
13966 if (filter.countActions() != 1) {
13967 throw new IllegalArgumentException(
13968 "replacePreferredActivity expects filter to have only 1 action.");
13970 if (filter.countDataAuthorities() != 0
13971 || filter.countDataPaths() != 0
13972 || filter.countDataSchemes() > 1
13973 || filter.countDataTypes() != 0) {
13974 throw new IllegalArgumentException(
13975 "replacePreferredActivity expects filter to have no data authorities, " +
13976 "paths, or types; and at most one scheme.");
13979 final int callingUid = Binder.getCallingUid();
13980 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13981 synchronized (mPackages) {
13982 if (mContext.checkCallingOrSelfPermission(
13983 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13984 != PackageManager.PERMISSION_GRANTED) {
13985 if (getUidTargetSdkVersionLockedLPr(callingUid)
13986 < Build.VERSION_CODES.FROYO) {
13987 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13988 + Binder.getCallingUid());
13991 mContext.enforceCallingOrSelfPermission(
13992 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13995 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13997 // Get all of the existing entries that exactly match this filter.
13998 ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13999 if (existing != null && existing.size() == 1) {
14000 PreferredActivity cur = existing.get(0);
14001 if (DEBUG_PREFERRED) {
14002 Slog.i(TAG, "Checking replace of preferred:");
14003 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
14004 if (!cur.mPref.mAlways) {
14005 Slog.i(TAG, " -- CUR; not mAlways!");
14007 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch);
14008 Slog.i(TAG, " -- CUR: mSet="
14009 + Arrays.toString(cur.mPref.mSetComponents));
14010 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent);
14011 Slog.i(TAG, " -- NEW: mMatch="
14012 + (match&IntentFilter.MATCH_CATEGORY_MASK));
14013 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set));
14014 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString());
14017 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14018 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14019 && cur.mPref.sameSet(set)) {
14020 // Setting the preferred activity to what it happens to be already
14021 if (DEBUG_PREFERRED) {
14022 Slog.i(TAG, "Replacing with same preferred activity "
14023 + cur.mPref.mShortComponent + " for user "
14025 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
14031 if (existing != null) {
14032 if (DEBUG_PREFERRED) {
14033 Slog.i(TAG, existing.size() + " existing preferred matches for:");
14034 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
14036 for (int i = 0; i < existing.size(); i++) {
14037 PreferredActivity pa = existing.get(i);
14038 if (DEBUG_PREFERRED) {
14039 Slog.i(TAG, "Removing existing preferred activity "
14040 + pa.mPref.mComponent + ":");
14041 pa.dump(new LogPrinter(Log.INFO, TAG), " ");
14043 pir.removeFilter(pa);
14047 addPreferredActivityInternal(filter, match, set, activity, true, userId,
14048 "Replacing preferred");
14053 public void clearPackagePreferredActivities(String packageName) {
14054 final int uid = Binder.getCallingUid();
14056 synchronized (mPackages) {
14057 PackageParser.Package pkg = mPackages.get(packageName);
14058 if (pkg == null || pkg.applicationInfo.uid != uid) {
14059 if (mContext.checkCallingOrSelfPermission(
14060 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14061 != PackageManager.PERMISSION_GRANTED) {
14062 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14063 < Build.VERSION_CODES.FROYO) {
14064 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14065 + Binder.getCallingUid());
14068 mContext.enforceCallingOrSelfPermission(
14069 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14073 int user = UserHandle.getCallingUserId();
14074 if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14075 scheduleWritePackageRestrictionsLocked(user);
14080 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14081 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14082 ArrayList<PreferredActivity> removed = null;
14083 boolean changed = false;
14084 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14085 final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14086 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14087 if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14090 Iterator<PreferredActivity> it = pir.filterIterator();
14091 while (it.hasNext()) {
14092 PreferredActivity pa = it.next();
14093 // Mark entry for removal only if it matches the package name
14094 // and the entry is of type "always".
14095 if (packageName == null ||
14096 (pa.mPref.mComponent.getPackageName().equals(packageName)
14097 && pa.mPref.mAlways)) {
14098 if (removed == null) {
14099 removed = new ArrayList<PreferredActivity>();
14104 if (removed != null) {
14105 for (int j=0; j<removed.size(); j++) {
14106 PreferredActivity pa = removed.get(j);
14107 pir.removeFilter(pa);
14115 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14116 private void clearIntentFilterVerificationsLPw(int userId) {
14117 final int packageCount = mPackages.size();
14118 for (int i = 0; i < packageCount; i++) {
14119 PackageParser.Package pkg = mPackages.valueAt(i);
14120 clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14124 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14125 void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14126 if (userId == UserHandle.USER_ALL) {
14127 if (mSettings.removeIntentFilterVerificationLPw(packageName,
14128 sUserManager.getUserIds())) {
14129 for (int oneUserId : sUserManager.getUserIds()) {
14130 scheduleWritePackageRestrictionsLocked(oneUserId);
14134 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14135 scheduleWritePackageRestrictionsLocked(userId);
14140 void clearDefaultBrowserIfNeeded(String packageName) {
14141 for (int oneUserId : sUserManager.getUserIds()) {
14142 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14143 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14144 if (packageName.equals(defaultBrowserPackageName)) {
14145 setDefaultBrowserPackageName(null, oneUserId);
14151 public void resetApplicationPreferences(int userId) {
14152 mContext.enforceCallingOrSelfPermission(
14153 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14155 synchronized (mPackages) {
14156 final long identity = Binder.clearCallingIdentity();
14158 clearPackagePreferredActivitiesLPw(null, userId);
14159 mSettings.applyDefaultPreferredAppsLPw(this, userId);
14160 // TODO: We have to reset the default SMS and Phone. This requires
14161 // significant refactoring to keep all default apps in the package
14162 // manager (cleaner but more work) or have the services provide
14163 // callbacks to the package manager to request a default app reset.
14164 applyFactoryDefaultBrowserLPw(userId);
14165 clearIntentFilterVerificationsLPw(userId);
14166 primeDomainVerificationsLPw(userId);
14167 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14168 scheduleWritePackageRestrictionsLocked(userId);
14170 Binder.restoreCallingIdentity(identity);
14176 public int getPreferredActivities(List<IntentFilter> outFilters,
14177 List<ComponentName> outActivities, String packageName) {
14180 final int userId = UserHandle.getCallingUserId();
14182 synchronized (mPackages) {
14183 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14185 final Iterator<PreferredActivity> it = pir.filterIterator();
14186 while (it.hasNext()) {
14187 final PreferredActivity pa = it.next();
14188 if (packageName == null
14189 || (pa.mPref.mComponent.getPackageName().equals(packageName)
14190 && pa.mPref.mAlways)) {
14191 if (outFilters != null) {
14192 outFilters.add(new IntentFilter(pa));
14194 if (outActivities != null) {
14195 outActivities.add(pa.mPref.mComponent);
14206 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14208 int callingUid = Binder.getCallingUid();
14209 if (callingUid != Process.SYSTEM_UID) {
14210 throw new SecurityException(
14211 "addPersistentPreferredActivity can only be run by the system");
14213 if (filter.countActions() == 0) {
14214 Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14217 synchronized (mPackages) {
14218 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14220 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
14221 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14222 new PersistentPreferredActivity(filter, activity));
14223 scheduleWritePackageRestrictionsLocked(userId);
14228 public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14229 int callingUid = Binder.getCallingUid();
14230 if (callingUid != Process.SYSTEM_UID) {
14231 throw new SecurityException(
14232 "clearPackagePersistentPreferredActivities can only be run by the system");
14234 ArrayList<PersistentPreferredActivity> removed = null;
14235 boolean changed = false;
14236 synchronized (mPackages) {
14237 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14238 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14239 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14241 if (userId != thisUserId) {
14244 Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14245 while (it.hasNext()) {
14246 PersistentPreferredActivity ppa = it.next();
14247 // Mark entry for removal only if it matches the package name.
14248 if (ppa.mComponent.getPackageName().equals(packageName)) {
14249 if (removed == null) {
14250 removed = new ArrayList<PersistentPreferredActivity>();
14255 if (removed != null) {
14256 for (int j=0; j<removed.size(); j++) {
14257 PersistentPreferredActivity ppa = removed.get(j);
14258 ppir.removeFilter(ppa);
14265 scheduleWritePackageRestrictionsLocked(userId);
14271 * Common machinery for picking apart a restored XML blob and passing
14272 * it to a caller-supplied functor to be applied to the running system.
14274 private void restoreFromXml(XmlPullParser parser, int userId,
14275 String expectedStartTag, BlobXmlRestorer functor)
14276 throws IOException, XmlPullParserException {
14278 while ((type = parser.next()) != XmlPullParser.START_TAG
14279 && type != XmlPullParser.END_DOCUMENT) {
14281 if (type != XmlPullParser.START_TAG) {
14282 // oops didn't find a start tag?!
14283 if (DEBUG_BACKUP) {
14284 Slog.e(TAG, "Didn't find start tag during restore");
14289 // this is supposed to be TAG_PREFERRED_BACKUP
14290 if (!expectedStartTag.equals(parser.getName())) {
14291 if (DEBUG_BACKUP) {
14292 Slog.e(TAG, "Found unexpected tag " + parser.getName());
14297 // skip interfering stuff, then we're aligned with the backing implementation
14298 while ((type = parser.next()) == XmlPullParser.TEXT) { }
14299 functor.apply(parser, userId);
14302 private interface BlobXmlRestorer {
14303 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14307 * Non-Binder method, support for the backup/restore mechanism: write the
14308 * full set of preferred activities in its canonical XML format. Returns the
14309 * XML output as a byte array, or null if there is none.
14312 public byte[] getPreferredActivityBackup(int userId) {
14313 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14314 throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14317 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14319 final XmlSerializer serializer = new FastXmlSerializer();
14320 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14321 serializer.startDocument(null, true);
14322 serializer.startTag(null, TAG_PREFERRED_BACKUP);
14324 synchronized (mPackages) {
14325 mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14328 serializer.endTag(null, TAG_PREFERRED_BACKUP);
14329 serializer.endDocument();
14330 serializer.flush();
14331 } catch (Exception e) {
14332 if (DEBUG_BACKUP) {
14333 Slog.e(TAG, "Unable to write preferred activities for backup", e);
14338 return dataStream.toByteArray();
14342 public void restorePreferredActivities(byte[] backup, int userId) {
14343 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14344 throw new SecurityException("Only the system may call restorePreferredActivities()");
14348 final XmlPullParser parser = Xml.newPullParser();
14349 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14350 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14351 new BlobXmlRestorer() {
14353 public void apply(XmlPullParser parser, int userId)
14354 throws XmlPullParserException, IOException {
14355 synchronized (mPackages) {
14356 mSettings.readPreferredActivitiesLPw(parser, userId);
14360 } catch (Exception e) {
14361 if (DEBUG_BACKUP) {
14362 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14368 * Non-Binder method, support for the backup/restore mechanism: write the
14369 * default browser (etc) settings in its canonical XML format. Returns the default
14370 * browser XML representation as a byte array, or null if there is none.
14373 public byte[] getDefaultAppsBackup(int userId) {
14374 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14375 throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14378 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14380 final XmlSerializer serializer = new FastXmlSerializer();
14381 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14382 serializer.startDocument(null, true);
14383 serializer.startTag(null, TAG_DEFAULT_APPS);
14385 synchronized (mPackages) {
14386 mSettings.writeDefaultAppsLPr(serializer, userId);
14389 serializer.endTag(null, TAG_DEFAULT_APPS);
14390 serializer.endDocument();
14391 serializer.flush();
14392 } catch (Exception e) {
14393 if (DEBUG_BACKUP) {
14394 Slog.e(TAG, "Unable to write default apps for backup", e);
14399 return dataStream.toByteArray();
14403 public void restoreDefaultApps(byte[] backup, int userId) {
14404 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14405 throw new SecurityException("Only the system may call restoreDefaultApps()");
14409 final XmlPullParser parser = Xml.newPullParser();
14410 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14411 restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14412 new BlobXmlRestorer() {
14414 public void apply(XmlPullParser parser, int userId)
14415 throws XmlPullParserException, IOException {
14416 synchronized (mPackages) {
14417 mSettings.readDefaultAppsLPw(parser, userId);
14421 } catch (Exception e) {
14422 if (DEBUG_BACKUP) {
14423 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14429 public byte[] getIntentFilterVerificationBackup(int userId) {
14430 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14431 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14434 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14436 final XmlSerializer serializer = new FastXmlSerializer();
14437 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14438 serializer.startDocument(null, true);
14439 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14441 synchronized (mPackages) {
14442 mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14445 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14446 serializer.endDocument();
14447 serializer.flush();
14448 } catch (Exception e) {
14449 if (DEBUG_BACKUP) {
14450 Slog.e(TAG, "Unable to write default apps for backup", e);
14455 return dataStream.toByteArray();
14459 public void restoreIntentFilterVerification(byte[] backup, int userId) {
14460 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14461 throw new SecurityException("Only the system may call restorePreferredActivities()");
14465 final XmlPullParser parser = Xml.newPullParser();
14466 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14467 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14468 new BlobXmlRestorer() {
14470 public void apply(XmlPullParser parser, int userId)
14471 throws XmlPullParserException, IOException {
14472 synchronized (mPackages) {
14473 mSettings.readAllDomainVerificationsLPr(parser, userId);
14474 mSettings.writeLPr();
14478 } catch (Exception e) {
14479 if (DEBUG_BACKUP) {
14480 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14486 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14487 int sourceUserId, int targetUserId, int flags) {
14488 mContext.enforceCallingOrSelfPermission(
14489 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14490 int callingUid = Binder.getCallingUid();
14491 enforceOwnerRights(ownerPackage, callingUid);
14492 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14493 if (intentFilter.countActions() == 0) {
14494 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14497 synchronized (mPackages) {
14498 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14499 ownerPackage, targetUserId, flags);
14500 CrossProfileIntentResolver resolver =
14501 mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14502 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14503 // We have all those whose filter is equal. Now checking if the rest is equal as well.
14504 if (existing != null) {
14505 int size = existing.size();
14506 for (int i = 0; i < size; i++) {
14507 if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14512 resolver.addFilter(newFilter);
14513 scheduleWritePackageRestrictionsLocked(sourceUserId);
14518 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14519 mContext.enforceCallingOrSelfPermission(
14520 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14521 int callingUid = Binder.getCallingUid();
14522 enforceOwnerRights(ownerPackage, callingUid);
14523 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14524 synchronized (mPackages) {
14525 CrossProfileIntentResolver resolver =
14526 mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14527 ArraySet<CrossProfileIntentFilter> set =
14528 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14529 for (CrossProfileIntentFilter filter : set) {
14530 if (filter.getOwnerPackage().equals(ownerPackage)) {
14531 resolver.removeFilter(filter);
14534 scheduleWritePackageRestrictionsLocked(sourceUserId);
14538 // Enforcing that callingUid is owning pkg on userId
14539 private void enforceOwnerRights(String pkg, int callingUid) {
14540 // The system owns everything.
14541 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14544 int callingUserId = UserHandle.getUserId(callingUid);
14545 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14547 throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14550 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14551 throw new SecurityException("Calling uid " + callingUid
14552 + " does not own package " + pkg);
14557 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14558 Intent intent = new Intent(Intent.ACTION_MAIN);
14559 intent.addCategory(Intent.CATEGORY_HOME);
14561 final int callingUserId = UserHandle.getCallingUserId();
14562 List<ResolveInfo> list = queryIntentActivities(intent, null,
14563 PackageManager.GET_META_DATA, callingUserId);
14564 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14565 true, false, false, callingUserId);
14567 allHomeCandidates.clear();
14568 if (list != null) {
14569 for (ResolveInfo ri : list) {
14570 allHomeCandidates.add(ri);
14573 return (preferred == null || preferred.activityInfo == null)
14575 : new ComponentName(preferred.activityInfo.packageName,
14576 preferred.activityInfo.name);
14580 public void setApplicationEnabledSetting(String appPackageName,
14581 int newState, int flags, int userId, String callingPackage) {
14582 if (!sUserManager.exists(userId)) return;
14583 if (callingPackage == null) {
14584 callingPackage = Integer.toString(Binder.getCallingUid());
14586 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14590 public void setComponentEnabledSetting(ComponentName componentName,
14591 int newState, int flags, int userId) {
14592 if (!sUserManager.exists(userId)) return;
14593 setEnabledSetting(componentName.getPackageName(),
14594 componentName.getClassName(), newState, flags, userId, null);
14597 private void setEnabledSetting(final String packageName, String className, int newState,
14598 final int flags, int userId, String callingPackage) {
14599 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14600 || newState == COMPONENT_ENABLED_STATE_ENABLED
14601 || newState == COMPONENT_ENABLED_STATE_DISABLED
14602 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14603 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14604 throw new IllegalArgumentException("Invalid new component state: "
14607 PackageSetting pkgSetting;
14608 final int uid = Binder.getCallingUid();
14609 final int permission = mContext.checkCallingOrSelfPermission(
14610 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14611 enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14612 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14613 boolean sendNow = false;
14614 boolean isApp = (className == null);
14615 String componentName = isApp ? packageName : className;
14616 int packageUid = -1;
14617 ArrayList<String> components;
14620 synchronized (mPackages) {
14621 pkgSetting = mSettings.mPackages.get(packageName);
14622 if (pkgSetting == null) {
14623 if (className == null) {
14624 throw new IllegalArgumentException(
14625 "Unknown package: " + packageName);
14627 throw new IllegalArgumentException(
14628 "Unknown component: " + packageName
14629 + "/" + className);
14631 // Allow root and verify that userId is not being specified by a different user
14632 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14633 throw new SecurityException(
14634 "Permission Denial: attempt to change component state from pid="
14635 + Binder.getCallingPid()
14636 + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14638 if (className == null) {
14639 // We're dealing with an application/package level state change
14640 if (pkgSetting.getEnabled(userId) == newState) {
14644 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14645 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14646 // Don't care about who enables an app.
14647 callingPackage = null;
14649 pkgSetting.setEnabled(newState, userId, callingPackage);
14650 // pkgSetting.pkg.mSetEnabled = newState;
14652 // We're dealing with a component level state change
14653 // First, verify that this is a valid class name.
14654 PackageParser.Package pkg = pkgSetting.pkg;
14655 if (pkg == null || !pkg.hasComponentClassName(className)) {
14656 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14657 throw new IllegalArgumentException("Component class " + className
14658 + " does not exist in " + packageName);
14660 Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14661 + className + " does not exist in " + packageName);
14664 switch (newState) {
14665 case COMPONENT_ENABLED_STATE_ENABLED:
14666 if (!pkgSetting.enableComponentLPw(className, userId)) {
14670 case COMPONENT_ENABLED_STATE_DISABLED:
14671 if (!pkgSetting.disableComponentLPw(className, userId)) {
14675 case COMPONENT_ENABLED_STATE_DEFAULT:
14676 if (!pkgSetting.restoreComponentLPw(className, userId)) {
14681 Slog.e(TAG, "Invalid new component state: " + newState);
14685 scheduleWritePackageRestrictionsLocked(userId);
14686 components = mPendingBroadcasts.get(userId, packageName);
14687 final boolean newPackage = components == null;
14689 components = new ArrayList<String>();
14691 if (!components.contains(componentName)) {
14692 components.add(componentName);
14694 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14696 // Purge entry from pending broadcast list if another one exists already
14697 // since we are sending one right away.
14698 mPendingBroadcasts.remove(userId, packageName);
14701 mPendingBroadcasts.put(userId, packageName, components);
14703 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14704 // Schedule a message
14705 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14710 long callingId = Binder.clearCallingIdentity();
14713 packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14714 sendPackageChangedBroadcast(packageName,
14715 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14718 Binder.restoreCallingIdentity(callingId);
14722 private void sendPackageChangedBroadcast(String packageName,
14723 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14725 Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14727 Bundle extras = new Bundle(4);
14728 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14729 String nameList[] = new String[componentNames.size()];
14730 componentNames.toArray(nameList);
14731 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14732 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14733 extras.putInt(Intent.EXTRA_UID, packageUid);
14734 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null,
14735 new int[] {UserHandle.getUserId(packageUid)});
14739 public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14740 if (!sUserManager.exists(userId)) return;
14741 final int uid = Binder.getCallingUid();
14742 final int permission = mContext.checkCallingOrSelfPermission(
14743 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14744 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14745 enforceCrossUserPermission(uid, userId, true, true, "stop package");
14747 synchronized (mPackages) {
14748 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14749 allowedByPermission, uid, userId)) {
14750 scheduleWritePackageRestrictionsLocked(userId);
14756 public String getInstallerPackageName(String packageName) {
14758 synchronized (mPackages) {
14759 return mSettings.getInstallerPackageNameLPr(packageName);
14764 public int getApplicationEnabledSetting(String packageName, int userId) {
14765 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14766 int uid = Binder.getCallingUid();
14767 enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14769 synchronized (mPackages) {
14770 return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14775 public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14776 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14777 int uid = Binder.getCallingUid();
14778 enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14780 synchronized (mPackages) {
14781 return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14786 public void enterSafeMode() {
14787 enforceSystemOrRoot("Only the system can request entering safe mode");
14789 if (!mSystemReady) {
14795 public void systemReady() {
14796 mSystemReady = true;
14798 // Read the compatibilty setting when the system is ready.
14799 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14800 mContext.getContentResolver(),
14801 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14802 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14803 if (DEBUG_SETTINGS) {
14804 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14807 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14809 synchronized (mPackages) {
14810 // Verify that all of the preferred activity components actually
14811 // exist. It is possible for applications to be updated and at
14812 // that point remove a previously declared activity component that
14813 // had been set as a preferred activity. We try to clean this up
14814 // the next time we encounter that preferred activity, but it is
14815 // possible for the user flow to never be able to return to that
14816 // situation so here we do a sanity check to make sure we haven't
14817 // left any junk around.
14818 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14819 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14820 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14822 for (PreferredActivity pa : pir.filterSet()) {
14823 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14827 if (removed.size() > 0) {
14828 for (int r=0; r<removed.size(); r++) {
14829 PreferredActivity pa = removed.get(r);
14830 Slog.w(TAG, "Removing dangling preferred activity: "
14831 + pa.mPref.mComponent);
14832 pir.removeFilter(pa);
14834 mSettings.writePackageRestrictionsLPr(
14835 mSettings.mPreferredActivities.keyAt(i));
14839 for (int userId : UserManagerService.getInstance().getUserIds()) {
14840 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14841 grantPermissionsUserIds = ArrayUtils.appendInt(
14842 grantPermissionsUserIds, userId);
14846 sUserManager.systemReady();
14848 // If we upgraded grant all default permissions before kicking off.
14849 for (int userId : grantPermissionsUserIds) {
14850 mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14853 // Kick off any messages waiting for system ready
14854 if (mPostSystemReadyMessages != null) {
14855 for (Message msg : mPostSystemReadyMessages) {
14856 msg.sendToTarget();
14858 mPostSystemReadyMessages = null;
14861 // Watch for external volumes that come and go over time
14862 final StorageManager storage = mContext.getSystemService(StorageManager.class);
14863 storage.registerListener(mStorageListener);
14865 mInstallerService.systemReady();
14866 mPackageDexOptimizer.systemReady();
14868 MountServiceInternal mountServiceInternal = LocalServices.getService(
14869 MountServiceInternal.class);
14870 mountServiceInternal.addExternalStoragePolicy(
14871 new MountServiceInternal.ExternalStorageMountPolicy() {
14873 public int getMountMode(int uid, String packageName) {
14874 if (Process.isIsolated(uid)) {
14875 return Zygote.MOUNT_EXTERNAL_NONE;
14877 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14878 return Zygote.MOUNT_EXTERNAL_DEFAULT;
14880 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14881 return Zygote.MOUNT_EXTERNAL_DEFAULT;
14883 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14884 return Zygote.MOUNT_EXTERNAL_READ;
14886 return Zygote.MOUNT_EXTERNAL_WRITE;
14890 public boolean hasExternalStorage(int uid, String packageName) {
14897 public boolean isSafeMode() {
14902 public boolean hasSystemUidErrors() {
14903 return mHasSystemUidErrors;
14906 static String arrayToString(int[] array) {
14907 StringBuffer buf = new StringBuffer(128);
14909 if (array != null) {
14910 for (int i=0; i<array.length; i++) {
14911 if (i > 0) buf.append(", ");
14912 buf.append(array[i]);
14916 return buf.toString();
14919 static class DumpState {
14920 public static final int DUMP_LIBS = 1 << 0;
14921 public static final int DUMP_FEATURES = 1 << 1;
14922 public static final int DUMP_RESOLVERS = 1 << 2;
14923 public static final int DUMP_PERMISSIONS = 1 << 3;
14924 public static final int DUMP_PACKAGES = 1 << 4;
14925 public static final int DUMP_SHARED_USERS = 1 << 5;
14926 public static final int DUMP_MESSAGES = 1 << 6;
14927 public static final int DUMP_PROVIDERS = 1 << 7;
14928 public static final int DUMP_VERIFIERS = 1 << 8;
14929 public static final int DUMP_PREFERRED = 1 << 9;
14930 public static final int DUMP_PREFERRED_XML = 1 << 10;
14931 public static final int DUMP_KEYSETS = 1 << 11;
14932 public static final int DUMP_VERSION = 1 << 12;
14933 public static final int DUMP_INSTALLS = 1 << 13;
14934 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14935 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14937 public static final int OPTION_SHOW_FILTERS = 1 << 0;
14939 private int mTypes;
14941 private int mOptions;
14943 private boolean mTitlePrinted;
14945 private SharedUserSetting mSharedUser;
14947 public boolean isDumping(int type) {
14948 if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14952 return (mTypes & type) != 0;
14955 public void setDump(int type) {
14959 public boolean isOptionEnabled(int option) {
14960 return (mOptions & option) != 0;
14963 public void setOptionEnabled(int option) {
14964 mOptions |= option;
14967 public boolean onTitlePrinted() {
14968 final boolean printed = mTitlePrinted;
14969 mTitlePrinted = true;
14973 public boolean getTitlePrinted() {
14974 return mTitlePrinted;
14977 public void setTitlePrinted(boolean enabled) {
14978 mTitlePrinted = enabled;
14981 public SharedUserSetting getSharedUser() {
14982 return mSharedUser;
14985 public void setSharedUser(SharedUserSetting user) {
14986 mSharedUser = user;
14991 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14992 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14993 != PackageManager.PERMISSION_GRANTED) {
14994 pw.println("Permission Denial: can't dump ActivityManager from from pid="
14995 + Binder.getCallingPid()
14996 + ", uid=" + Binder.getCallingUid()
14997 + " without permission "
14998 + android.Manifest.permission.DUMP);
15002 DumpState dumpState = new DumpState();
15003 boolean fullPreferred = false;
15004 boolean checkin = false;
15006 String packageName = null;
15007 ArraySet<String> permissionNames = null;
15010 while (opti < args.length) {
15011 String opt = args[opti];
15012 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15017 if ("-a".equals(opt)) {
15018 // Right now we only know how to print all.
15019 } else if ("-h".equals(opt)) {
15020 pw.println("Package manager dump options:");
15021 pw.println(" [-h] [-f] [--checkin] [cmd] ...");
15022 pw.println(" --checkin: dump for a checkin");
15023 pw.println(" -f: print details of intent filters");
15024 pw.println(" -h: print this help");
15025 pw.println(" cmd may be one of:");
15026 pw.println(" l[ibraries]: list known shared libraries");
15027 pw.println(" f[ibraries]: list device features");
15028 pw.println(" k[eysets]: print known keysets");
15029 pw.println(" r[esolvers]: dump intent resolvers");
15030 pw.println(" perm[issions]: dump permissions");
15031 pw.println(" permission [name ...]: dump declaration and use of given permission");
15032 pw.println(" pref[erred]: print preferred package settings");
15033 pw.println(" preferred-xml [--full]: print preferred package settings as xml");
15034 pw.println(" prov[iders]: dump content providers");
15035 pw.println(" p[ackages]: dump installed packages");
15036 pw.println(" s[hared-users]: dump shared user IDs");
15037 pw.println(" m[essages]: print collected runtime messages");
15038 pw.println(" v[erifiers]: print package verifier info");
15039 pw.println(" d[omain-preferred-apps]: print domains preferred apps");
15040 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15041 pw.println(" version: print database version info");
15042 pw.println(" write: write current settings now");
15043 pw.println(" installs: details about install sessions");
15044 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?");
15045 pw.println(" <package.name>: info about given package");
15047 } else if ("--checkin".equals(opt)) {
15049 } else if ("-f".equals(opt)) {
15050 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15052 pw.println("Unknown argument: " + opt + "; use -h for help");
15056 // Is the caller requesting to dump a particular piece of data?
15057 if (opti < args.length) {
15058 String cmd = args[opti];
15060 // Is this a package name?
15061 if ("android".equals(cmd) || cmd.contains(".")) {
15063 // When dumping a single package, we always dump all of its
15064 // filter information since the amount of data will be reasonable.
15065 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15066 } else if ("check-permission".equals(cmd)) {
15067 if (opti >= args.length) {
15068 pw.println("Error: check-permission missing permission argument");
15071 String perm = args[opti];
15073 if (opti >= args.length) {
15074 pw.println("Error: check-permission missing package argument");
15077 String pkg = args[opti];
15079 int user = UserHandle.getUserId(Binder.getCallingUid());
15080 if (opti < args.length) {
15082 user = Integer.parseInt(args[opti]);
15083 } catch (NumberFormatException e) {
15084 pw.println("Error: check-permission user argument is not a number: "
15089 pw.println(checkPermission(perm, pkg, user));
15091 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15092 dumpState.setDump(DumpState.DUMP_LIBS);
15093 } else if ("f".equals(cmd) || "features".equals(cmd)) {
15094 dumpState.setDump(DumpState.DUMP_FEATURES);
15095 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15096 dumpState.setDump(DumpState.DUMP_RESOLVERS);
15097 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15098 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15099 } else if ("permission".equals(cmd)) {
15100 if (opti >= args.length) {
15101 pw.println("Error: permission requires permission name");
15104 permissionNames = new ArraySet<>();
15105 while (opti < args.length) {
15106 permissionNames.add(args[opti]);
15109 dumpState.setDump(DumpState.DUMP_PERMISSIONS
15110 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15111 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15112 dumpState.setDump(DumpState.DUMP_PREFERRED);
15113 } else if ("preferred-xml".equals(cmd)) {
15114 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15115 if (opti < args.length && "--full".equals(args[opti])) {
15116 fullPreferred = true;
15119 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15120 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15121 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15122 dumpState.setDump(DumpState.DUMP_PACKAGES);
15123 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15124 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15125 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15126 dumpState.setDump(DumpState.DUMP_PROVIDERS);
15127 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15128 dumpState.setDump(DumpState.DUMP_MESSAGES);
15129 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15130 dumpState.setDump(DumpState.DUMP_VERIFIERS);
15131 } else if ("i".equals(cmd) || "ifv".equals(cmd)
15132 || "intent-filter-verifiers".equals(cmd)) {
15133 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15134 } else if ("version".equals(cmd)) {
15135 dumpState.setDump(DumpState.DUMP_VERSION);
15136 } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15137 dumpState.setDump(DumpState.DUMP_KEYSETS);
15138 } else if ("installs".equals(cmd)) {
15139 dumpState.setDump(DumpState.DUMP_INSTALLS);
15140 } else if ("write".equals(cmd)) {
15141 synchronized (mPackages) {
15142 mSettings.writeLPr();
15143 pw.println("Settings written.");
15150 pw.println("vers,1");
15154 synchronized (mPackages) {
15155 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15157 if (dumpState.onTitlePrinted())
15159 pw.println("Database versions:");
15160 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " "));
15164 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15166 if (dumpState.onTitlePrinted())
15168 pw.println("Verifiers:");
15169 pw.print(" Required: ");
15170 pw.print(mRequiredVerifierPackage);
15171 pw.print(" (uid=");
15172 pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15174 } else if (mRequiredVerifierPackage != null) {
15175 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15176 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15180 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15181 packageName == null) {
15182 if (mIntentFilterVerifierComponent != null) {
15183 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15185 if (dumpState.onTitlePrinted())
15187 pw.println("Intent Filter Verifier:");
15188 pw.print(" Using: ");
15189 pw.print(verifierPackageName);
15190 pw.print(" (uid=");
15191 pw.print(getPackageUid(verifierPackageName, 0));
15193 } else if (verifierPackageName != null) {
15194 pw.print("ifv,"); pw.print(verifierPackageName);
15195 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15199 pw.println("No Intent Filter Verifier available!");
15203 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15204 boolean printedHeader = false;
15205 final Iterator<String> it = mSharedLibraries.keySet().iterator();
15206 while (it.hasNext()) {
15207 String name = it.next();
15208 SharedLibraryEntry ent = mSharedLibraries.get(name);
15210 if (!printedHeader) {
15211 if (dumpState.onTitlePrinted())
15213 pw.println("Libraries:");
15214 printedHeader = true;
15224 if (ent.path != null) {
15226 pw.print("(jar) ");
15227 pw.print(ent.path);
15230 pw.print(ent.path);
15234 pw.print("(apk) ");
15245 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15246 if (dumpState.onTitlePrinted())
15249 pw.println("Features:");
15251 Iterator<String> it = mAvailableFeatures.keySet().iterator();
15252 while (it.hasNext()) {
15253 String name = it.next();
15263 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15264 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15265 : "Activity Resolver Table:", " ", packageName,
15266 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15267 dumpState.setTitlePrinted(true);
15269 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15270 : "Receiver Resolver Table:", " ", packageName,
15271 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15272 dumpState.setTitlePrinted(true);
15274 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15275 : "Service Resolver Table:", " ", packageName,
15276 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15277 dumpState.setTitlePrinted(true);
15279 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15280 : "Provider Resolver Table:", " ", packageName,
15281 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15282 dumpState.setTitlePrinted(true);
15286 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15287 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15288 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15289 int user = mSettings.mPreferredActivities.keyAt(i);
15291 dumpState.getTitlePrinted()
15292 ? "\nPreferred Activities User " + user + ":"
15293 : "Preferred Activities User " + user + ":", " ",
15294 packageName, true, false)) {
15295 dumpState.setTitlePrinted(true);
15300 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15302 FileOutputStream fout = new FileOutputStream(fd);
15303 BufferedOutputStream str = new BufferedOutputStream(fout);
15304 XmlSerializer serializer = new FastXmlSerializer();
15306 serializer.setOutput(str, StandardCharsets.UTF_8.name());
15307 serializer.startDocument(null, true);
15308 serializer.setFeature(
15309 "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15310 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15311 serializer.endDocument();
15312 serializer.flush();
15313 } catch (IllegalArgumentException e) {
15314 pw.println("Failed writing: " + e);
15315 } catch (IllegalStateException e) {
15316 pw.println("Failed writing: " + e);
15317 } catch (IOException e) {
15318 pw.println("Failed writing: " + e);
15323 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15324 && packageName == null) {
15326 int count = mSettings.mPackages.size();
15328 pw.println("No applications!");
15331 final String prefix = " ";
15332 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15333 if (allPackageSettings.size() == 0) {
15334 pw.println("No domain preferred apps!");
15337 pw.println("App verification status:");
15340 for (PackageSetting ps : allPackageSettings) {
15341 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15342 if (ivi == null || ivi.getPackageName() == null) continue;
15343 pw.println(prefix + "Package: " + ivi.getPackageName());
15344 pw.println(prefix + "Domains: " + ivi.getDomainsString());
15345 pw.println(prefix + "Status: " + ivi.getStatusString());
15350 pw.println(prefix + "No app verification established.");
15353 for (int userId : sUserManager.getUserIds()) {
15354 pw.println("App linkages for user " + userId + ":");
15357 for (PackageSetting ps : allPackageSettings) {
15358 final long status = ps.getDomainVerificationStatusForUser(userId);
15359 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15362 pw.println(prefix + "Package: " + ps.name);
15363 pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15364 String statusStr = IntentFilterVerificationInfo.
15365 getStatusStringFromValue(status);
15366 pw.println(prefix + "Status: " + statusStr);
15371 pw.println(prefix + "No configured app linkages.");
15379 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15380 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15381 if (packageName == null && permissionNames == null) {
15382 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15384 if (dumpState.onTitlePrinted())
15386 pw.println("AppOp Permissions:");
15388 pw.print(" AppOp Permission ");
15389 pw.print(mAppOpPermissionPackages.keyAt(iperm));
15391 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15392 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15393 pw.print(" "); pw.println(pkgs.valueAt(ipkg));
15399 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15400 boolean printedSomething = false;
15401 for (PackageParser.Provider p : mProviders.mProviders.values()) {
15402 if (packageName != null && !packageName.equals(p.info.packageName)) {
15405 if (!printedSomething) {
15406 if (dumpState.onTitlePrinted())
15408 pw.println("Registered ContentProviders:");
15409 printedSomething = true;
15411 pw.print(" "); p.printComponentShortName(pw); pw.println(":");
15412 pw.print(" "); pw.println(p.toString());
15414 printedSomething = false;
15415 for (Map.Entry<String, PackageParser.Provider> entry :
15416 mProvidersByAuthority.entrySet()) {
15417 PackageParser.Provider p = entry.getValue();
15418 if (packageName != null && !packageName.equals(p.info.packageName)) {
15421 if (!printedSomething) {
15422 if (dumpState.onTitlePrinted())
15424 pw.println("ContentProvider Authorities:");
15425 printedSomething = true;
15427 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:");
15428 pw.print(" "); pw.println(p.toString());
15429 if (p.info != null && p.info.applicationInfo != null) {
15430 final String appInfo = p.info.applicationInfo.toString();
15431 pw.print(" applicationInfo="); pw.println(appInfo);
15436 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15437 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15440 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15441 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15444 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15445 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15448 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15449 // XXX should handle packageName != null by dumping only install data that
15450 // the given package is involved with.
15451 if (dumpState.onTitlePrinted()) pw.println();
15452 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120));
15455 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15456 if (dumpState.onTitlePrinted()) pw.println();
15457 mSettings.dumpReadMessagesLPr(pw, dumpState);
15460 pw.println("Package warning messages:");
15461 BufferedReader in = null;
15462 String line = null;
15464 in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15465 while ((line = in.readLine()) != null) {
15466 if (line.contains("ignored: updated version")) continue;
15469 } catch (IOException ignored) {
15471 IoUtils.closeQuietly(in);
15475 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15476 BufferedReader in = null;
15477 String line = null;
15479 in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15480 while ((line = in.readLine()) != null) {
15481 if (line.contains("ignored: updated version")) continue;
15485 } catch (IOException ignored) {
15487 IoUtils.closeQuietly(in);
15493 private String dumpDomainString(String packageName) {
15494 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15495 List<IntentFilter> filters = getAllIntentFilters(packageName);
15497 ArraySet<String> result = new ArraySet<>();
15498 if (iviList.size() > 0) {
15499 for (IntentFilterVerificationInfo ivi : iviList) {
15500 for (String host : ivi.getDomains()) {
15505 if (filters != null && filters.size() > 0) {
15506 for (IntentFilter filter : filters) {
15507 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15508 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15509 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15510 result.addAll(filter.getHostsList());
15515 StringBuilder sb = new StringBuilder(result.size() * 16);
15516 for (String domain : result) {
15517 if (sb.length() > 0) sb.append(" ");
15520 return sb.toString();
15523 // ------- apps on sdcard specific code -------
15524 static final boolean DEBUG_SD_INSTALL = false;
15526 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15528 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15530 private boolean mMediaMounted = false;
15532 static String getEncryptKey() {
15534 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15535 SD_ENCRYPTION_KEYSTORE_NAME);
15536 if (sdEncKey == null) {
15537 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15538 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15539 if (sdEncKey == null) {
15540 Slog.e(TAG, "Failed to create encryption keys");
15545 } catch (NoSuchAlgorithmException nsae) {
15546 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15548 } catch (IOException ioe) {
15549 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15555 * Update media status on PackageManager.
15558 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15559 int callingUid = Binder.getCallingUid();
15560 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15561 throw new SecurityException("Media status can only be updated by the system");
15563 // reader; this apparently protects mMediaMounted, but should probably
15564 // be a different lock in that case.
15565 synchronized (mPackages) {
15566 Log.i(TAG, "Updating external media status from "
15567 + (mMediaMounted ? "mounted" : "unmounted") + " to "
15568 + (mediaStatus ? "mounted" : "unmounted"));
15569 if (DEBUG_SD_INSTALL)
15570 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15571 + ", mMediaMounted=" + mMediaMounted);
15572 if (mediaStatus == mMediaMounted) {
15573 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15575 mHandler.sendMessage(msg);
15578 mMediaMounted = mediaStatus;
15580 // Queue up an async operation since the package installation may take a
15582 mHandler.post(new Runnable() {
15583 public void run() {
15584 updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15590 * Called by MountService when the initial ASECs to scan are available.
15591 * Should block until all the ASEC containers are finished being scanned.
15593 public void scanAvailableAsecs() {
15594 updateExternalMediaStatusInner(true, false, false);
15595 if (mShouldRestoreconData) {
15596 SELinuxMMAC.setRestoreconDone();
15597 mShouldRestoreconData = false;
15602 * Collect information of applications on external media, map them against
15603 * existing containers and update information based on current mount status.
15604 * Please note that we always have to report status if reportStatus has been
15605 * set to true especially when unloading packages.
15607 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15608 boolean externalStorage) {
15609 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15610 int[] uidArr = EmptyArray.INT;
15612 final String[] list = PackageHelper.getSecureContainerList();
15613 if (ArrayUtils.isEmpty(list)) {
15614 Log.i(TAG, "No secure containers found");
15616 // Process list of secure containers and categorize them
15617 // as active or stale based on their package internal state.
15620 synchronized (mPackages) {
15621 for (String cid : list) {
15622 // Leave stages untouched for now; installer service owns them
15623 if (PackageInstallerService.isStageName(cid)) continue;
15625 if (DEBUG_SD_INSTALL)
15626 Log.i(TAG, "Processing container " + cid);
15627 String pkgName = getAsecPackageName(cid);
15628 if (pkgName == null) {
15629 Slog.i(TAG, "Found stale container " + cid + " with no package name");
15632 if (DEBUG_SD_INSTALL)
15633 Log.i(TAG, "Looking for pkg : " + pkgName);
15635 final PackageSetting ps = mSettings.mPackages.get(pkgName);
15637 Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15642 * Skip packages that are not external if we're unmounting
15643 * external storage.
15645 if (externalStorage && !isMounted && !isExternal(ps)) {
15649 final AsecInstallArgs args = new AsecInstallArgs(cid,
15650 getAppDexInstructionSets(ps), ps.isForwardLocked());
15651 // The package status is changed only if the code path
15652 // matches between settings and the container id.
15653 if (ps.codePathString != null
15654 && ps.codePathString.startsWith(args.getCodePath())) {
15655 if (DEBUG_SD_INSTALL) {
15656 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15657 + " at code path: " + ps.codePathString);
15660 // We do have a valid package installed on sdcard
15661 processCids.put(args, ps.codePathString);
15662 final int uid = ps.appId;
15664 uidArr = ArrayUtils.appendInt(uidArr, uid);
15667 Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15668 + ps.codePathString);
15673 Arrays.sort(uidArr);
15676 // Process packages with valid entries.
15678 if (DEBUG_SD_INSTALL)
15679 Log.i(TAG, "Loading packages");
15680 loadMediaPackages(processCids, uidArr);
15681 startCleaningPackages();
15682 mInstallerService.onSecureContainersAvailable();
15684 if (DEBUG_SD_INSTALL)
15685 Log.i(TAG, "Unloading packages");
15686 unloadMediaPackages(processCids, uidArr, reportStatus);
15690 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15691 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15692 final int size = infos.size();
15693 final String[] packageNames = new String[size];
15694 final int[] packageUids = new int[size];
15695 for (int i = 0; i < size; i++) {
15696 final ApplicationInfo info = infos.get(i);
15697 packageNames[i] = info.packageName;
15698 packageUids[i] = info.uid;
15700 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15704 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15705 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15706 sendResourcesChangedBroadcast(mediaStatus, replacing,
15707 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15710 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15711 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15712 int size = pkgList.length;
15714 // Send broadcasts here
15715 Bundle extras = new Bundle();
15716 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15717 if (uidArr != null) {
15718 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15721 extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15723 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15724 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15725 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15730 * Look at potentially valid container ids from processCids If package
15731 * information doesn't match the one on record or package scanning fails,
15732 * the cid is added to list of removeCids. We currently don't delete stale
15735 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15736 ArrayList<String> pkgList = new ArrayList<String>();
15737 Set<AsecInstallArgs> keys = processCids.keySet();
15739 for (AsecInstallArgs args : keys) {
15740 String codePath = processCids.get(args);
15741 if (DEBUG_SD_INSTALL)
15742 Log.i(TAG, "Loading container : " + args.cid);
15743 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15745 // Make sure there are no container errors first.
15746 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15747 Slog.e(TAG, "Failed to mount cid : " + args.cid
15748 + " when installing from sdcard");
15751 // Check code path here.
15752 if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15753 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15754 + " does not match one in settings " + codePath);
15758 int parseFlags = mDefParseFlags;
15759 if (args.isExternalAsec()) {
15760 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15762 if (args.isFwdLocked()) {
15763 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15766 synchronized (mInstallLock) {
15767 PackageParser.Package pkg = null;
15769 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15770 } catch (PackageManagerException e) {
15771 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15773 // Scan the package
15776 * TODO why is the lock being held? doPostInstall is
15777 * called in other places without the lock. This needs
15778 * to be straightened out.
15781 synchronized (mPackages) {
15782 retCode = PackageManager.INSTALL_SUCCEEDED;
15783 pkgList.add(pkg.packageName);
15784 // Post process args
15785 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15786 pkg.applicationInfo.uid);
15789 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard");
15794 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15795 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15800 synchronized (mPackages) {
15801 // If the platform SDK has changed since the last time we booted,
15802 // we need to re-grant app permission to catch any new ones that
15803 // appear. This is really a hack, and means that apps can in some
15804 // cases get permissions that the user didn't initially explicitly
15805 // allow... it would be nice to have some better way to handle
15807 final VersionInfo ver = mSettings.getExternalVersion();
15809 int updateFlags = UPDATE_PERMISSIONS_ALL;
15810 if (ver.sdkVersion != mSdkVersion) {
15811 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15812 + mSdkVersion + "; regranting permissions for external");
15813 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15815 updatePermissionsLPw(null, null, updateFlags);
15817 // Yay, everything is now upgraded
15818 ver.forceCurrent();
15820 // can downgrade to reader
15821 // Persist settings
15822 mSettings.writeLPr();
15824 // Send a broadcast to let everyone know we are done processing
15825 if (pkgList.size() > 0) {
15826 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15831 * Utility method to unload a list of specified containers
15833 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15834 // Just unmount all valid containers.
15835 for (AsecInstallArgs arg : cidArgs) {
15836 synchronized (mInstallLock) {
15837 arg.doPostDeleteLI(false);
15843 * Unload packages mounted on external media. This involves deleting package
15844 * data from internal structures, sending broadcasts about diabled packages,
15845 * gc'ing to free up references, unmounting all secure containers
15846 * corresponding to packages on external media, and posting a
15847 * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15848 * that we always have to post this message if status has been requested no
15851 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15852 final boolean reportStatus) {
15853 if (DEBUG_SD_INSTALL)
15854 Log.i(TAG, "unloading media packages");
15855 ArrayList<String> pkgList = new ArrayList<String>();
15856 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15857 final Set<AsecInstallArgs> keys = processCids.keySet();
15858 for (AsecInstallArgs args : keys) {
15859 String pkgName = args.getPackageName();
15860 if (DEBUG_SD_INSTALL)
15861 Log.i(TAG, "Trying to unload pkg : " + pkgName);
15862 // Delete package internally
15863 PackageRemovedInfo outInfo = new PackageRemovedInfo();
15864 synchronized (mInstallLock) {
15865 boolean res = deletePackageLI(pkgName, null, false, null, null,
15866 PackageManager.DELETE_KEEP_DATA, outInfo, false);
15868 pkgList.add(pkgName);
15870 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15871 failedList.add(args);
15877 synchronized (mPackages) {
15878 // We didn't update the settings after removing each package;
15879 // write them now for all packages.
15880 mSettings.writeLPr();
15883 // We have to absolutely send UPDATED_MEDIA_STATUS only
15884 // after confirming that all the receivers processed the ordered
15885 // broadcast when packages get disabled, force a gc to clean things up.
15886 // and unload all the containers.
15887 if (pkgList.size() > 0) {
15888 sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15889 new IIntentReceiver.Stub() {
15890 public void performReceive(Intent intent, int resultCode, String data,
15891 Bundle extras, boolean ordered, boolean sticky,
15892 int sendingUser) throws RemoteException {
15893 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15894 reportStatus ? 1 : 0, 1, keys);
15895 mHandler.sendMessage(msg);
15899 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15901 mHandler.sendMessage(msg);
15905 private void loadPrivatePackages(final VolumeInfo vol) {
15906 mHandler.post(new Runnable() {
15908 public void run() {
15909 loadPrivatePackagesInner(vol);
15914 private void loadPrivatePackagesInner(VolumeInfo vol) {
15915 final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15916 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15918 final VersionInfo ver;
15919 final List<PackageSetting> packages;
15920 synchronized (mPackages) {
15921 ver = mSettings.findOrCreateVersion(vol.fsUuid);
15922 packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15925 for (PackageSetting ps : packages) {
15926 synchronized (mInstallLock) {
15927 final PackageParser.Package pkg;
15929 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15930 loaded.add(pkg.applicationInfo);
15931 } catch (PackageManagerException e) {
15932 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15935 if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15936 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15941 synchronized (mPackages) {
15942 int updateFlags = UPDATE_PERMISSIONS_ALL;
15943 if (ver.sdkVersion != mSdkVersion) {
15944 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15945 + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15946 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15948 updatePermissionsLPw(null, null, updateFlags);
15950 // Yay, everything is now upgraded
15951 ver.forceCurrent();
15953 mSettings.writeLPr();
15956 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15957 sendResourcesChangedBroadcast(true, false, loaded, null);
15960 private void unloadPrivatePackages(final VolumeInfo vol) {
15961 mHandler.post(new Runnable() {
15963 public void run() {
15964 unloadPrivatePackagesInner(vol);
15969 private void unloadPrivatePackagesInner(VolumeInfo vol) {
15970 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15971 synchronized (mInstallLock) {
15972 synchronized (mPackages) {
15973 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15974 for (PackageSetting ps : packages) {
15975 if (ps.pkg == null) continue;
15977 final ApplicationInfo info = ps.pkg.applicationInfo;
15978 final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15979 if (deletePackageLI(ps.name, null, false, null, null,
15980 PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15981 unloaded.add(info);
15983 Slog.w(TAG, "Failed to unload " + ps.codePath);
15987 mSettings.writeLPr();
15991 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15992 sendResourcesChangedBroadcast(false, false, unloaded, null);
15996 * Examine all users present on given mounted volume, and destroy data
15997 * belonging to users that are no longer valid, or whose user ID has been
16000 private void reconcileUsers(String volumeUuid) {
16001 final File[] files = FileUtils
16002 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16003 for (File file : files) {
16004 if (!file.isDirectory()) continue;
16007 final UserInfo info;
16009 userId = Integer.parseInt(file.getName());
16010 info = sUserManager.getUserInfo(userId);
16011 } catch (NumberFormatException e) {
16012 Slog.w(TAG, "Invalid user directory " + file);
16016 boolean destroyUser = false;
16017 if (info == null) {
16018 logCriticalInfo(Log.WARN, "Destroying user directory " + file
16019 + " because no matching user was found");
16020 destroyUser = true;
16023 UserManagerService.enforceSerialNumber(file, info.serialNumber);
16024 } catch (IOException e) {
16025 logCriticalInfo(Log.WARN, "Destroying user directory " + file
16026 + " because we failed to enforce serial number: " + e);
16027 destroyUser = true;
16032 synchronized (mInstallLock) {
16033 mInstaller.removeUserDataDirs(volumeUuid, userId);
16038 final UserManager um = mContext.getSystemService(UserManager.class);
16039 for (UserInfo user : um.getUsers()) {
16040 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16041 if (userDir.exists()) continue;
16044 UserManagerService.prepareUserDirectory(userDir);
16045 UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16046 } catch (IOException e) {
16047 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16053 * Examine all apps present on given mounted volume, and destroy apps that
16054 * aren't expected, either due to uninstallation or reinstallation on
16057 private void reconcileApps(String volumeUuid) {
16058 final File[] files = FileUtils
16059 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16060 for (File file : files) {
16061 final boolean isPackage = (isApkFile(file) || file.isDirectory())
16062 && !PackageInstallerService.isStageName(file.getName());
16064 // Ignore entries which are not packages
16068 boolean destroyApp = false;
16069 String packageName = null;
16071 final PackageLite pkg = PackageParser.parsePackageLite(file,
16072 PackageParser.PARSE_MUST_BE_APK);
16073 packageName = pkg.packageName;
16075 synchronized (mPackages) {
16076 final PackageSetting ps = mSettings.mPackages.get(packageName);
16078 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16079 + volumeUuid + " because we found no install record");
16081 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16082 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16083 + volumeUuid + " because we expected it on " + ps.volumeUuid);
16088 } catch (PackageParserException e) {
16089 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16094 synchronized (mInstallLock) {
16095 if (packageName != null) {
16096 removeDataDirsLI(volumeUuid, packageName);
16098 if (file.isDirectory()) {
16099 mInstaller.rmPackageDir(file.getAbsolutePath());
16108 private void unfreezePackage(String packageName) {
16109 synchronized (mPackages) {
16110 final PackageSetting ps = mSettings.mPackages.get(packageName);
16118 public int movePackage(final String packageName, final String volumeUuid) {
16119 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16121 final int moveId = mNextMoveId.getAndIncrement();
16123 movePackageInternal(packageName, volumeUuid, moveId);
16124 } catch (PackageManagerException e) {
16125 Slog.w(TAG, "Failed to move " + packageName, e);
16126 mMoveCallbacks.notifyStatusChanged(moveId,
16127 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16132 private void movePackageInternal(final String packageName, final String volumeUuid,
16133 final int moveId) throws PackageManagerException {
16134 final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16135 final StorageManager storage = mContext.getSystemService(StorageManager.class);
16136 final PackageManager pm = mContext.getPackageManager();
16138 final boolean currentAsec;
16139 final String currentVolumeUuid;
16140 final File codeFile;
16141 final String installerPackageName;
16142 final String packageAbiOverride;
16144 final String seinfo;
16145 final String label;
16148 synchronized (mPackages) {
16149 final PackageParser.Package pkg = mPackages.get(packageName);
16150 final PackageSetting ps = mSettings.mPackages.get(packageName);
16151 if (pkg == null || ps == null) {
16152 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16155 if (pkg.applicationInfo.isSystemApp()) {
16156 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16157 "Cannot move system application");
16160 if (pkg.applicationInfo.isExternalAsec()) {
16161 currentAsec = true;
16162 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16163 } else if (pkg.applicationInfo.isForwardLocked()) {
16164 currentAsec = true;
16165 currentVolumeUuid = "forward_locked";
16167 currentAsec = false;
16168 currentVolumeUuid = ps.volumeUuid;
16170 final File probe = new File(pkg.codePath);
16171 final File probeOat = new File(probe, "oat");
16172 if (!probe.isDirectory() || !probeOat.isDirectory()) {
16173 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16174 "Move only supported for modern cluster style installs");
16178 if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16179 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16180 "Package already moved to " + volumeUuid);
16184 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16185 "Failed to move already frozen package");
16189 codeFile = new File(pkg.codePath);
16190 installerPackageName = ps.installerPackageName;
16191 packageAbiOverride = ps.cpuAbiOverrideString;
16192 appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16193 seinfo = pkg.applicationInfo.seinfo;
16194 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16197 // Now that we're guarded by frozen state, kill app during move
16198 final long token = Binder.clearCallingIdentity();
16200 killApplication(packageName, appId, "move pkg");
16202 Binder.restoreCallingIdentity(token);
16205 final Bundle extras = new Bundle();
16206 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16207 extras.putString(Intent.EXTRA_TITLE, label);
16208 mMoveCallbacks.notifyCreated(moveId, extras);
16211 final boolean moveCompleteApp;
16212 final File measurePath;
16214 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16215 installFlags = INSTALL_INTERNAL;
16216 moveCompleteApp = !currentAsec;
16217 measurePath = Environment.getDataAppDirectory(volumeUuid);
16218 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16219 installFlags = INSTALL_EXTERNAL;
16220 moveCompleteApp = false;
16221 measurePath = storage.getPrimaryPhysicalVolume().getPath();
16223 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16224 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16225 || !volume.isMountedWritable()) {
16226 unfreezePackage(packageName);
16227 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16228 "Move location not mounted private volume");
16231 Preconditions.checkState(!currentAsec);
16233 installFlags = INSTALL_INTERNAL;
16234 moveCompleteApp = true;
16235 measurePath = Environment.getDataAppDirectory(volumeUuid);
16238 final PackageStats stats = new PackageStats(null, -1);
16239 synchronized (mInstaller) {
16240 if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16241 unfreezePackage(packageName);
16242 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16243 "Failed to measure package size");
16247 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16250 final long startFreeBytes = measurePath.getFreeSpace();
16251 final long sizeBytes;
16252 if (moveCompleteApp) {
16253 sizeBytes = stats.codeSize + stats.dataSize;
16255 sizeBytes = stats.codeSize;
16258 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16259 unfreezePackage(packageName);
16260 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16261 "Not enough free space to move");
16264 mMoveCallbacks.notifyStatusChanged(moveId, 10);
16266 final CountDownLatch installedLatch = new CountDownLatch(1);
16267 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16269 public void onUserActionRequired(Intent intent) throws RemoteException {
16270 throw new IllegalStateException();
16274 public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16275 Bundle extras) throws RemoteException {
16276 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16277 + PackageManager.installStatusToString(returnCode, msg));
16279 installedLatch.countDown();
16281 // Regardless of success or failure of the move operation,
16282 // always unfreeze the package
16283 unfreezePackage(packageName);
16285 final int status = PackageManager.installStatusToPublicStatus(returnCode);
16287 case PackageInstaller.STATUS_SUCCESS:
16288 mMoveCallbacks.notifyStatusChanged(moveId,
16289 PackageManager.MOVE_SUCCEEDED);
16291 case PackageInstaller.STATUS_FAILURE_STORAGE:
16292 mMoveCallbacks.notifyStatusChanged(moveId,
16293 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16296 mMoveCallbacks.notifyStatusChanged(moveId,
16297 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16303 final MoveInfo move;
16304 if (moveCompleteApp) {
16305 // Kick off a thread to report progress estimates
16308 public void run() {
16311 if (installedLatch.await(1, TimeUnit.SECONDS)) {
16314 } catch (InterruptedException ignored) {
16317 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16318 final int progress = 10 + (int) MathUtils.constrain(
16319 ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16320 mMoveCallbacks.notifyStatusChanged(moveId, progress);
16325 final String dataAppName = codeFile.getName();
16326 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16327 dataAppName, appId, seinfo);
16332 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16334 final Message msg = mHandler.obtainMessage(INIT_COPY);
16335 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16336 msg.obj = new InstallParams(origin, move, installObserver, installFlags,
16337 installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16338 mHandler.sendMessage(msg);
16342 public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16343 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16345 final int realMoveId = mNextMoveId.getAndIncrement();
16346 final Bundle extras = new Bundle();
16347 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16348 mMoveCallbacks.notifyCreated(realMoveId, extras);
16350 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16352 public void onCreated(int moveId, Bundle extras) {
16357 public void onStatusChanged(int moveId, int status, long estMillis) {
16358 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16362 final StorageManager storage = mContext.getSystemService(StorageManager.class);
16363 storage.setPrimaryStorageUuid(volumeUuid, callback);
16368 public int getMoveStatus(int moveId) {
16369 mContext.enforceCallingOrSelfPermission(
16370 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16371 return mMoveCallbacks.mLastStatus.get(moveId);
16375 public void registerMoveCallback(IPackageMoveObserver callback) {
16376 mContext.enforceCallingOrSelfPermission(
16377 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16378 mMoveCallbacks.register(callback);
16382 public void unregisterMoveCallback(IPackageMoveObserver callback) {
16383 mContext.enforceCallingOrSelfPermission(
16384 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16385 mMoveCallbacks.unregister(callback);
16389 public boolean setInstallLocation(int loc) {
16390 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16392 if (getInstallLocation() == loc) {
16395 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16396 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16397 android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16398 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16405 public int getInstallLocation() {
16406 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16407 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16408 PackageHelper.APP_INSTALL_AUTO);
16411 /** Called by UserManagerService */
16412 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16413 mDirtyUsers.remove(userHandle);
16414 mSettings.removeUserLPw(userHandle);
16415 mPendingBroadcasts.remove(userHandle);
16416 if (mInstaller != null) {
16417 // Technically, we shouldn't be doing this with the package lock
16418 // held. However, this is very rare, and there is already so much
16419 // other disk I/O going on, that we'll let it slide for now.
16420 final StorageManager storage = mContext.getSystemService(StorageManager.class);
16421 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16422 final String volumeUuid = vol.getFsUuid();
16423 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16424 mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16427 mUserNeedsBadging.delete(userHandle);
16428 removeUnusedPackagesLILPw(userManager, userHandle);
16432 * We're removing userHandle and would like to remove any downloaded packages
16433 * that are no longer in use by any other user.
16434 * @param userHandle the user being removed
16436 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16437 final boolean DEBUG_CLEAN_APKS = false;
16438 int [] users = userManager.getUserIdsLPr();
16439 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16440 while (psit.hasNext()) {
16441 PackageSetting ps = psit.next();
16442 if (ps.pkg == null) {
16445 final String packageName = ps.pkg.packageName;
16446 // Skip over if system app
16447 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16450 if (DEBUG_CLEAN_APKS) {
16451 Slog.i(TAG, "Checking package " + packageName);
16453 boolean keep = false;
16454 for (int i = 0; i < users.length; i++) {
16455 if (users[i] != userHandle && ps.getInstalled(users[i])) {
16457 if (DEBUG_CLEAN_APKS) {
16458 Slog.i(TAG, " Keeping package " + packageName + " for user "
16465 if (DEBUG_CLEAN_APKS) {
16466 Slog.i(TAG, " Removing package " + packageName);
16468 mHandler.post(new Runnable() {
16469 public void run() {
16470 deletePackageX(packageName, userHandle, 0);
16477 /** Called by UserManagerService */
16478 void createNewUserLILPw(int userHandle) {
16479 if (mInstaller != null) {
16480 mInstaller.createUserConfig(userHandle);
16481 mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16482 applyFactoryDefaultBrowserLPw(userHandle);
16483 primeDomainVerificationsLPw(userHandle);
16487 void newUserCreated(final int userHandle) {
16488 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16492 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16493 mContext.enforceCallingOrSelfPermission(
16494 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16495 "Only package verification agents can read the verifier device identity");
16497 synchronized (mPackages) {
16498 return mSettings.getVerifierDeviceIdentityLPw();
16503 public void setPermissionEnforced(String permission, boolean enforced) {
16504 // TODO: Now that we no longer change GID for storage, this should to away.
16505 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16506 "setPermissionEnforced");
16507 if (READ_EXTERNAL_STORAGE.equals(permission)) {
16508 synchronized (mPackages) {
16509 if (mSettings.mReadExternalStorageEnforced == null
16510 || mSettings.mReadExternalStorageEnforced != enforced) {
16511 mSettings.mReadExternalStorageEnforced = enforced;
16512 mSettings.writeLPr();
16515 // kill any non-foreground processes so we restart them and
16516 // grant/revoke the GID.
16517 final IActivityManager am = ActivityManagerNative.getDefault();
16519 final long token = Binder.clearCallingIdentity();
16521 am.killProcessesBelowForeground("setPermissionEnforcement");
16522 } catch (RemoteException e) {
16524 Binder.restoreCallingIdentity(token);
16528 throw new IllegalArgumentException("No selective enforcement for " + permission);
16534 public boolean isPermissionEnforced(String permission) {
16539 public boolean isStorageLow() {
16540 final long token = Binder.clearCallingIdentity();
16542 final DeviceStorageMonitorInternal
16543 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16545 return dsm.isMemoryLow();
16550 Binder.restoreCallingIdentity(token);
16555 public IPackageInstaller getPackageInstaller() {
16556 return mInstallerService;
16559 private boolean userNeedsBadging(int userId) {
16560 int index = mUserNeedsBadging.indexOfKey(userId);
16562 final UserInfo userInfo;
16563 final long token = Binder.clearCallingIdentity();
16565 userInfo = sUserManager.getUserInfo(userId);
16567 Binder.restoreCallingIdentity(token);
16570 if (userInfo != null && userInfo.isManagedProfile()) {
16575 mUserNeedsBadging.put(userId, b);
16578 return mUserNeedsBadging.valueAt(index);
16582 public KeySet getKeySetByAlias(String packageName, String alias) {
16583 if (packageName == null || alias == null) {
16586 synchronized(mPackages) {
16587 final PackageParser.Package pkg = mPackages.get(packageName);
16589 Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16590 throw new IllegalArgumentException("Unknown package: " + packageName);
16592 KeySetManagerService ksms = mSettings.mKeySetManagerService;
16593 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16598 public KeySet getSigningKeySet(String packageName) {
16599 if (packageName == null) {
16602 synchronized(mPackages) {
16603 final PackageParser.Package pkg = mPackages.get(packageName);
16605 Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16606 throw new IllegalArgumentException("Unknown package: " + packageName);
16608 if (pkg.applicationInfo.uid != Binder.getCallingUid()
16609 && Process.SYSTEM_UID != Binder.getCallingUid()) {
16610 throw new SecurityException("May not access signing KeySet of other apps.");
16612 KeySetManagerService ksms = mSettings.mKeySetManagerService;
16613 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16618 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16619 if (packageName == null || ks == null) {
16622 synchronized(mPackages) {
16623 final PackageParser.Package pkg = mPackages.get(packageName);
16625 Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16626 throw new IllegalArgumentException("Unknown package: " + packageName);
16628 IBinder ksh = ks.getToken();
16629 if (ksh instanceof KeySetHandle) {
16630 KeySetManagerService ksms = mSettings.mKeySetManagerService;
16631 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16638 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16639 if (packageName == null || ks == null) {
16642 synchronized(mPackages) {
16643 final PackageParser.Package pkg = mPackages.get(packageName);
16645 Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16646 throw new IllegalArgumentException("Unknown package: " + packageName);
16648 IBinder ksh = ks.getToken();
16649 if (ksh instanceof KeySetHandle) {
16650 KeySetManagerService ksms = mSettings.mKeySetManagerService;
16651 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16657 public void getUsageStatsIfNoPackageUsageInfo() {
16658 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16659 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16661 throw new IllegalStateException("UsageStatsManager must be initialized");
16663 long now = System.currentTimeMillis();
16664 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16665 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16666 String packageName = entry.getKey();
16667 PackageParser.Package pkg = mPackages.get(packageName);
16671 UsageStats usage = entry.getValue();
16672 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16673 mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16679 * Check and throw if the given before/after packages would be considered a
16682 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16683 throws PackageManagerException {
16684 if (after.versionCode < before.mVersionCode) {
16685 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16686 "Update version code " + after.versionCode + " is older than current "
16687 + before.mVersionCode);
16688 } else if (after.versionCode == before.mVersionCode) {
16689 if (after.baseRevisionCode < before.baseRevisionCode) {
16690 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16691 "Update base revision code " + after.baseRevisionCode
16692 + " is older than current " + before.baseRevisionCode);
16695 if (!ArrayUtils.isEmpty(after.splitNames)) {
16696 for (int i = 0; i < after.splitNames.length; i++) {
16697 final String splitName = after.splitNames[i];
16698 final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16700 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16701 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16702 "Update split " + splitName + " revision code "
16703 + after.splitRevisionCodes[i] + " is older than current "
16704 + before.splitRevisionCodes[j]);
16712 private static class MoveCallbacks extends Handler {
16713 private static final int MSG_CREATED = 1;
16714 private static final int MSG_STATUS_CHANGED = 2;
16716 private final RemoteCallbackList<IPackageMoveObserver>
16717 mCallbacks = new RemoteCallbackList<>();
16719 private final SparseIntArray mLastStatus = new SparseIntArray();
16721 public MoveCallbacks(Looper looper) {
16725 public void register(IPackageMoveObserver callback) {
16726 mCallbacks.register(callback);
16729 public void unregister(IPackageMoveObserver callback) {
16730 mCallbacks.unregister(callback);
16734 public void handleMessage(Message msg) {
16735 final SomeArgs args = (SomeArgs) msg.obj;
16736 final int n = mCallbacks.beginBroadcast();
16737 for (int i = 0; i < n; i++) {
16738 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16740 invokeCallback(callback, msg.what, args);
16741 } catch (RemoteException ignored) {
16744 mCallbacks.finishBroadcast();
16748 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16749 throws RemoteException {
16751 case MSG_CREATED: {
16752 callback.onCreated(args.argi1, (Bundle) args.arg2);
16755 case MSG_STATUS_CHANGED: {
16756 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16762 private void notifyCreated(int moveId, Bundle extras) {
16763 Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16765 final SomeArgs args = SomeArgs.obtain();
16766 args.argi1 = moveId;
16767 args.arg2 = extras;
16768 obtainMessage(MSG_CREATED, args).sendToTarget();
16771 private void notifyStatusChanged(int moveId, int status) {
16772 notifyStatusChanged(moveId, status, -1);
16775 private void notifyStatusChanged(int moveId, int status, long estMillis) {
16776 Slog.v(TAG, "Move " + moveId + " status " + status);
16778 final SomeArgs args = SomeArgs.obtain();
16779 args.argi1 = moveId;
16780 args.argi2 = status;
16781 args.arg3 = estMillis;
16782 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16784 synchronized (mLastStatus) {
16785 mLastStatus.put(moveId, status);
16790 private final class OnPermissionChangeListeners extends Handler {
16791 private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16793 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16794 new RemoteCallbackList<>();
16796 public OnPermissionChangeListeners(Looper looper) {
16801 public void handleMessage(Message msg) {
16802 switch (msg.what) {
16803 case MSG_ON_PERMISSIONS_CHANGED: {
16804 final int uid = msg.arg1;
16805 handleOnPermissionsChanged(uid);
16810 public void addListenerLocked(IOnPermissionsChangeListener listener) {
16811 mPermissionListeners.register(listener);
16815 public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16816 mPermissionListeners.unregister(listener);
16819 public void onPermissionsChanged(int uid) {
16820 if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16821 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16825 private void handleOnPermissionsChanged(int uid) {
16826 final int count = mPermissionListeners.beginBroadcast();
16828 for (int i = 0; i < count; i++) {
16829 IOnPermissionsChangeListener callback = mPermissionListeners
16830 .getBroadcastItem(i);
16832 callback.onPermissionsChanged(uid);
16833 } catch (RemoteException e) {
16834 Log.e(TAG, "Permission listener is dead", e);
16838 mPermissionListeners.finishBroadcast();
16843 private class PackageManagerInternalImpl extends PackageManagerInternal {
16845 public void setLocationPackagesProvider(PackagesProvider provider) {
16846 synchronized (mPackages) {
16847 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16852 public void setImePackagesProvider(PackagesProvider provider) {
16853 synchronized (mPackages) {
16854 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16859 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16860 synchronized (mPackages) {
16861 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16866 public void setSmsAppPackagesProvider(PackagesProvider provider) {
16867 synchronized (mPackages) {
16868 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16873 public void setDialerAppPackagesProvider(PackagesProvider provider) {
16874 synchronized (mPackages) {
16875 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16880 public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16881 synchronized (mPackages) {
16882 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16887 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16888 synchronized (mPackages) {
16889 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16894 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16895 synchronized (mPackages) {
16896 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16897 packageName, userId);
16902 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16903 synchronized (mPackages) {
16904 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16905 packageName, userId);
16909 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16910 synchronized (mPackages) {
16911 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16912 packageName, userId);
16918 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16919 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16920 synchronized (mPackages) {
16921 final long identity = Binder.clearCallingIdentity();
16923 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16924 packageNames, userId);
16926 Binder.restoreCallingIdentity(identity);
16931 private static void enforceSystemOrPhoneCaller(String tag) {
16932 int callingUid = Binder.getCallingUid();
16933 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16934 throw new SecurityException(
16935 "Cannot call " + tag + " from UID " + callingUid);