PackageManagerService.java revision c8a465c4d3827970f61555e604c43ef3b3f6d4d6
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 33import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 53import static android.content.pm.PackageManager.INSTALL_INTERNAL; 54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 59import static android.content.pm.PackageManager.MATCH_ALL; 60import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 61import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 62import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 63import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 64import static android.content.pm.PackageManager.PERMISSION_DENIED; 65import static android.content.pm.PackageManager.PERMISSION_GRANTED; 66import static android.content.pm.PackageParser.isApkFile; 67import static android.os.Process.PACKAGE_INFO_GID; 68import static android.os.Process.SYSTEM_UID; 69import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 70import static android.system.OsConstants.O_CREAT; 71import static android.system.OsConstants.O_RDWR; 72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 74import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 75import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 76import static com.android.internal.util.ArrayUtils.appendInt; 77import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 80import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 81import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 85 86import android.Manifest; 87import android.app.ActivityManager; 88import android.app.ActivityManagerNative; 89import android.app.AppGlobals; 90import android.app.IActivityManager; 91import android.app.admin.IDevicePolicyManager; 92import android.app.backup.IBackupManager; 93import android.app.usage.UsageStats; 94import android.app.usage.UsageStatsManager; 95import android.content.BroadcastReceiver; 96import android.content.ComponentName; 97import android.content.Context; 98import android.content.IIntentReceiver; 99import android.content.Intent; 100import android.content.IntentFilter; 101import android.content.IntentSender; 102import android.content.IntentSender.SendIntentException; 103import android.content.ServiceConnection; 104import android.content.pm.ActivityInfo; 105import android.content.pm.ApplicationInfo; 106import android.content.pm.FeatureInfo; 107import android.content.pm.IOnPermissionsChangeListener; 108import android.content.pm.IPackageDataObserver; 109import android.content.pm.IPackageDeleteObserver; 110import android.content.pm.IPackageDeleteObserver2; 111import android.content.pm.IPackageInstallObserver2; 112import android.content.pm.IPackageInstaller; 113import android.content.pm.IPackageManager; 114import android.content.pm.IPackageMoveObserver; 115import android.content.pm.IPackageStatsObserver; 116import android.content.pm.InstrumentationInfo; 117import android.content.pm.IntentFilterVerificationInfo; 118import android.content.pm.KeySet; 119import android.content.pm.ManifestDigest; 120import android.content.pm.PackageCleanItem; 121import android.content.pm.PackageInfo; 122import android.content.pm.PackageInfoLite; 123import android.content.pm.PackageInstaller; 124import android.content.pm.PackageManager; 125import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 126import android.content.pm.PackageManagerInternal; 127import android.content.pm.PackageParser; 128import android.content.pm.PackageParser.ActivityIntentInfo; 129import android.content.pm.PackageParser.PackageLite; 130import android.content.pm.PackageParser.PackageParserException; 131import android.content.pm.PackageStats; 132import android.content.pm.PackageUserState; 133import android.content.pm.ParceledListSlice; 134import android.content.pm.PermissionGroupInfo; 135import android.content.pm.PermissionInfo; 136import android.content.pm.ProviderInfo; 137import android.content.pm.ResolveInfo; 138import android.content.pm.ServiceInfo; 139import android.content.pm.Signature; 140import android.content.pm.UserInfo; 141import android.content.pm.VerificationParams; 142import android.content.pm.VerifierDeviceIdentity; 143import android.content.pm.VerifierInfo; 144import android.content.res.Resources; 145import android.hardware.display.DisplayManager; 146import android.net.Uri; 147import android.os.Debug; 148import android.os.Binder; 149import android.os.Build; 150import android.os.Bundle; 151import android.os.Environment; 152import android.os.Environment.UserEnvironment; 153import android.os.FileUtils; 154import android.os.Handler; 155import android.os.IBinder; 156import android.os.Looper; 157import android.os.Message; 158import android.os.Parcel; 159import android.os.ParcelFileDescriptor; 160import android.os.Process; 161import android.os.RemoteCallbackList; 162import android.os.RemoteException; 163import android.os.SELinux; 164import android.os.ServiceManager; 165import android.os.SystemClock; 166import android.os.SystemProperties; 167import android.os.Trace; 168import android.os.UserHandle; 169import android.os.UserManager; 170import android.os.storage.IMountService; 171import android.os.storage.MountServiceInternal; 172import android.os.storage.StorageEventListener; 173import android.os.storage.StorageManager; 174import android.os.storage.VolumeInfo; 175import android.os.storage.VolumeRecord; 176import android.security.KeyStore; 177import android.security.SystemKeyStore; 178import android.system.ErrnoException; 179import android.system.Os; 180import android.system.StructStat; 181import android.text.TextUtils; 182import android.text.format.DateUtils; 183import android.util.ArrayMap; 184import android.util.ArraySet; 185import android.util.AtomicFile; 186import android.util.DisplayMetrics; 187import android.util.EventLog; 188import android.util.ExceptionUtils; 189import android.util.Log; 190import android.util.LogPrinter; 191import android.util.MathUtils; 192import android.util.PrintStreamPrinter; 193import android.util.Slog; 194import android.util.SparseArray; 195import android.util.SparseBooleanArray; 196import android.util.SparseIntArray; 197import android.util.Xml; 198import android.view.Display; 199 200import dalvik.system.DexFile; 201import dalvik.system.VMRuntime; 202 203import libcore.io.IoUtils; 204import libcore.util.EmptyArray; 205 206import com.android.internal.R; 207import com.android.internal.annotations.GuardedBy; 208import com.android.internal.app.IMediaContainerService; 209import com.android.internal.app.ResolverActivity; 210import com.android.internal.content.NativeLibraryHelper; 211import com.android.internal.content.PackageHelper; 212import com.android.internal.os.IParcelFileDescriptorFactory; 213import com.android.internal.os.SomeArgs; 214import com.android.internal.os.Zygote; 215import com.android.internal.util.ArrayUtils; 216import com.android.internal.util.FastPrintWriter; 217import com.android.internal.util.FastXmlSerializer; 218import com.android.internal.util.IndentingPrintWriter; 219import com.android.internal.util.Preconditions; 220import com.android.server.EventLogTags; 221import com.android.server.FgThread; 222import com.android.server.IntentResolver; 223import com.android.server.LocalServices; 224import com.android.server.ServiceThread; 225import com.android.server.SystemConfig; 226import com.android.server.Watchdog; 227import com.android.server.pm.PermissionsState.PermissionState; 228import com.android.server.pm.Settings.DatabaseVersion; 229import com.android.server.pm.Settings.VersionInfo; 230import com.android.server.storage.DeviceStorageMonitorInternal; 231 232import org.xmlpull.v1.XmlPullParser; 233import org.xmlpull.v1.XmlPullParserException; 234import org.xmlpull.v1.XmlSerializer; 235 236import java.io.BufferedInputStream; 237import java.io.BufferedOutputStream; 238import java.io.BufferedReader; 239import java.io.ByteArrayInputStream; 240import java.io.ByteArrayOutputStream; 241import java.io.File; 242import java.io.FileDescriptor; 243import java.io.FileNotFoundException; 244import java.io.FileOutputStream; 245import java.io.FileReader; 246import java.io.FilenameFilter; 247import java.io.IOException; 248import java.io.InputStream; 249import java.io.PrintWriter; 250import java.nio.charset.StandardCharsets; 251import java.security.NoSuchAlgorithmException; 252import java.security.PublicKey; 253import java.security.cert.CertificateEncodingException; 254import java.security.cert.CertificateException; 255import java.text.SimpleDateFormat; 256import java.util.ArrayList; 257import java.util.Arrays; 258import java.util.Collection; 259import java.util.Collections; 260import java.util.Comparator; 261import java.util.Date; 262import java.util.Iterator; 263import java.util.List; 264import java.util.Map; 265import java.util.Objects; 266import java.util.Set; 267import java.util.concurrent.CountDownLatch; 268import java.util.concurrent.TimeUnit; 269import java.util.concurrent.atomic.AtomicBoolean; 270import java.util.concurrent.atomic.AtomicInteger; 271import java.util.concurrent.atomic.AtomicLong; 272 273/** 274 * Keep track of all those .apks everywhere. 275 * 276 * This is very central to the platform's security; please run the unit 277 * tests whenever making modifications here: 278 * 279runtest -c android.content.pm.PackageManagerTests frameworks-core 280 * 281 * {@hide} 282 */ 283public class PackageManagerService extends IPackageManager.Stub { 284 static final String TAG = "PackageManager"; 285 static final boolean DEBUG_SETTINGS = false; 286 static final boolean DEBUG_PREFERRED = false; 287 static final boolean DEBUG_UPGRADE = false; 288 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 289 private static final boolean DEBUG_BACKUP = false; 290 private static final boolean DEBUG_INSTALL = false; 291 private static final boolean DEBUG_REMOVE = false; 292 private static final boolean DEBUG_BROADCASTS = false; 293 private static final boolean DEBUG_SHOW_INFO = false; 294 private static final boolean DEBUG_PACKAGE_INFO = false; 295 private static final boolean DEBUG_INTENT_MATCHING = false; 296 private static final boolean DEBUG_PACKAGE_SCANNING = false; 297 private static final boolean DEBUG_VERIFY = false; 298 private static final boolean DEBUG_DEXOPT = false; 299 private static final boolean DEBUG_ABI_SELECTION = false; 300 301 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 302 303 private static final int RADIO_UID = Process.PHONE_UID; 304 private static final int LOG_UID = Process.LOG_UID; 305 private static final int NFC_UID = Process.NFC_UID; 306 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 307 private static final int SHELL_UID = Process.SHELL_UID; 308 309 // Cap the size of permission trees that 3rd party apps can define 310 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 311 312 // Suffix used during package installation when copying/moving 313 // package apks to install directory. 314 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 315 316 static final int SCAN_NO_DEX = 1<<1; 317 static final int SCAN_FORCE_DEX = 1<<2; 318 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 319 static final int SCAN_NEW_INSTALL = 1<<4; 320 static final int SCAN_NO_PATHS = 1<<5; 321 static final int SCAN_UPDATE_TIME = 1<<6; 322 static final int SCAN_DEFER_DEX = 1<<7; 323 static final int SCAN_BOOTING = 1<<8; 324 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 325 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 326 static final int SCAN_REPLACING = 1<<11; 327 static final int SCAN_REQUIRE_KNOWN = 1<<12; 328 static final int SCAN_MOVE = 1<<13; 329 static final int SCAN_INITIAL = 1<<14; 330 331 static final int REMOVE_CHATTY = 1<<16; 332 333 private static final int[] EMPTY_INT_ARRAY = new int[0]; 334 335 /** 336 * Timeout (in milliseconds) after which the watchdog should declare that 337 * our handler thread is wedged. The usual default for such things is one 338 * minute but we sometimes do very lengthy I/O operations on this thread, 339 * such as installing multi-gigabyte applications, so ours needs to be longer. 340 */ 341 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 342 343 /** 344 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 345 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 346 * settings entry if available, otherwise we use the hardcoded default. If it's been 347 * more than this long since the last fstrim, we force one during the boot sequence. 348 * 349 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 350 * one gets run at the next available charging+idle time. This final mandatory 351 * no-fstrim check kicks in only of the other scheduling criteria is never met. 352 */ 353 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 354 355 /** 356 * Whether verification is enabled by default. 357 */ 358 private static final boolean DEFAULT_VERIFY_ENABLE = true; 359 360 /** 361 * The default maximum time to wait for the verification agent to return in 362 * milliseconds. 363 */ 364 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 365 366 /** 367 * The default response for package verification timeout. 368 * 369 * This can be either PackageManager.VERIFICATION_ALLOW or 370 * PackageManager.VERIFICATION_REJECT. 371 */ 372 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 373 374 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 375 376 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 377 DEFAULT_CONTAINER_PACKAGE, 378 "com.android.defcontainer.DefaultContainerService"); 379 380 private static final String KILL_APP_REASON_GIDS_CHANGED = 381 "permission grant or revoke changed gids"; 382 383 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 384 "permissions revoked"; 385 386 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 387 388 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 389 390 /** Permission grant: not grant the permission. */ 391 private static final int GRANT_DENIED = 1; 392 393 /** Permission grant: grant the permission as an install permission. */ 394 private static final int GRANT_INSTALL = 2; 395 396 /** Permission grant: grant the permission as an install permission for a legacy app. */ 397 private static final int GRANT_INSTALL_LEGACY = 3; 398 399 /** Permission grant: grant the permission as a runtime one. */ 400 private static final int GRANT_RUNTIME = 4; 401 402 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 403 private static final int GRANT_UPGRADE = 5; 404 405 /** Canonical intent used to identify what counts as a "web browser" app */ 406 private static final Intent sBrowserIntent; 407 static { 408 sBrowserIntent = new Intent(); 409 sBrowserIntent.setAction(Intent.ACTION_VIEW); 410 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 411 sBrowserIntent.setData(Uri.parse("http:")); 412 } 413 414 final ServiceThread mHandlerThread; 415 416 final PackageHandler mHandler; 417 418 /** 419 * Messages for {@link #mHandler} that need to wait for system ready before 420 * being dispatched. 421 */ 422 private ArrayList<Message> mPostSystemReadyMessages; 423 424 final int mSdkVersion = Build.VERSION.SDK_INT; 425 426 final Context mContext; 427 final boolean mFactoryTest; 428 final boolean mOnlyCore; 429 final boolean mLazyDexOpt; 430 final long mDexOptLRUThresholdInMills; 431 final DisplayMetrics mMetrics; 432 final int mDefParseFlags; 433 final String[] mSeparateProcesses; 434 final boolean mIsUpgrade; 435 436 // This is where all application persistent data goes. 437 final File mAppDataDir; 438 439 // This is where all application persistent data goes for secondary users. 440 final File mUserAppDataDir; 441 442 /** The location for ASEC container files on internal storage. */ 443 final String mAsecInternalPath; 444 445 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 446 // LOCK HELD. Can be called with mInstallLock held. 447 @GuardedBy("mInstallLock") 448 final Installer mInstaller; 449 450 /** Directory where installed third-party apps stored */ 451 final File mAppInstallDir; 452 453 /** 454 * Directory to which applications installed internally have their 455 * 32 bit native libraries copied. 456 */ 457 private File mAppLib32InstallDir; 458 459 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 460 // apps. 461 final File mDrmAppPrivateInstallDir; 462 463 // ---------------------------------------------------------------- 464 465 // Lock for state used when installing and doing other long running 466 // operations. Methods that must be called with this lock held have 467 // the suffix "LI". 468 final Object mInstallLock = new Object(); 469 470 // ---------------------------------------------------------------- 471 472 // Keys are String (package name), values are Package. This also serves 473 // as the lock for the global state. Methods that must be called with 474 // this lock held have the prefix "LP". 475 @GuardedBy("mPackages") 476 final ArrayMap<String, PackageParser.Package> mPackages = 477 new ArrayMap<String, PackageParser.Package>(); 478 479 // Tracks available target package names -> overlay package paths. 480 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 481 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 482 483 /** 484 * Tracks new system packages [receiving in an OTA] that we expect to 485 * find updated user-installed versions. Keys are package name, values 486 * are package location. 487 */ 488 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 489 490 final Settings mSettings; 491 boolean mRestoredSettings; 492 493 // System configuration read by SystemConfig. 494 final int[] mGlobalGids; 495 final SparseArray<ArraySet<String>> mSystemPermissions; 496 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 497 498 // If mac_permissions.xml was found for seinfo labeling. 499 boolean mFoundPolicyFile; 500 501 // If a recursive restorecon of /data/data/<pkg> is needed. 502 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 503 504 public static final class SharedLibraryEntry { 505 public final String path; 506 public final String apk; 507 508 SharedLibraryEntry(String _path, String _apk) { 509 path = _path; 510 apk = _apk; 511 } 512 } 513 514 // Currently known shared libraries. 515 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 516 new ArrayMap<String, SharedLibraryEntry>(); 517 518 // All available activities, for your resolving pleasure. 519 final ActivityIntentResolver mActivities = 520 new ActivityIntentResolver(); 521 522 // All available receivers, for your resolving pleasure. 523 final ActivityIntentResolver mReceivers = 524 new ActivityIntentResolver(); 525 526 // All available services, for your resolving pleasure. 527 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 528 529 // All available providers, for your resolving pleasure. 530 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 531 532 // Mapping from provider base names (first directory in content URI codePath) 533 // to the provider information. 534 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 535 new ArrayMap<String, PackageParser.Provider>(); 536 537 // Mapping from instrumentation class names to info about them. 538 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 539 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 540 541 // Mapping from permission names to info about them. 542 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 543 new ArrayMap<String, PackageParser.PermissionGroup>(); 544 545 // Packages whose data we have transfered into another package, thus 546 // should no longer exist. 547 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 548 549 // Broadcast actions that are only available to the system. 550 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 551 552 /** List of packages waiting for verification. */ 553 final SparseArray<PackageVerificationState> mPendingVerification 554 = new SparseArray<PackageVerificationState>(); 555 556 /** Set of packages associated with each app op permission. */ 557 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 558 559 final PackageInstallerService mInstallerService; 560 561 private final PackageDexOptimizer mPackageDexOptimizer; 562 563 private AtomicInteger mNextMoveId = new AtomicInteger(); 564 private final MoveCallbacks mMoveCallbacks; 565 566 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 567 568 // Cache of users who need badging. 569 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 570 571 /** Token for keys in mPendingVerification. */ 572 private int mPendingVerificationToken = 0; 573 574 volatile boolean mSystemReady; 575 volatile boolean mSafeMode; 576 volatile boolean mHasSystemUidErrors; 577 578 ApplicationInfo mAndroidApplication; 579 final ActivityInfo mResolveActivity = new ActivityInfo(); 580 final ResolveInfo mResolveInfo = new ResolveInfo(); 581 ComponentName mResolveComponentName; 582 PackageParser.Package mPlatformPackage; 583 ComponentName mCustomResolverComponentName; 584 585 boolean mResolverReplaced = false; 586 587 private final ComponentName mIntentFilterVerifierComponent; 588 private int mIntentFilterVerificationToken = 0; 589 590 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 591 = new SparseArray<IntentFilterVerificationState>(); 592 593 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 594 new DefaultPermissionGrantPolicy(this); 595 596 private static class IFVerificationParams { 597 PackageParser.Package pkg; 598 boolean replacing; 599 int userId; 600 int verifierUid; 601 602 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 603 int _userId, int _verifierUid) { 604 pkg = _pkg; 605 replacing = _replacing; 606 userId = _userId; 607 replacing = _replacing; 608 verifierUid = _verifierUid; 609 } 610 } 611 612 private interface IntentFilterVerifier<T extends IntentFilter> { 613 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 614 T filter, String packageName); 615 void startVerifications(int userId); 616 void receiveVerificationResponse(int verificationId); 617 } 618 619 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 620 private Context mContext; 621 private ComponentName mIntentFilterVerifierComponent; 622 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 623 624 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 625 mContext = context; 626 mIntentFilterVerifierComponent = verifierComponent; 627 } 628 629 private String getDefaultScheme() { 630 return IntentFilter.SCHEME_HTTPS; 631 } 632 633 @Override 634 public void startVerifications(int userId) { 635 // Launch verifications requests 636 int count = mCurrentIntentFilterVerifications.size(); 637 for (int n=0; n<count; n++) { 638 int verificationId = mCurrentIntentFilterVerifications.get(n); 639 final IntentFilterVerificationState ivs = 640 mIntentFilterVerificationStates.get(verificationId); 641 642 String packageName = ivs.getPackageName(); 643 644 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 645 final int filterCount = filters.size(); 646 ArraySet<String> domainsSet = new ArraySet<>(); 647 for (int m=0; m<filterCount; m++) { 648 PackageParser.ActivityIntentInfo filter = filters.get(m); 649 domainsSet.addAll(filter.getHostsList()); 650 } 651 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 652 synchronized (mPackages) { 653 if (mSettings.createIntentFilterVerificationIfNeededLPw( 654 packageName, domainsList) != null) { 655 scheduleWriteSettingsLocked(); 656 } 657 } 658 sendVerificationRequest(userId, verificationId, ivs); 659 } 660 mCurrentIntentFilterVerifications.clear(); 661 } 662 663 private void sendVerificationRequest(int userId, int verificationId, 664 IntentFilterVerificationState ivs) { 665 666 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 667 verificationIntent.putExtra( 668 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 669 verificationId); 670 verificationIntent.putExtra( 671 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 672 getDefaultScheme()); 673 verificationIntent.putExtra( 674 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 675 ivs.getHostsString()); 676 verificationIntent.putExtra( 677 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 678 ivs.getPackageName()); 679 verificationIntent.setComponent(mIntentFilterVerifierComponent); 680 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 681 682 UserHandle user = new UserHandle(userId); 683 mContext.sendBroadcastAsUser(verificationIntent, user); 684 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 685 "Sending IntentFilter verification broadcast"); 686 } 687 688 public void receiveVerificationResponse(int verificationId) { 689 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 690 691 final boolean verified = ivs.isVerified(); 692 693 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 694 final int count = filters.size(); 695 if (DEBUG_DOMAIN_VERIFICATION) { 696 Slog.i(TAG, "Received verification response " + verificationId 697 + " for " + count + " filters, verified=" + verified); 698 } 699 for (int n=0; n<count; n++) { 700 PackageParser.ActivityIntentInfo filter = filters.get(n); 701 filter.setVerified(verified); 702 703 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 704 + " verified with result:" + verified + " and hosts:" 705 + ivs.getHostsString()); 706 } 707 708 mIntentFilterVerificationStates.remove(verificationId); 709 710 final String packageName = ivs.getPackageName(); 711 IntentFilterVerificationInfo ivi = null; 712 713 synchronized (mPackages) { 714 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 715 } 716 if (ivi == null) { 717 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 718 + verificationId + " packageName:" + packageName); 719 return; 720 } 721 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 722 "Updating IntentFilterVerificationInfo for package " + packageName 723 +" verificationId:" + verificationId); 724 725 synchronized (mPackages) { 726 if (verified) { 727 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 728 } else { 729 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 730 } 731 scheduleWriteSettingsLocked(); 732 733 final int userId = ivs.getUserId(); 734 if (userId != UserHandle.USER_ALL) { 735 final int userStatus = 736 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 737 738 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 739 boolean needUpdate = false; 740 741 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 742 // already been set by the User thru the Disambiguation dialog 743 switch (userStatus) { 744 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 745 if (verified) { 746 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 747 } else { 748 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 749 } 750 needUpdate = true; 751 break; 752 753 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 754 if (verified) { 755 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 756 needUpdate = true; 757 } 758 break; 759 760 default: 761 // Nothing to do 762 } 763 764 if (needUpdate) { 765 mSettings.updateIntentFilterVerificationStatusLPw( 766 packageName, updatedStatus, userId); 767 scheduleWritePackageRestrictionsLocked(userId); 768 } 769 } 770 } 771 } 772 773 @Override 774 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 775 ActivityIntentInfo filter, String packageName) { 776 if (!hasValidDomains(filter)) { 777 return false; 778 } 779 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 780 if (ivs == null) { 781 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 782 packageName); 783 } 784 if (DEBUG_DOMAIN_VERIFICATION) { 785 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 786 } 787 ivs.addFilter(filter); 788 return true; 789 } 790 791 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 792 int userId, int verificationId, String packageName) { 793 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 794 verifierUid, userId, packageName); 795 ivs.setPendingState(); 796 synchronized (mPackages) { 797 mIntentFilterVerificationStates.append(verificationId, ivs); 798 mCurrentIntentFilterVerifications.add(verificationId); 799 } 800 return ivs; 801 } 802 } 803 804 private static boolean hasValidDomains(ActivityIntentInfo filter) { 805 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 806 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 807 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 808 } 809 810 private IntentFilterVerifier mIntentFilterVerifier; 811 812 // Set of pending broadcasts for aggregating enable/disable of components. 813 static class PendingPackageBroadcasts { 814 // for each user id, a map of <package name -> components within that package> 815 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 816 817 public PendingPackageBroadcasts() { 818 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 819 } 820 821 public ArrayList<String> get(int userId, String packageName) { 822 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 823 return packages.get(packageName); 824 } 825 826 public void put(int userId, String packageName, ArrayList<String> components) { 827 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 828 packages.put(packageName, components); 829 } 830 831 public void remove(int userId, String packageName) { 832 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 833 if (packages != null) { 834 packages.remove(packageName); 835 } 836 } 837 838 public void remove(int userId) { 839 mUidMap.remove(userId); 840 } 841 842 public int userIdCount() { 843 return mUidMap.size(); 844 } 845 846 public int userIdAt(int n) { 847 return mUidMap.keyAt(n); 848 } 849 850 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 851 return mUidMap.get(userId); 852 } 853 854 public int size() { 855 // total number of pending broadcast entries across all userIds 856 int num = 0; 857 for (int i = 0; i< mUidMap.size(); i++) { 858 num += mUidMap.valueAt(i).size(); 859 } 860 return num; 861 } 862 863 public void clear() { 864 mUidMap.clear(); 865 } 866 867 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 868 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 869 if (map == null) { 870 map = new ArrayMap<String, ArrayList<String>>(); 871 mUidMap.put(userId, map); 872 } 873 return map; 874 } 875 } 876 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 877 878 // Service Connection to remote media container service to copy 879 // package uri's from external media onto secure containers 880 // or internal storage. 881 private IMediaContainerService mContainerService = null; 882 883 static final int SEND_PENDING_BROADCAST = 1; 884 static final int MCS_BOUND = 3; 885 static final int END_COPY = 4; 886 static final int INIT_COPY = 5; 887 static final int MCS_UNBIND = 6; 888 static final int START_CLEANING_PACKAGE = 7; 889 static final int FIND_INSTALL_LOC = 8; 890 static final int POST_INSTALL = 9; 891 static final int MCS_RECONNECT = 10; 892 static final int MCS_GIVE_UP = 11; 893 static final int UPDATED_MEDIA_STATUS = 12; 894 static final int WRITE_SETTINGS = 13; 895 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 896 static final int PACKAGE_VERIFIED = 15; 897 static final int CHECK_PENDING_VERIFICATION = 16; 898 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 899 static final int INTENT_FILTER_VERIFIED = 18; 900 901 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 902 903 // Delay time in millisecs 904 static final int BROADCAST_DELAY = 10 * 1000; 905 906 static UserManagerService sUserManager; 907 908 // Stores a list of users whose package restrictions file needs to be updated 909 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 910 911 final private DefaultContainerConnection mDefContainerConn = 912 new DefaultContainerConnection(); 913 class DefaultContainerConnection implements ServiceConnection { 914 public void onServiceConnected(ComponentName name, IBinder service) { 915 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 916 IMediaContainerService imcs = 917 IMediaContainerService.Stub.asInterface(service); 918 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 919 } 920 921 public void onServiceDisconnected(ComponentName name) { 922 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 923 } 924 } 925 926 // Recordkeeping of restore-after-install operations that are currently in flight 927 // between the Package Manager and the Backup Manager 928 class PostInstallData { 929 public InstallArgs args; 930 public PackageInstalledInfo res; 931 932 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 933 args = _a; 934 res = _r; 935 } 936 } 937 938 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 939 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 940 941 // XML tags for backup/restore of various bits of state 942 private static final String TAG_PREFERRED_BACKUP = "pa"; 943 private static final String TAG_DEFAULT_APPS = "da"; 944 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 945 946 final String mRequiredVerifierPackage; 947 final String mRequiredInstallerPackage; 948 949 private final PackageUsage mPackageUsage = new PackageUsage(); 950 951 private class PackageUsage { 952 private static final int WRITE_INTERVAL 953 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 954 955 private final Object mFileLock = new Object(); 956 private final AtomicLong mLastWritten = new AtomicLong(0); 957 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 958 959 private boolean mIsHistoricalPackageUsageAvailable = true; 960 961 boolean isHistoricalPackageUsageAvailable() { 962 return mIsHistoricalPackageUsageAvailable; 963 } 964 965 void write(boolean force) { 966 if (force) { 967 writeInternal(); 968 return; 969 } 970 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 971 && !DEBUG_DEXOPT) { 972 return; 973 } 974 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 975 new Thread("PackageUsage_DiskWriter") { 976 @Override 977 public void run() { 978 try { 979 writeInternal(); 980 } finally { 981 mBackgroundWriteRunning.set(false); 982 } 983 } 984 }.start(); 985 } 986 } 987 988 private void writeInternal() { 989 synchronized (mPackages) { 990 synchronized (mFileLock) { 991 AtomicFile file = getFile(); 992 FileOutputStream f = null; 993 try { 994 f = file.startWrite(); 995 BufferedOutputStream out = new BufferedOutputStream(f); 996 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 997 StringBuilder sb = new StringBuilder(); 998 for (PackageParser.Package pkg : mPackages.values()) { 999 if (pkg.mLastPackageUsageTimeInMills == 0) { 1000 continue; 1001 } 1002 sb.setLength(0); 1003 sb.append(pkg.packageName); 1004 sb.append(' '); 1005 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1006 sb.append('\n'); 1007 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1008 } 1009 out.flush(); 1010 file.finishWrite(f); 1011 } catch (IOException e) { 1012 if (f != null) { 1013 file.failWrite(f); 1014 } 1015 Log.e(TAG, "Failed to write package usage times", e); 1016 } 1017 } 1018 } 1019 mLastWritten.set(SystemClock.elapsedRealtime()); 1020 } 1021 1022 void readLP() { 1023 synchronized (mFileLock) { 1024 AtomicFile file = getFile(); 1025 BufferedInputStream in = null; 1026 try { 1027 in = new BufferedInputStream(file.openRead()); 1028 StringBuffer sb = new StringBuffer(); 1029 while (true) { 1030 String packageName = readToken(in, sb, ' '); 1031 if (packageName == null) { 1032 break; 1033 } 1034 String timeInMillisString = readToken(in, sb, '\n'); 1035 if (timeInMillisString == null) { 1036 throw new IOException("Failed to find last usage time for package " 1037 + packageName); 1038 } 1039 PackageParser.Package pkg = mPackages.get(packageName); 1040 if (pkg == null) { 1041 continue; 1042 } 1043 long timeInMillis; 1044 try { 1045 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1046 } catch (NumberFormatException e) { 1047 throw new IOException("Failed to parse " + timeInMillisString 1048 + " as a long.", e); 1049 } 1050 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1051 } 1052 } catch (FileNotFoundException expected) { 1053 mIsHistoricalPackageUsageAvailable = false; 1054 } catch (IOException e) { 1055 Log.w(TAG, "Failed to read package usage times", e); 1056 } finally { 1057 IoUtils.closeQuietly(in); 1058 } 1059 } 1060 mLastWritten.set(SystemClock.elapsedRealtime()); 1061 } 1062 1063 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1064 throws IOException { 1065 sb.setLength(0); 1066 while (true) { 1067 int ch = in.read(); 1068 if (ch == -1) { 1069 if (sb.length() == 0) { 1070 return null; 1071 } 1072 throw new IOException("Unexpected EOF"); 1073 } 1074 if (ch == endOfToken) { 1075 return sb.toString(); 1076 } 1077 sb.append((char)ch); 1078 } 1079 } 1080 1081 private AtomicFile getFile() { 1082 File dataDir = Environment.getDataDirectory(); 1083 File systemDir = new File(dataDir, "system"); 1084 File fname = new File(systemDir, "package-usage.list"); 1085 return new AtomicFile(fname); 1086 } 1087 } 1088 1089 class PackageHandler extends Handler { 1090 private boolean mBound = false; 1091 final ArrayList<HandlerParams> mPendingInstalls = 1092 new ArrayList<HandlerParams>(); 1093 1094 private boolean connectToService() { 1095 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1096 " DefaultContainerService"); 1097 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1098 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1099 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1100 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1101 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1102 mBound = true; 1103 return true; 1104 } 1105 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1106 return false; 1107 } 1108 1109 private void disconnectService() { 1110 mContainerService = null; 1111 mBound = false; 1112 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1113 mContext.unbindService(mDefContainerConn); 1114 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1115 } 1116 1117 PackageHandler(Looper looper) { 1118 super(looper); 1119 } 1120 1121 public void handleMessage(Message msg) { 1122 try { 1123 doHandleMessage(msg); 1124 } finally { 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1126 } 1127 } 1128 1129 void doHandleMessage(Message msg) { 1130 switch (msg.what) { 1131 case INIT_COPY: { 1132 HandlerParams params = (HandlerParams) msg.obj; 1133 int idx = mPendingInstalls.size(); 1134 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1135 // If a bind was already initiated we dont really 1136 // need to do anything. The pending install 1137 // will be processed later on. 1138 if (!mBound) { 1139 try { 1140 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindMCS", 1141 System.identityHashCode(params)); 1142 // If this is the only one pending we might 1143 // have to bind to the service again. 1144 if (!connectToService()) { 1145 Slog.e(TAG, "Failed to bind to media container service"); 1146 params.serviceError(); 1147 return; 1148 } else { 1149 // Once we bind to the service, the first 1150 // pending request will be processed. 1151 mPendingInstalls.add(idx, params); 1152 } 1153 } finally { 1154 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindMCS", 1155 System.identityHashCode(params)); 1156 } 1157 } else { 1158 mPendingInstalls.add(idx, params); 1159 // Already bound to the service. Just make 1160 // sure we trigger off processing the first request. 1161 if (idx == 0) { 1162 mHandler.sendEmptyMessage(MCS_BOUND); 1163 } 1164 } 1165 break; 1166 } 1167 case MCS_BOUND: { 1168 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1169 if (msg.obj != null) { 1170 mContainerService = (IMediaContainerService) msg.obj; 1171 } 1172 if (mContainerService == null) { 1173 if (!mBound) { 1174 // Something seriously wrong since we are not bound and we are not 1175 // waiting for connection. Bail out. 1176 Slog.e(TAG, "Cannot bind to media container service"); 1177 for (HandlerParams params : mPendingInstalls) { 1178 // Indicate service bind error 1179 params.serviceError(); 1180 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1181 System.identityHashCode(params)); 1182 } 1183 mPendingInstalls.clear(); 1184 } else { 1185 Slog.w(TAG, "Waiting to connect to media container service"); 1186 } 1187 } else if (mPendingInstalls.size() > 0) { 1188 HandlerParams params = mPendingInstalls.get(0); 1189 if (params != null) { 1190 if (params.startCopy()) { 1191 // We are done... look for more work or to 1192 // go idle. 1193 if (DEBUG_SD_INSTALL) Log.i(TAG, 1194 "Checking for more work or unbind..."); 1195 // Delete pending install 1196 if (mPendingInstalls.size() > 0) { 1197 mPendingInstalls.remove(0); 1198 } 1199 if (mPendingInstalls.size() == 0) { 1200 if (mBound) { 1201 if (DEBUG_SD_INSTALL) Log.i(TAG, 1202 "Posting delayed MCS_UNBIND"); 1203 removeMessages(MCS_UNBIND); 1204 Message ubmsg = obtainMessage(MCS_UNBIND); 1205 // Unbind after a little delay, to avoid 1206 // continual thrashing. 1207 sendMessageDelayed(ubmsg, 10000); 1208 } 1209 } else { 1210 // There are more pending requests in queue. 1211 // Just post MCS_BOUND message to trigger processing 1212 // of next pending install. 1213 if (DEBUG_SD_INSTALL) Log.i(TAG, 1214 "Posting MCS_BOUND for next work"); 1215 mHandler.sendEmptyMessage(MCS_BOUND); 1216 } 1217 } 1218 } 1219 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1220 System.identityHashCode(params)); 1221 } else { 1222 // Should never happen ideally. 1223 Slog.w(TAG, "Empty queue"); 1224 } 1225 break; 1226 } 1227 case MCS_RECONNECT: { 1228 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1229 if (mPendingInstalls.size() > 0) { 1230 if (mBound) { 1231 disconnectService(); 1232 } 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(); 1238 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1239 System.identityHashCode(params)); 1240 } 1241 mPendingInstalls.clear(); 1242 } 1243 } 1244 break; 1245 } 1246 case MCS_UNBIND: { 1247 // If there is no actual work left, then time to unbind. 1248 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1249 1250 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1251 if (mBound) { 1252 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1253 1254 disconnectService(); 1255 } 1256 } else if (mPendingInstalls.size() > 0) { 1257 // There are more pending requests in queue. 1258 // Just post MCS_BOUND message to trigger processing 1259 // of next pending install. 1260 mHandler.sendEmptyMessage(MCS_BOUND); 1261 } 1262 1263 break; 1264 } 1265 case MCS_GIVE_UP: { 1266 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1267 HandlerParams params = mPendingInstalls.remove(0); 1268 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1269 System.identityHashCode(params)); 1270 break; 1271 } 1272 case SEND_PENDING_BROADCAST: { 1273 String packages[]; 1274 ArrayList<String> components[]; 1275 int size = 0; 1276 int uids[]; 1277 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1278 synchronized (mPackages) { 1279 if (mPendingBroadcasts == null) { 1280 return; 1281 } 1282 size = mPendingBroadcasts.size(); 1283 if (size <= 0) { 1284 // Nothing to be done. Just return 1285 return; 1286 } 1287 packages = new String[size]; 1288 components = new ArrayList[size]; 1289 uids = new int[size]; 1290 int i = 0; // filling out the above arrays 1291 1292 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1293 int packageUserId = mPendingBroadcasts.userIdAt(n); 1294 Iterator<Map.Entry<String, ArrayList<String>>> it 1295 = mPendingBroadcasts.packagesForUserId(packageUserId) 1296 .entrySet().iterator(); 1297 while (it.hasNext() && i < size) { 1298 Map.Entry<String, ArrayList<String>> ent = it.next(); 1299 packages[i] = ent.getKey(); 1300 components[i] = ent.getValue(); 1301 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1302 uids[i] = (ps != null) 1303 ? UserHandle.getUid(packageUserId, ps.appId) 1304 : -1; 1305 i++; 1306 } 1307 } 1308 size = i; 1309 mPendingBroadcasts.clear(); 1310 } 1311 // Send broadcasts 1312 for (int i = 0; i < size; i++) { 1313 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1314 } 1315 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1316 break; 1317 } 1318 case START_CLEANING_PACKAGE: { 1319 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1320 final String packageName = (String)msg.obj; 1321 final int userId = msg.arg1; 1322 final boolean andCode = msg.arg2 != 0; 1323 synchronized (mPackages) { 1324 if (userId == UserHandle.USER_ALL) { 1325 int[] users = sUserManager.getUserIds(); 1326 for (int user : users) { 1327 mSettings.addPackageToCleanLPw( 1328 new PackageCleanItem(user, packageName, andCode)); 1329 } 1330 } else { 1331 mSettings.addPackageToCleanLPw( 1332 new PackageCleanItem(userId, packageName, andCode)); 1333 } 1334 } 1335 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1336 startCleaningPackages(); 1337 } break; 1338 case POST_INSTALL: { 1339 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1340 PostInstallData data = mRunningInstalls.get(msg.arg1); 1341 mRunningInstalls.delete(msg.arg1); 1342 boolean deleteOld = false; 1343 1344 if (data != null) { 1345 InstallArgs args = data.args; 1346 PackageInstalledInfo res = data.res; 1347 1348 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1349 final String packageName = res.pkg.applicationInfo.packageName; 1350 res.removedInfo.sendBroadcast(false, true, false); 1351 Bundle extras = new Bundle(1); 1352 extras.putInt(Intent.EXTRA_UID, res.uid); 1353 1354 // Now that we successfully installed the package, grant runtime 1355 // permissions if requested before broadcasting the install. 1356 if ((args.installFlags 1357 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1358 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1359 args.installGrantPermissions); 1360 } 1361 1362 // Determine the set of users who are adding this 1363 // package for the first time vs. those who are seeing 1364 // an update. 1365 int[] firstUsers; 1366 int[] updateUsers = new int[0]; 1367 if (res.origUsers == null || res.origUsers.length == 0) { 1368 firstUsers = res.newUsers; 1369 } else { 1370 firstUsers = new int[0]; 1371 for (int i=0; i<res.newUsers.length; i++) { 1372 int user = res.newUsers[i]; 1373 boolean isNew = true; 1374 for (int j=0; j<res.origUsers.length; j++) { 1375 if (res.origUsers[j] == user) { 1376 isNew = false; 1377 break; 1378 } 1379 } 1380 if (isNew) { 1381 int[] newFirst = new int[firstUsers.length+1]; 1382 System.arraycopy(firstUsers, 0, newFirst, 0, 1383 firstUsers.length); 1384 newFirst[firstUsers.length] = user; 1385 firstUsers = newFirst; 1386 } else { 1387 int[] newUpdate = new int[updateUsers.length+1]; 1388 System.arraycopy(updateUsers, 0, newUpdate, 0, 1389 updateUsers.length); 1390 newUpdate[updateUsers.length] = user; 1391 updateUsers = newUpdate; 1392 } 1393 } 1394 } 1395 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1396 packageName, extras, null, null, firstUsers); 1397 final boolean update = res.removedInfo.removedPackage != null; 1398 if (update) { 1399 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1400 } 1401 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1402 packageName, extras, null, null, updateUsers); 1403 if (update) { 1404 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1405 packageName, extras, null, null, updateUsers); 1406 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1407 null, null, packageName, null, updateUsers); 1408 1409 // treat asec-hosted packages like removable media on upgrade 1410 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1411 if (DEBUG_INSTALL) { 1412 Slog.i(TAG, "upgrading pkg " + res.pkg 1413 + " is ASEC-hosted -> AVAILABLE"); 1414 } 1415 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1416 ArrayList<String> pkgList = new ArrayList<String>(1); 1417 pkgList.add(packageName); 1418 sendResourcesChangedBroadcast(true, true, 1419 pkgList,uidArray, null); 1420 } 1421 } 1422 if (res.removedInfo.args != null) { 1423 // Remove the replaced package's older resources safely now 1424 deleteOld = true; 1425 } 1426 1427 // If this app is a browser and it's newly-installed for some 1428 // users, clear any default-browser state in those users 1429 if (firstUsers.length > 0) { 1430 // the app's nature doesn't depend on the user, so we can just 1431 // check its browser nature in any user and generalize. 1432 if (packageIsBrowser(packageName, firstUsers[0])) { 1433 synchronized (mPackages) { 1434 for (int userId : firstUsers) { 1435 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1436 } 1437 } 1438 } 1439 } 1440 // Log current value of "unknown sources" setting 1441 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1442 getUnknownSourcesSettings()); 1443 } 1444 // Force a gc to clear up things 1445 Runtime.getRuntime().gc(); 1446 // We delete after a gc for applications on sdcard. 1447 if (deleteOld) { 1448 synchronized (mInstallLock) { 1449 res.removedInfo.args.doPostDeleteLI(true); 1450 } 1451 } 1452 if (args.observer != null) { 1453 try { 1454 Bundle extras = extrasForInstallResult(res); 1455 args.observer.onPackageInstalled(res.name, res.returnCode, 1456 res.returnMsg, extras); 1457 } catch (RemoteException e) { 1458 Slog.i(TAG, "Observer no longer exists."); 1459 } 1460 } 1461 } else { 1462 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1463 } 1464 1465 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1466 } break; 1467 case UPDATED_MEDIA_STATUS: { 1468 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1469 boolean reportStatus = msg.arg1 == 1; 1470 boolean doGc = msg.arg2 == 1; 1471 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1472 if (doGc) { 1473 // Force a gc to clear up stale containers. 1474 Runtime.getRuntime().gc(); 1475 } 1476 if (msg.obj != null) { 1477 @SuppressWarnings("unchecked") 1478 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1479 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1480 // Unload containers 1481 unloadAllContainers(args); 1482 } 1483 if (reportStatus) { 1484 try { 1485 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1486 PackageHelper.getMountService().finishMediaUpdate(); 1487 } catch (RemoteException e) { 1488 Log.e(TAG, "MountService not running?"); 1489 } 1490 } 1491 } break; 1492 case WRITE_SETTINGS: { 1493 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1494 synchronized (mPackages) { 1495 removeMessages(WRITE_SETTINGS); 1496 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1497 mSettings.writeLPr(); 1498 mDirtyUsers.clear(); 1499 } 1500 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1501 } break; 1502 case WRITE_PACKAGE_RESTRICTIONS: { 1503 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1504 synchronized (mPackages) { 1505 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1506 for (int userId : mDirtyUsers) { 1507 mSettings.writePackageRestrictionsLPr(userId); 1508 } 1509 mDirtyUsers.clear(); 1510 } 1511 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1512 } break; 1513 case CHECK_PENDING_VERIFICATION: { 1514 final int verificationId = msg.arg1; 1515 final PackageVerificationState state = mPendingVerification.get(verificationId); 1516 1517 if ((state != null) && !state.timeoutExtended()) { 1518 final InstallArgs args = state.getInstallArgs(); 1519 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1520 1521 Slog.i(TAG, "Verification timed out for " + originUri); 1522 mPendingVerification.remove(verificationId); 1523 1524 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1525 1526 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1527 Slog.i(TAG, "Continuing with installation of " + originUri); 1528 state.setVerifierResponse(Binder.getCallingUid(), 1529 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1530 broadcastPackageVerified(verificationId, originUri, 1531 PackageManager.VERIFICATION_ALLOW, 1532 state.getInstallArgs().getUser()); 1533 try { 1534 ret = args.copyApk(mContainerService, true); 1535 } catch (RemoteException e) { 1536 Slog.e(TAG, "Could not contact the ContainerService"); 1537 } 1538 } else { 1539 broadcastPackageVerified(verificationId, originUri, 1540 PackageManager.VERIFICATION_REJECT, 1541 state.getInstallArgs().getUser()); 1542 } 1543 1544 processPendingInstall(args, ret); 1545 mHandler.sendEmptyMessage(MCS_UNBIND); 1546 } 1547 Trace.asyncTraceEnd( 1548 TRACE_TAG_PACKAGE_MANAGER, "pendingVerification", verificationId); 1549 break; 1550 } 1551 case PACKAGE_VERIFIED: { 1552 final int verificationId = msg.arg1; 1553 1554 final PackageVerificationState state = mPendingVerification.get(verificationId); 1555 if (state == null) { 1556 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1557 break; 1558 } 1559 1560 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1561 1562 state.setVerifierResponse(response.callerUid, response.code); 1563 1564 if (state.isVerificationComplete()) { 1565 mPendingVerification.remove(verificationId); 1566 1567 final InstallArgs args = state.getInstallArgs(); 1568 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1569 1570 int ret; 1571 if (state.isInstallAllowed()) { 1572 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1573 broadcastPackageVerified(verificationId, originUri, 1574 response.code, state.getInstallArgs().getUser()); 1575 try { 1576 ret = args.copyApk(mContainerService, true); 1577 } catch (RemoteException e) { 1578 Slog.e(TAG, "Could not contact the ContainerService"); 1579 } 1580 } else { 1581 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1582 } 1583 1584 processPendingInstall(args, ret); 1585 1586 mHandler.sendEmptyMessage(MCS_UNBIND); 1587 } 1588 1589 break; 1590 } 1591 case START_INTENT_FILTER_VERIFICATIONS: { 1592 IFVerificationParams params = (IFVerificationParams) msg.obj; 1593 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1594 params.replacing, params.pkg); 1595 break; 1596 } 1597 case INTENT_FILTER_VERIFIED: { 1598 final int verificationId = msg.arg1; 1599 1600 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1601 verificationId); 1602 if (state == null) { 1603 Slog.w(TAG, "Invalid IntentFilter verification token " 1604 + verificationId + " received"); 1605 break; 1606 } 1607 1608 final int userId = state.getUserId(); 1609 1610 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1611 "Processing IntentFilter verification with token:" 1612 + verificationId + " and userId:" + userId); 1613 1614 final IntentFilterVerificationResponse response = 1615 (IntentFilterVerificationResponse) msg.obj; 1616 1617 state.setVerifierResponse(response.callerUid, response.code); 1618 1619 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1620 "IntentFilter verification with token:" + verificationId 1621 + " and userId:" + userId 1622 + " is settings verifier response with response code:" 1623 + response.code); 1624 1625 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1626 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1627 + response.getFailedDomainsString()); 1628 } 1629 1630 if (state.isVerificationComplete()) { 1631 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1632 } else { 1633 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1634 "IntentFilter verification with token:" + verificationId 1635 + " was not said to be complete"); 1636 } 1637 1638 break; 1639 } 1640 } 1641 } 1642 } 1643 1644 private StorageEventListener mStorageListener = new StorageEventListener() { 1645 @Override 1646 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1647 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1648 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1649 final String volumeUuid = vol.getFsUuid(); 1650 1651 // Clean up any users or apps that were removed or recreated 1652 // while this volume was missing 1653 reconcileUsers(volumeUuid); 1654 reconcileApps(volumeUuid); 1655 1656 // Clean up any install sessions that expired or were 1657 // cancelled while this volume was missing 1658 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1659 1660 loadPrivatePackages(vol); 1661 1662 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1663 unloadPrivatePackages(vol); 1664 } 1665 } 1666 1667 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1668 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1669 updateExternalMediaStatus(true, false); 1670 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1671 updateExternalMediaStatus(false, false); 1672 } 1673 } 1674 } 1675 1676 @Override 1677 public void onVolumeForgotten(String fsUuid) { 1678 if (TextUtils.isEmpty(fsUuid)) { 1679 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1680 return; 1681 } 1682 1683 // Remove any apps installed on the forgotten volume 1684 synchronized (mPackages) { 1685 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1686 for (PackageSetting ps : packages) { 1687 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1688 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1689 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1690 } 1691 1692 mSettings.onVolumeForgotten(fsUuid); 1693 mSettings.writeLPr(); 1694 } 1695 } 1696 }; 1697 1698 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1699 String[] grantedPermissions) { 1700 if (userId >= UserHandle.USER_OWNER) { 1701 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1702 } else if (userId == UserHandle.USER_ALL) { 1703 final int[] userIds; 1704 synchronized (mPackages) { 1705 userIds = UserManagerService.getInstance().getUserIds(); 1706 } 1707 for (int someUserId : userIds) { 1708 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1709 } 1710 } 1711 1712 // We could have touched GID membership, so flush out packages.list 1713 synchronized (mPackages) { 1714 mSettings.writePackageListLPr(); 1715 } 1716 } 1717 1718 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1719 String[] grantedPermissions) { 1720 SettingBase sb = (SettingBase) pkg.mExtras; 1721 if (sb == null) { 1722 return; 1723 } 1724 1725 PermissionsState permissionsState = sb.getPermissionsState(); 1726 1727 for (String permission : pkg.requestedPermissions) { 1728 BasePermission bp = mSettings.mPermissions.get(permission); 1729 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1730 || ArrayUtils.contains(grantedPermissions, permission))) { 1731 permissionsState.grantRuntimePermission(bp, userId); 1732 } 1733 } 1734 } 1735 1736 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1737 Bundle extras = null; 1738 switch (res.returnCode) { 1739 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1740 extras = new Bundle(); 1741 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1742 res.origPermission); 1743 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1744 res.origPackage); 1745 break; 1746 } 1747 case PackageManager.INSTALL_SUCCEEDED: { 1748 extras = new Bundle(); 1749 extras.putBoolean(Intent.EXTRA_REPLACING, 1750 res.removedInfo != null && res.removedInfo.removedPackage != null); 1751 break; 1752 } 1753 } 1754 return extras; 1755 } 1756 1757 void scheduleWriteSettingsLocked() { 1758 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1759 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1760 } 1761 } 1762 1763 void scheduleWritePackageRestrictionsLocked(int userId) { 1764 if (!sUserManager.exists(userId)) return; 1765 mDirtyUsers.add(userId); 1766 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1767 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1768 } 1769 } 1770 1771 public static PackageManagerService main(Context context, Installer installer, 1772 boolean factoryTest, boolean onlyCore) { 1773 PackageManagerService m = new PackageManagerService(context, installer, 1774 factoryTest, onlyCore); 1775 ServiceManager.addService("package", m); 1776 return m; 1777 } 1778 1779 static String[] splitString(String str, char sep) { 1780 int count = 1; 1781 int i = 0; 1782 while ((i=str.indexOf(sep, i)) >= 0) { 1783 count++; 1784 i++; 1785 } 1786 1787 String[] res = new String[count]; 1788 i=0; 1789 count = 0; 1790 int lastI=0; 1791 while ((i=str.indexOf(sep, i)) >= 0) { 1792 res[count] = str.substring(lastI, i); 1793 count++; 1794 i++; 1795 lastI = i; 1796 } 1797 res[count] = str.substring(lastI, str.length()); 1798 return res; 1799 } 1800 1801 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1802 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1803 Context.DISPLAY_SERVICE); 1804 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1805 } 1806 1807 public PackageManagerService(Context context, Installer installer, 1808 boolean factoryTest, boolean onlyCore) { 1809 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1810 SystemClock.uptimeMillis()); 1811 1812 if (mSdkVersion <= 0) { 1813 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1814 } 1815 1816 mContext = context; 1817 mFactoryTest = factoryTest; 1818 mOnlyCore = onlyCore; 1819 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1820 mMetrics = new DisplayMetrics(); 1821 mSettings = new Settings(mPackages); 1822 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1823 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1824 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1825 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1826 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1827 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1828 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1829 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1830 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1831 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1832 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1833 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1834 1835 // TODO: add a property to control this? 1836 long dexOptLRUThresholdInMinutes; 1837 if (mLazyDexOpt) { 1838 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1839 } else { 1840 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1841 } 1842 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1843 1844 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1845 if (separateProcesses != null && separateProcesses.length() > 0) { 1846 if ("*".equals(separateProcesses)) { 1847 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1848 mSeparateProcesses = null; 1849 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1850 } else { 1851 mDefParseFlags = 0; 1852 mSeparateProcesses = separateProcesses.split(","); 1853 Slog.w(TAG, "Running with debug.separate_processes: " 1854 + separateProcesses); 1855 } 1856 } else { 1857 mDefParseFlags = 0; 1858 mSeparateProcesses = null; 1859 } 1860 1861 mInstaller = installer; 1862 mPackageDexOptimizer = new PackageDexOptimizer(this); 1863 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1864 1865 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1866 FgThread.get().getLooper()); 1867 1868 getDefaultDisplayMetrics(context, mMetrics); 1869 1870 SystemConfig systemConfig = SystemConfig.getInstance(); 1871 mGlobalGids = systemConfig.getGlobalGids(); 1872 mSystemPermissions = systemConfig.getSystemPermissions(); 1873 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1874 1875 synchronized (mInstallLock) { 1876 // writer 1877 synchronized (mPackages) { 1878 mHandlerThread = new ServiceThread(TAG, 1879 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1880 mHandlerThread.start(); 1881 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1882 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1883 1884 File dataDir = Environment.getDataDirectory(); 1885 mAppDataDir = new File(dataDir, "data"); 1886 mAppInstallDir = new File(dataDir, "app"); 1887 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1888 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1889 mUserAppDataDir = new File(dataDir, "user"); 1890 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1891 1892 sUserManager = new UserManagerService(context, this, 1893 mInstallLock, mPackages); 1894 1895 // Propagate permission configuration in to package manager. 1896 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1897 = systemConfig.getPermissions(); 1898 for (int i=0; i<permConfig.size(); i++) { 1899 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1900 BasePermission bp = mSettings.mPermissions.get(perm.name); 1901 if (bp == null) { 1902 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1903 mSettings.mPermissions.put(perm.name, bp); 1904 } 1905 if (perm.gids != null) { 1906 bp.setGids(perm.gids, perm.perUser); 1907 } 1908 } 1909 1910 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1911 for (int i=0; i<libConfig.size(); i++) { 1912 mSharedLibraries.put(libConfig.keyAt(i), 1913 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1914 } 1915 1916 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1917 1918 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1919 mSdkVersion, mOnlyCore); 1920 1921 String customResolverActivity = Resources.getSystem().getString( 1922 R.string.config_customResolverActivity); 1923 if (TextUtils.isEmpty(customResolverActivity)) { 1924 customResolverActivity = null; 1925 } else { 1926 mCustomResolverComponentName = ComponentName.unflattenFromString( 1927 customResolverActivity); 1928 } 1929 1930 long startTime = SystemClock.uptimeMillis(); 1931 1932 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1933 startTime); 1934 1935 // Set flag to monitor and not change apk file paths when 1936 // scanning install directories. 1937 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1938 1939 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1940 1941 /** 1942 * Add everything in the in the boot class path to the 1943 * list of process files because dexopt will have been run 1944 * if necessary during zygote startup. 1945 */ 1946 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1947 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1948 1949 if (bootClassPath != null) { 1950 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1951 for (String element : bootClassPathElements) { 1952 alreadyDexOpted.add(element); 1953 } 1954 } else { 1955 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1956 } 1957 1958 if (systemServerClassPath != null) { 1959 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1960 for (String element : systemServerClassPathElements) { 1961 alreadyDexOpted.add(element); 1962 } 1963 } else { 1964 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1965 } 1966 1967 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1968 final String[] dexCodeInstructionSets = 1969 getDexCodeInstructionSets( 1970 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1971 1972 /** 1973 * Ensure all external libraries have had dexopt run on them. 1974 */ 1975 if (mSharedLibraries.size() > 0) { 1976 // NOTE: For now, we're compiling these system "shared libraries" 1977 // (and framework jars) into all available architectures. It's possible 1978 // to compile them only when we come across an app that uses them (there's 1979 // already logic for that in scanPackageLI) but that adds some complexity. 1980 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1981 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1982 final String lib = libEntry.path; 1983 if (lib == null) { 1984 continue; 1985 } 1986 1987 try { 1988 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1989 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1990 alreadyDexOpted.add(lib); 1991 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1992 } 1993 } catch (FileNotFoundException e) { 1994 Slog.w(TAG, "Library not found: " + lib); 1995 } catch (IOException e) { 1996 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1997 + e.getMessage()); 1998 } 1999 } 2000 } 2001 } 2002 2003 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2004 2005 // Gross hack for now: we know this file doesn't contain any 2006 // code, so don't dexopt it to avoid the resulting log spew. 2007 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 2008 2009 // Gross hack for now: we know this file is only part of 2010 // the boot class path for art, so don't dexopt it to 2011 // avoid the resulting log spew. 2012 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 2013 2014 /** 2015 * There are a number of commands implemented in Java, which 2016 * we currently need to do the dexopt on so that they can be 2017 * run from a non-root shell. 2018 */ 2019 String[] frameworkFiles = frameworkDir.list(); 2020 if (frameworkFiles != null) { 2021 // TODO: We could compile these only for the most preferred ABI. We should 2022 // first double check that the dex files for these commands are not referenced 2023 // by other system apps. 2024 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2025 for (int i=0; i<frameworkFiles.length; i++) { 2026 File libPath = new File(frameworkDir, frameworkFiles[i]); 2027 String path = libPath.getPath(); 2028 // Skip the file if we already did it. 2029 if (alreadyDexOpted.contains(path)) { 2030 continue; 2031 } 2032 // Skip the file if it is not a type we want to dexopt. 2033 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2034 continue; 2035 } 2036 try { 2037 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2038 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2039 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2040 } 2041 } catch (FileNotFoundException e) { 2042 Slog.w(TAG, "Jar not found: " + path); 2043 } catch (IOException e) { 2044 Slog.w(TAG, "Exception reading jar: " + path, e); 2045 } 2046 } 2047 } 2048 } 2049 2050 // Collect vendor overlay packages. 2051 // (Do this before scanning any apps.) 2052 // For security and version matching reason, only consider 2053 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2054 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2055 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2056 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2057 2058 // Find base frameworks (resource packages without code). 2059 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2060 | PackageParser.PARSE_IS_SYSTEM_DIR 2061 | PackageParser.PARSE_IS_PRIVILEGED, 2062 scanFlags | SCAN_NO_DEX, 0); 2063 2064 // Collected privileged system packages. 2065 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2066 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2067 | PackageParser.PARSE_IS_SYSTEM_DIR 2068 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2069 2070 // Collect ordinary system packages. 2071 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2072 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2073 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2074 2075 // Collect all vendor packages. 2076 File vendorAppDir = new File("/vendor/app"); 2077 try { 2078 vendorAppDir = vendorAppDir.getCanonicalFile(); 2079 } catch (IOException e) { 2080 // failed to look up canonical path, continue with original one 2081 } 2082 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2083 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2084 2085 // Collect all OEM packages. 2086 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2087 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2088 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2089 2090 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2091 mInstaller.moveFiles(); 2092 2093 // Prune any system packages that no longer exist. 2094 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2095 if (!mOnlyCore) { 2096 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2097 while (psit.hasNext()) { 2098 PackageSetting ps = psit.next(); 2099 2100 /* 2101 * If this is not a system app, it can't be a 2102 * disable system app. 2103 */ 2104 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2105 continue; 2106 } 2107 2108 /* 2109 * If the package is scanned, it's not erased. 2110 */ 2111 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2112 if (scannedPkg != null) { 2113 /* 2114 * If the system app is both scanned and in the 2115 * disabled packages list, then it must have been 2116 * added via OTA. Remove it from the currently 2117 * scanned package so the previously user-installed 2118 * application can be scanned. 2119 */ 2120 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2121 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2122 + ps.name + "; removing system app. Last known codePath=" 2123 + ps.codePathString + ", installStatus=" + ps.installStatus 2124 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2125 + scannedPkg.mVersionCode); 2126 removePackageLI(ps, true); 2127 mExpectingBetter.put(ps.name, ps.codePath); 2128 } 2129 2130 continue; 2131 } 2132 2133 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2134 psit.remove(); 2135 logCriticalInfo(Log.WARN, "System package " + ps.name 2136 + " no longer exists; wiping its data"); 2137 removeDataDirsLI(null, ps.name); 2138 } else { 2139 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2140 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2141 possiblyDeletedUpdatedSystemApps.add(ps.name); 2142 } 2143 } 2144 } 2145 } 2146 2147 //look for any incomplete package installations 2148 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2149 //clean up list 2150 for(int i = 0; i < deletePkgsList.size(); i++) { 2151 //clean up here 2152 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2153 } 2154 //delete tmp files 2155 deleteTempPackageFiles(); 2156 2157 // Remove any shared userIDs that have no associated packages 2158 mSettings.pruneSharedUsersLPw(); 2159 2160 if (!mOnlyCore) { 2161 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2162 SystemClock.uptimeMillis()); 2163 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2164 2165 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2166 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2167 2168 /** 2169 * Remove disable package settings for any updated system 2170 * apps that were removed via an OTA. If they're not a 2171 * previously-updated app, remove them completely. 2172 * Otherwise, just revoke their system-level permissions. 2173 */ 2174 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2175 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2176 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2177 2178 String msg; 2179 if (deletedPkg == null) { 2180 msg = "Updated system package " + deletedAppName 2181 + " no longer exists; wiping its data"; 2182 removeDataDirsLI(null, deletedAppName); 2183 } else { 2184 msg = "Updated system app + " + deletedAppName 2185 + " no longer present; removing system privileges for " 2186 + deletedAppName; 2187 2188 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2189 2190 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2191 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2192 } 2193 logCriticalInfo(Log.WARN, msg); 2194 } 2195 2196 /** 2197 * Make sure all system apps that we expected to appear on 2198 * the userdata partition actually showed up. If they never 2199 * appeared, crawl back and revive the system version. 2200 */ 2201 for (int i = 0; i < mExpectingBetter.size(); i++) { 2202 final String packageName = mExpectingBetter.keyAt(i); 2203 if (!mPackages.containsKey(packageName)) { 2204 final File scanFile = mExpectingBetter.valueAt(i); 2205 2206 logCriticalInfo(Log.WARN, "Expected better " + packageName 2207 + " but never showed up; reverting to system"); 2208 2209 final int reparseFlags; 2210 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2211 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2212 | PackageParser.PARSE_IS_SYSTEM_DIR 2213 | PackageParser.PARSE_IS_PRIVILEGED; 2214 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2215 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2216 | PackageParser.PARSE_IS_SYSTEM_DIR; 2217 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2218 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2219 | PackageParser.PARSE_IS_SYSTEM_DIR; 2220 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2221 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2222 | PackageParser.PARSE_IS_SYSTEM_DIR; 2223 } else { 2224 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2225 continue; 2226 } 2227 2228 mSettings.enableSystemPackageLPw(packageName); 2229 2230 try { 2231 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2232 } catch (PackageManagerException e) { 2233 Slog.e(TAG, "Failed to parse original system package: " 2234 + e.getMessage()); 2235 } 2236 } 2237 } 2238 } 2239 mExpectingBetter.clear(); 2240 2241 // Now that we know all of the shared libraries, update all clients to have 2242 // the correct library paths. 2243 updateAllSharedLibrariesLPw(); 2244 2245 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2246 // NOTE: We ignore potential failures here during a system scan (like 2247 // the rest of the commands above) because there's precious little we 2248 // can do about it. A settings error is reported, though. 2249 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2250 false /* force dexopt */, false /* defer dexopt */); 2251 } 2252 2253 // Now that we know all the packages we are keeping, 2254 // read and update their last usage times. 2255 mPackageUsage.readLP(); 2256 2257 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2258 SystemClock.uptimeMillis()); 2259 Slog.i(TAG, "Time to scan packages: " 2260 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2261 + " seconds"); 2262 2263 // If the platform SDK has changed since the last time we booted, 2264 // we need to re-grant app permission to catch any new ones that 2265 // appear. This is really a hack, and means that apps can in some 2266 // cases get permissions that the user didn't initially explicitly 2267 // allow... it would be nice to have some better way to handle 2268 // this situation. 2269 final VersionInfo ver = mSettings.getInternalVersion(); 2270 2271 int updateFlags = UPDATE_PERMISSIONS_ALL; 2272 if (ver.sdkVersion != mSdkVersion) { 2273 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2274 + mSdkVersion + "; regranting permissions for internal storage"); 2275 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2276 } 2277 updatePermissionsLPw(null, null, updateFlags); 2278 ver.sdkVersion = mSdkVersion; 2279 2280 // If this is the first boot, and it is a normal boot, then 2281 // we need to initialize the default preferred apps. 2282 if (!mRestoredSettings && !onlyCore) { 2283 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2284 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2285 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2286 } 2287 2288 // If this is first boot after an OTA, and a normal boot, then 2289 // we need to clear code cache directories. 2290 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2291 if (mIsUpgrade && !onlyCore) { 2292 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2293 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2294 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2295 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2296 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2297 } 2298 } 2299 ver.fingerprint = Build.FINGERPRINT; 2300 } 2301 2302 checkDefaultBrowser(); 2303 2304 // All the changes are done during package scanning. 2305 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2306 2307 // can downgrade to reader 2308 mSettings.writeLPr(); 2309 2310 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2311 SystemClock.uptimeMillis()); 2312 2313 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2314 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2315 2316 mInstallerService = new PackageInstallerService(context, this); 2317 2318 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2319 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2320 mIntentFilterVerifierComponent); 2321 2322 } // synchronized (mPackages) 2323 } // synchronized (mInstallLock) 2324 2325 // Now after opening every single application zip, make sure they 2326 // are all flushed. Not really needed, but keeps things nice and 2327 // tidy. 2328 Runtime.getRuntime().gc(); 2329 2330 // Expose private service for system components to use. 2331 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2332 } 2333 2334 @Override 2335 public boolean isFirstBoot() { 2336 return !mRestoredSettings; 2337 } 2338 2339 @Override 2340 public boolean isOnlyCoreApps() { 2341 return mOnlyCore; 2342 } 2343 2344 @Override 2345 public boolean isUpgrade() { 2346 return mIsUpgrade; 2347 } 2348 2349 private String getRequiredVerifierLPr() { 2350 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2351 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2352 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2353 2354 String requiredVerifier = null; 2355 2356 final int N = receivers.size(); 2357 for (int i = 0; i < N; i++) { 2358 final ResolveInfo info = receivers.get(i); 2359 2360 if (info.activityInfo == null) { 2361 continue; 2362 } 2363 2364 final String packageName = info.activityInfo.packageName; 2365 2366 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2367 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2368 continue; 2369 } 2370 2371 if (requiredVerifier != null) { 2372 throw new RuntimeException("There can be only one required verifier"); 2373 } 2374 2375 requiredVerifier = packageName; 2376 } 2377 2378 return requiredVerifier; 2379 } 2380 2381 private String getRequiredInstallerLPr() { 2382 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2383 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2384 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2385 2386 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2387 PACKAGE_MIME_TYPE, 0, 0); 2388 2389 String requiredInstaller = null; 2390 2391 final int N = installers.size(); 2392 for (int i = 0; i < N; i++) { 2393 final ResolveInfo info = installers.get(i); 2394 final String packageName = info.activityInfo.packageName; 2395 2396 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2397 continue; 2398 } 2399 2400 if (requiredInstaller != null) { 2401 throw new RuntimeException("There must be one required installer"); 2402 } 2403 2404 requiredInstaller = packageName; 2405 } 2406 2407 if (requiredInstaller == null) { 2408 throw new RuntimeException("There must be one required installer"); 2409 } 2410 2411 return requiredInstaller; 2412 } 2413 2414 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2415 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2416 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2417 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2418 2419 ComponentName verifierComponentName = null; 2420 2421 int priority = -1000; 2422 final int N = receivers.size(); 2423 for (int i = 0; i < N; i++) { 2424 final ResolveInfo info = receivers.get(i); 2425 2426 if (info.activityInfo == null) { 2427 continue; 2428 } 2429 2430 final String packageName = info.activityInfo.packageName; 2431 2432 final PackageSetting ps = mSettings.mPackages.get(packageName); 2433 if (ps == null) { 2434 continue; 2435 } 2436 2437 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2438 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2439 continue; 2440 } 2441 2442 // Select the IntentFilterVerifier with the highest priority 2443 if (priority < info.priority) { 2444 priority = info.priority; 2445 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2446 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2447 + verifierComponentName + " with priority: " + info.priority); 2448 } 2449 } 2450 2451 return verifierComponentName; 2452 } 2453 2454 private void primeDomainVerificationsLPw(int userId) { 2455 if (DEBUG_DOMAIN_VERIFICATION) { 2456 Slog.d(TAG, "Priming domain verifications in user " + userId); 2457 } 2458 2459 SystemConfig systemConfig = SystemConfig.getInstance(); 2460 ArraySet<String> packages = systemConfig.getLinkedApps(); 2461 ArraySet<String> domains = new ArraySet<String>(); 2462 2463 for (String packageName : packages) { 2464 PackageParser.Package pkg = mPackages.get(packageName); 2465 if (pkg != null) { 2466 if (!pkg.isSystemApp()) { 2467 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2468 continue; 2469 } 2470 2471 domains.clear(); 2472 for (PackageParser.Activity a : pkg.activities) { 2473 for (ActivityIntentInfo filter : a.intents) { 2474 if (hasValidDomains(filter)) { 2475 domains.addAll(filter.getHostsList()); 2476 } 2477 } 2478 } 2479 2480 if (domains.size() > 0) { 2481 if (DEBUG_DOMAIN_VERIFICATION) { 2482 Slog.v(TAG, " + " + packageName); 2483 } 2484 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2485 // state w.r.t. the formal app-linkage "no verification attempted" state; 2486 // and then 'always' in the per-user state actually used for intent resolution. 2487 final IntentFilterVerificationInfo ivi; 2488 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2489 new ArrayList<String>(domains)); 2490 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2491 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2492 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2493 } else { 2494 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2495 + "' does not handle web links"); 2496 } 2497 } else { 2498 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2499 } 2500 } 2501 2502 scheduleWritePackageRestrictionsLocked(userId); 2503 scheduleWriteSettingsLocked(); 2504 } 2505 2506 private void applyFactoryDefaultBrowserLPw(int userId) { 2507 // The default browser app's package name is stored in a string resource, 2508 // with a product-specific overlay used for vendor customization. 2509 String browserPkg = mContext.getResources().getString( 2510 com.android.internal.R.string.default_browser); 2511 if (!TextUtils.isEmpty(browserPkg)) { 2512 // non-empty string => required to be a known package 2513 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2514 if (ps == null) { 2515 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2516 browserPkg = null; 2517 } else { 2518 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2519 } 2520 } 2521 2522 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2523 // default. If there's more than one, just leave everything alone. 2524 if (browserPkg == null) { 2525 calculateDefaultBrowserLPw(userId); 2526 } 2527 } 2528 2529 private void calculateDefaultBrowserLPw(int userId) { 2530 List<String> allBrowsers = resolveAllBrowserApps(userId); 2531 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2532 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2533 } 2534 2535 private List<String> resolveAllBrowserApps(int userId) { 2536 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2537 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2538 PackageManager.MATCH_ALL, userId); 2539 2540 final int count = list.size(); 2541 List<String> result = new ArrayList<String>(count); 2542 for (int i=0; i<count; i++) { 2543 ResolveInfo info = list.get(i); 2544 if (info.activityInfo == null 2545 || !info.handleAllWebDataURI 2546 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2547 || result.contains(info.activityInfo.packageName)) { 2548 continue; 2549 } 2550 result.add(info.activityInfo.packageName); 2551 } 2552 2553 return result; 2554 } 2555 2556 private boolean packageIsBrowser(String packageName, int userId) { 2557 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2558 PackageManager.MATCH_ALL, userId); 2559 final int N = list.size(); 2560 for (int i = 0; i < N; i++) { 2561 ResolveInfo info = list.get(i); 2562 if (packageName.equals(info.activityInfo.packageName)) { 2563 return true; 2564 } 2565 } 2566 return false; 2567 } 2568 2569 private void checkDefaultBrowser() { 2570 final int myUserId = UserHandle.myUserId(); 2571 final String packageName = getDefaultBrowserPackageName(myUserId); 2572 if (packageName != null) { 2573 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2574 if (info == null) { 2575 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2576 synchronized (mPackages) { 2577 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2578 } 2579 } 2580 } 2581 } 2582 2583 @Override 2584 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2585 throws RemoteException { 2586 try { 2587 return super.onTransact(code, data, reply, flags); 2588 } catch (RuntimeException e) { 2589 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2590 Slog.wtf(TAG, "Package Manager Crash", e); 2591 } 2592 throw e; 2593 } 2594 } 2595 2596 void cleanupInstallFailedPackage(PackageSetting ps) { 2597 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2598 2599 removeDataDirsLI(ps.volumeUuid, ps.name); 2600 if (ps.codePath != null) { 2601 if (ps.codePath.isDirectory()) { 2602 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2603 } else { 2604 ps.codePath.delete(); 2605 } 2606 } 2607 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2608 if (ps.resourcePath.isDirectory()) { 2609 FileUtils.deleteContents(ps.resourcePath); 2610 } 2611 ps.resourcePath.delete(); 2612 } 2613 mSettings.removePackageLPw(ps.name); 2614 } 2615 2616 static int[] appendInts(int[] cur, int[] add) { 2617 if (add == null) return cur; 2618 if (cur == null) return add; 2619 final int N = add.length; 2620 for (int i=0; i<N; i++) { 2621 cur = appendInt(cur, add[i]); 2622 } 2623 return cur; 2624 } 2625 2626 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2627 if (!sUserManager.exists(userId)) return null; 2628 final PackageSetting ps = (PackageSetting) p.mExtras; 2629 if (ps == null) { 2630 return null; 2631 } 2632 2633 final PermissionsState permissionsState = ps.getPermissionsState(); 2634 2635 final int[] gids = permissionsState.computeGids(userId); 2636 final Set<String> permissions = permissionsState.getPermissions(userId); 2637 final PackageUserState state = ps.readUserState(userId); 2638 2639 return PackageParser.generatePackageInfo(p, gids, flags, 2640 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2641 } 2642 2643 @Override 2644 public boolean isPackageFrozen(String packageName) { 2645 synchronized (mPackages) { 2646 final PackageSetting ps = mSettings.mPackages.get(packageName); 2647 if (ps != null) { 2648 return ps.frozen; 2649 } 2650 } 2651 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2652 return true; 2653 } 2654 2655 @Override 2656 public boolean isPackageAvailable(String packageName, int userId) { 2657 if (!sUserManager.exists(userId)) return false; 2658 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2659 synchronized (mPackages) { 2660 PackageParser.Package p = mPackages.get(packageName); 2661 if (p != null) { 2662 final PackageSetting ps = (PackageSetting) p.mExtras; 2663 if (ps != null) { 2664 final PackageUserState state = ps.readUserState(userId); 2665 if (state != null) { 2666 return PackageParser.isAvailable(state); 2667 } 2668 } 2669 } 2670 } 2671 return false; 2672 } 2673 2674 @Override 2675 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2676 if (!sUserManager.exists(userId)) return null; 2677 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2678 // reader 2679 synchronized (mPackages) { 2680 PackageParser.Package p = mPackages.get(packageName); 2681 if (DEBUG_PACKAGE_INFO) 2682 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2683 if (p != null) { 2684 return generatePackageInfo(p, flags, userId); 2685 } 2686 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2687 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2688 } 2689 } 2690 return null; 2691 } 2692 2693 @Override 2694 public String[] currentToCanonicalPackageNames(String[] names) { 2695 String[] out = new String[names.length]; 2696 // reader 2697 synchronized (mPackages) { 2698 for (int i=names.length-1; i>=0; i--) { 2699 PackageSetting ps = mSettings.mPackages.get(names[i]); 2700 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2701 } 2702 } 2703 return out; 2704 } 2705 2706 @Override 2707 public String[] canonicalToCurrentPackageNames(String[] names) { 2708 String[] out = new String[names.length]; 2709 // reader 2710 synchronized (mPackages) { 2711 for (int i=names.length-1; i>=0; i--) { 2712 String cur = mSettings.mRenamedPackages.get(names[i]); 2713 out[i] = cur != null ? cur : names[i]; 2714 } 2715 } 2716 return out; 2717 } 2718 2719 @Override 2720 public int getPackageUid(String packageName, int userId) { 2721 if (!sUserManager.exists(userId)) return -1; 2722 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2723 2724 // reader 2725 synchronized (mPackages) { 2726 PackageParser.Package p = mPackages.get(packageName); 2727 if(p != null) { 2728 return UserHandle.getUid(userId, p.applicationInfo.uid); 2729 } 2730 PackageSetting ps = mSettings.mPackages.get(packageName); 2731 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2732 return -1; 2733 } 2734 p = ps.pkg; 2735 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2736 } 2737 } 2738 2739 @Override 2740 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2741 if (!sUserManager.exists(userId)) { 2742 return null; 2743 } 2744 2745 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2746 "getPackageGids"); 2747 2748 // reader 2749 synchronized (mPackages) { 2750 PackageParser.Package p = mPackages.get(packageName); 2751 if (DEBUG_PACKAGE_INFO) { 2752 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2753 } 2754 if (p != null) { 2755 PackageSetting ps = (PackageSetting) p.mExtras; 2756 return ps.getPermissionsState().computeGids(userId); 2757 } 2758 } 2759 2760 return null; 2761 } 2762 2763 static PermissionInfo generatePermissionInfo( 2764 BasePermission bp, int flags) { 2765 if (bp.perm != null) { 2766 return PackageParser.generatePermissionInfo(bp.perm, flags); 2767 } 2768 PermissionInfo pi = new PermissionInfo(); 2769 pi.name = bp.name; 2770 pi.packageName = bp.sourcePackage; 2771 pi.nonLocalizedLabel = bp.name; 2772 pi.protectionLevel = bp.protectionLevel; 2773 return pi; 2774 } 2775 2776 @Override 2777 public PermissionInfo getPermissionInfo(String name, int flags) { 2778 // reader 2779 synchronized (mPackages) { 2780 final BasePermission p = mSettings.mPermissions.get(name); 2781 if (p != null) { 2782 return generatePermissionInfo(p, flags); 2783 } 2784 return null; 2785 } 2786 } 2787 2788 @Override 2789 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2790 // reader 2791 synchronized (mPackages) { 2792 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2793 for (BasePermission p : mSettings.mPermissions.values()) { 2794 if (group == null) { 2795 if (p.perm == null || p.perm.info.group == null) { 2796 out.add(generatePermissionInfo(p, flags)); 2797 } 2798 } else { 2799 if (p.perm != null && group.equals(p.perm.info.group)) { 2800 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2801 } 2802 } 2803 } 2804 2805 if (out.size() > 0) { 2806 return out; 2807 } 2808 return mPermissionGroups.containsKey(group) ? out : null; 2809 } 2810 } 2811 2812 @Override 2813 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2814 // reader 2815 synchronized (mPackages) { 2816 return PackageParser.generatePermissionGroupInfo( 2817 mPermissionGroups.get(name), flags); 2818 } 2819 } 2820 2821 @Override 2822 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2823 // reader 2824 synchronized (mPackages) { 2825 final int N = mPermissionGroups.size(); 2826 ArrayList<PermissionGroupInfo> out 2827 = new ArrayList<PermissionGroupInfo>(N); 2828 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2829 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2830 } 2831 return out; 2832 } 2833 } 2834 2835 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2836 int userId) { 2837 if (!sUserManager.exists(userId)) return null; 2838 PackageSetting ps = mSettings.mPackages.get(packageName); 2839 if (ps != null) { 2840 if (ps.pkg == null) { 2841 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2842 flags, userId); 2843 if (pInfo != null) { 2844 return pInfo.applicationInfo; 2845 } 2846 return null; 2847 } 2848 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2849 ps.readUserState(userId), userId); 2850 } 2851 return null; 2852 } 2853 2854 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2855 int userId) { 2856 if (!sUserManager.exists(userId)) return null; 2857 PackageSetting ps = mSettings.mPackages.get(packageName); 2858 if (ps != null) { 2859 PackageParser.Package pkg = ps.pkg; 2860 if (pkg == null) { 2861 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2862 return null; 2863 } 2864 // Only data remains, so we aren't worried about code paths 2865 pkg = new PackageParser.Package(packageName); 2866 pkg.applicationInfo.packageName = packageName; 2867 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2868 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2869 pkg.applicationInfo.dataDir = Environment 2870 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2871 .getAbsolutePath(); 2872 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2873 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2874 } 2875 return generatePackageInfo(pkg, flags, userId); 2876 } 2877 return null; 2878 } 2879 2880 @Override 2881 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2882 if (!sUserManager.exists(userId)) return null; 2883 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2884 // writer 2885 synchronized (mPackages) { 2886 PackageParser.Package p = mPackages.get(packageName); 2887 if (DEBUG_PACKAGE_INFO) Log.v( 2888 TAG, "getApplicationInfo " + packageName 2889 + ": " + p); 2890 if (p != null) { 2891 PackageSetting ps = mSettings.mPackages.get(packageName); 2892 if (ps == null) return null; 2893 // Note: isEnabledLP() does not apply here - always return info 2894 return PackageParser.generateApplicationInfo( 2895 p, flags, ps.readUserState(userId), userId); 2896 } 2897 if ("android".equals(packageName)||"system".equals(packageName)) { 2898 return mAndroidApplication; 2899 } 2900 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2901 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2902 } 2903 } 2904 return null; 2905 } 2906 2907 @Override 2908 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2909 final IPackageDataObserver observer) { 2910 mContext.enforceCallingOrSelfPermission( 2911 android.Manifest.permission.CLEAR_APP_CACHE, null); 2912 // Queue up an async operation since clearing cache may take a little while. 2913 mHandler.post(new Runnable() { 2914 public void run() { 2915 mHandler.removeCallbacks(this); 2916 int retCode = -1; 2917 synchronized (mInstallLock) { 2918 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2919 if (retCode < 0) { 2920 Slog.w(TAG, "Couldn't clear application caches"); 2921 } 2922 } 2923 if (observer != null) { 2924 try { 2925 observer.onRemoveCompleted(null, (retCode >= 0)); 2926 } catch (RemoteException e) { 2927 Slog.w(TAG, "RemoveException when invoking call back"); 2928 } 2929 } 2930 } 2931 }); 2932 } 2933 2934 @Override 2935 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2936 final IntentSender pi) { 2937 mContext.enforceCallingOrSelfPermission( 2938 android.Manifest.permission.CLEAR_APP_CACHE, null); 2939 // Queue up an async operation since clearing cache may take a little while. 2940 mHandler.post(new Runnable() { 2941 public void run() { 2942 mHandler.removeCallbacks(this); 2943 int retCode = -1; 2944 synchronized (mInstallLock) { 2945 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2946 if (retCode < 0) { 2947 Slog.w(TAG, "Couldn't clear application caches"); 2948 } 2949 } 2950 if(pi != null) { 2951 try { 2952 // Callback via pending intent 2953 int code = (retCode >= 0) ? 1 : 0; 2954 pi.sendIntent(null, code, null, 2955 null, null); 2956 } catch (SendIntentException e1) { 2957 Slog.i(TAG, "Failed to send pending intent"); 2958 } 2959 } 2960 } 2961 }); 2962 } 2963 2964 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2965 synchronized (mInstallLock) { 2966 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2967 throw new IOException("Failed to free enough space"); 2968 } 2969 } 2970 } 2971 2972 @Override 2973 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2974 if (!sUserManager.exists(userId)) return null; 2975 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2976 synchronized (mPackages) { 2977 PackageParser.Activity a = mActivities.mActivities.get(component); 2978 2979 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2980 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2981 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2982 if (ps == null) return null; 2983 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2984 userId); 2985 } 2986 if (mResolveComponentName.equals(component)) { 2987 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2988 new PackageUserState(), userId); 2989 } 2990 } 2991 return null; 2992 } 2993 2994 @Override 2995 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2996 String resolvedType) { 2997 synchronized (mPackages) { 2998 if (component.equals(mResolveComponentName)) { 2999 // The resolver supports EVERYTHING! 3000 return true; 3001 } 3002 PackageParser.Activity a = mActivities.mActivities.get(component); 3003 if (a == null) { 3004 return false; 3005 } 3006 for (int i=0; i<a.intents.size(); i++) { 3007 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3008 intent.getData(), intent.getCategories(), TAG) >= 0) { 3009 return true; 3010 } 3011 } 3012 return false; 3013 } 3014 } 3015 3016 @Override 3017 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3018 if (!sUserManager.exists(userId)) return null; 3019 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3020 synchronized (mPackages) { 3021 PackageParser.Activity a = mReceivers.mActivities.get(component); 3022 if (DEBUG_PACKAGE_INFO) Log.v( 3023 TAG, "getReceiverInfo " + component + ": " + a); 3024 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3025 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3026 if (ps == null) return null; 3027 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3028 userId); 3029 } 3030 } 3031 return null; 3032 } 3033 3034 @Override 3035 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3036 if (!sUserManager.exists(userId)) return null; 3037 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3038 synchronized (mPackages) { 3039 PackageParser.Service s = mServices.mServices.get(component); 3040 if (DEBUG_PACKAGE_INFO) Log.v( 3041 TAG, "getServiceInfo " + component + ": " + s); 3042 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3043 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3044 if (ps == null) return null; 3045 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3046 userId); 3047 } 3048 } 3049 return null; 3050 } 3051 3052 @Override 3053 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3054 if (!sUserManager.exists(userId)) return null; 3055 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3056 synchronized (mPackages) { 3057 PackageParser.Provider p = mProviders.mProviders.get(component); 3058 if (DEBUG_PACKAGE_INFO) Log.v( 3059 TAG, "getProviderInfo " + component + ": " + p); 3060 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3061 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3062 if (ps == null) return null; 3063 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3064 userId); 3065 } 3066 } 3067 return null; 3068 } 3069 3070 @Override 3071 public String[] getSystemSharedLibraryNames() { 3072 Set<String> libSet; 3073 synchronized (mPackages) { 3074 libSet = mSharedLibraries.keySet(); 3075 int size = libSet.size(); 3076 if (size > 0) { 3077 String[] libs = new String[size]; 3078 libSet.toArray(libs); 3079 return libs; 3080 } 3081 } 3082 return null; 3083 } 3084 3085 /** 3086 * @hide 3087 */ 3088 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3089 synchronized (mPackages) { 3090 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3091 if (lib != null && lib.apk != null) { 3092 return mPackages.get(lib.apk); 3093 } 3094 } 3095 return null; 3096 } 3097 3098 @Override 3099 public FeatureInfo[] getSystemAvailableFeatures() { 3100 Collection<FeatureInfo> featSet; 3101 synchronized (mPackages) { 3102 featSet = mAvailableFeatures.values(); 3103 int size = featSet.size(); 3104 if (size > 0) { 3105 FeatureInfo[] features = new FeatureInfo[size+1]; 3106 featSet.toArray(features); 3107 FeatureInfo fi = new FeatureInfo(); 3108 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3109 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3110 features[size] = fi; 3111 return features; 3112 } 3113 } 3114 return null; 3115 } 3116 3117 @Override 3118 public boolean hasSystemFeature(String name) { 3119 synchronized (mPackages) { 3120 return mAvailableFeatures.containsKey(name); 3121 } 3122 } 3123 3124 private void checkValidCaller(int uid, int userId) { 3125 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3126 return; 3127 3128 throw new SecurityException("Caller uid=" + uid 3129 + " is not privileged to communicate with user=" + userId); 3130 } 3131 3132 @Override 3133 public int checkPermission(String permName, String pkgName, int userId) { 3134 if (!sUserManager.exists(userId)) { 3135 return PackageManager.PERMISSION_DENIED; 3136 } 3137 3138 synchronized (mPackages) { 3139 final PackageParser.Package p = mPackages.get(pkgName); 3140 if (p != null && p.mExtras != null) { 3141 final PackageSetting ps = (PackageSetting) p.mExtras; 3142 final PermissionsState permissionsState = ps.getPermissionsState(); 3143 if (permissionsState.hasPermission(permName, userId)) { 3144 return PackageManager.PERMISSION_GRANTED; 3145 } 3146 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3147 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3148 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3149 return PackageManager.PERMISSION_GRANTED; 3150 } 3151 } 3152 } 3153 3154 return PackageManager.PERMISSION_DENIED; 3155 } 3156 3157 @Override 3158 public int checkUidPermission(String permName, int uid) { 3159 final int userId = UserHandle.getUserId(uid); 3160 3161 if (!sUserManager.exists(userId)) { 3162 return PackageManager.PERMISSION_DENIED; 3163 } 3164 3165 synchronized (mPackages) { 3166 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3167 if (obj != null) { 3168 final SettingBase ps = (SettingBase) obj; 3169 final PermissionsState permissionsState = ps.getPermissionsState(); 3170 if (permissionsState.hasPermission(permName, userId)) { 3171 return PackageManager.PERMISSION_GRANTED; 3172 } 3173 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3174 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3175 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3176 return PackageManager.PERMISSION_GRANTED; 3177 } 3178 } else { 3179 ArraySet<String> perms = mSystemPermissions.get(uid); 3180 if (perms != null) { 3181 if (perms.contains(permName)) { 3182 return PackageManager.PERMISSION_GRANTED; 3183 } 3184 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3185 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3186 return PackageManager.PERMISSION_GRANTED; 3187 } 3188 } 3189 } 3190 } 3191 3192 return PackageManager.PERMISSION_DENIED; 3193 } 3194 3195 @Override 3196 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3197 if (UserHandle.getCallingUserId() != userId) { 3198 mContext.enforceCallingPermission( 3199 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3200 "isPermissionRevokedByPolicy for user " + userId); 3201 } 3202 3203 if (checkPermission(permission, packageName, userId) 3204 == PackageManager.PERMISSION_GRANTED) { 3205 return false; 3206 } 3207 3208 final long identity = Binder.clearCallingIdentity(); 3209 try { 3210 final int flags = getPermissionFlags(permission, packageName, userId); 3211 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3212 } finally { 3213 Binder.restoreCallingIdentity(identity); 3214 } 3215 } 3216 3217 @Override 3218 public String getPermissionControllerPackageName() { 3219 synchronized (mPackages) { 3220 return mRequiredInstallerPackage; 3221 } 3222 } 3223 3224 /** 3225 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3226 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3227 * @param checkShell TODO(yamasani): 3228 * @param message the message to log on security exception 3229 */ 3230 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3231 boolean checkShell, String message) { 3232 if (userId < 0) { 3233 throw new IllegalArgumentException("Invalid userId " + userId); 3234 } 3235 if (checkShell) { 3236 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3237 } 3238 if (userId == UserHandle.getUserId(callingUid)) return; 3239 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3240 if (requireFullPermission) { 3241 mContext.enforceCallingOrSelfPermission( 3242 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3243 } else { 3244 try { 3245 mContext.enforceCallingOrSelfPermission( 3246 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3247 } catch (SecurityException se) { 3248 mContext.enforceCallingOrSelfPermission( 3249 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3250 } 3251 } 3252 } 3253 } 3254 3255 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3256 if (callingUid == Process.SHELL_UID) { 3257 if (userHandle >= 0 3258 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3259 throw new SecurityException("Shell does not have permission to access user " 3260 + userHandle); 3261 } else if (userHandle < 0) { 3262 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3263 + Debug.getCallers(3)); 3264 } 3265 } 3266 } 3267 3268 private BasePermission findPermissionTreeLP(String permName) { 3269 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3270 if (permName.startsWith(bp.name) && 3271 permName.length() > bp.name.length() && 3272 permName.charAt(bp.name.length()) == '.') { 3273 return bp; 3274 } 3275 } 3276 return null; 3277 } 3278 3279 private BasePermission checkPermissionTreeLP(String permName) { 3280 if (permName != null) { 3281 BasePermission bp = findPermissionTreeLP(permName); 3282 if (bp != null) { 3283 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3284 return bp; 3285 } 3286 throw new SecurityException("Calling uid " 3287 + Binder.getCallingUid() 3288 + " is not allowed to add to permission tree " 3289 + bp.name + " owned by uid " + bp.uid); 3290 } 3291 } 3292 throw new SecurityException("No permission tree found for " + permName); 3293 } 3294 3295 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3296 if (s1 == null) { 3297 return s2 == null; 3298 } 3299 if (s2 == null) { 3300 return false; 3301 } 3302 if (s1.getClass() != s2.getClass()) { 3303 return false; 3304 } 3305 return s1.equals(s2); 3306 } 3307 3308 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3309 if (pi1.icon != pi2.icon) return false; 3310 if (pi1.logo != pi2.logo) return false; 3311 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3312 if (!compareStrings(pi1.name, pi2.name)) return false; 3313 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3314 // We'll take care of setting this one. 3315 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3316 // These are not currently stored in settings. 3317 //if (!compareStrings(pi1.group, pi2.group)) return false; 3318 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3319 //if (pi1.labelRes != pi2.labelRes) return false; 3320 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3321 return true; 3322 } 3323 3324 int permissionInfoFootprint(PermissionInfo info) { 3325 int size = info.name.length(); 3326 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3327 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3328 return size; 3329 } 3330 3331 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3332 int size = 0; 3333 for (BasePermission perm : mSettings.mPermissions.values()) { 3334 if (perm.uid == tree.uid) { 3335 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3336 } 3337 } 3338 return size; 3339 } 3340 3341 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3342 // We calculate the max size of permissions defined by this uid and throw 3343 // if that plus the size of 'info' would exceed our stated maximum. 3344 if (tree.uid != Process.SYSTEM_UID) { 3345 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3346 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3347 throw new SecurityException("Permission tree size cap exceeded"); 3348 } 3349 } 3350 } 3351 3352 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3353 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3354 throw new SecurityException("Label must be specified in permission"); 3355 } 3356 BasePermission tree = checkPermissionTreeLP(info.name); 3357 BasePermission bp = mSettings.mPermissions.get(info.name); 3358 boolean added = bp == null; 3359 boolean changed = true; 3360 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3361 if (added) { 3362 enforcePermissionCapLocked(info, tree); 3363 bp = new BasePermission(info.name, tree.sourcePackage, 3364 BasePermission.TYPE_DYNAMIC); 3365 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3366 throw new SecurityException( 3367 "Not allowed to modify non-dynamic permission " 3368 + info.name); 3369 } else { 3370 if (bp.protectionLevel == fixedLevel 3371 && bp.perm.owner.equals(tree.perm.owner) 3372 && bp.uid == tree.uid 3373 && comparePermissionInfos(bp.perm.info, info)) { 3374 changed = false; 3375 } 3376 } 3377 bp.protectionLevel = fixedLevel; 3378 info = new PermissionInfo(info); 3379 info.protectionLevel = fixedLevel; 3380 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3381 bp.perm.info.packageName = tree.perm.info.packageName; 3382 bp.uid = tree.uid; 3383 if (added) { 3384 mSettings.mPermissions.put(info.name, bp); 3385 } 3386 if (changed) { 3387 if (!async) { 3388 mSettings.writeLPr(); 3389 } else { 3390 scheduleWriteSettingsLocked(); 3391 } 3392 } 3393 return added; 3394 } 3395 3396 @Override 3397 public boolean addPermission(PermissionInfo info) { 3398 synchronized (mPackages) { 3399 return addPermissionLocked(info, false); 3400 } 3401 } 3402 3403 @Override 3404 public boolean addPermissionAsync(PermissionInfo info) { 3405 synchronized (mPackages) { 3406 return addPermissionLocked(info, true); 3407 } 3408 } 3409 3410 @Override 3411 public void removePermission(String name) { 3412 synchronized (mPackages) { 3413 checkPermissionTreeLP(name); 3414 BasePermission bp = mSettings.mPermissions.get(name); 3415 if (bp != null) { 3416 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3417 throw new SecurityException( 3418 "Not allowed to modify non-dynamic permission " 3419 + name); 3420 } 3421 mSettings.mPermissions.remove(name); 3422 mSettings.writeLPr(); 3423 } 3424 } 3425 } 3426 3427 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3428 BasePermission bp) { 3429 int index = pkg.requestedPermissions.indexOf(bp.name); 3430 if (index == -1) { 3431 throw new SecurityException("Package " + pkg.packageName 3432 + " has not requested permission " + bp.name); 3433 } 3434 if (!bp.isRuntime()) { 3435 throw new SecurityException("Permission " + bp.name 3436 + " is not a changeable permission type"); 3437 } 3438 } 3439 3440 @Override 3441 public void grantRuntimePermission(String packageName, String name, final int userId) { 3442 if (!sUserManager.exists(userId)) { 3443 Log.e(TAG, "No such user:" + userId); 3444 return; 3445 } 3446 3447 mContext.enforceCallingOrSelfPermission( 3448 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3449 "grantRuntimePermission"); 3450 3451 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3452 "grantRuntimePermission"); 3453 3454 final int uid; 3455 final SettingBase sb; 3456 3457 synchronized (mPackages) { 3458 final PackageParser.Package pkg = mPackages.get(packageName); 3459 if (pkg == null) { 3460 throw new IllegalArgumentException("Unknown package: " + packageName); 3461 } 3462 3463 final BasePermission bp = mSettings.mPermissions.get(name); 3464 if (bp == null) { 3465 throw new IllegalArgumentException("Unknown permission: " + name); 3466 } 3467 3468 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3469 3470 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3471 sb = (SettingBase) pkg.mExtras; 3472 if (sb == null) { 3473 throw new IllegalArgumentException("Unknown package: " + packageName); 3474 } 3475 3476 final PermissionsState permissionsState = sb.getPermissionsState(); 3477 3478 final int flags = permissionsState.getPermissionFlags(name, userId); 3479 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3480 throw new SecurityException("Cannot grant system fixed permission: " 3481 + name + " for package: " + packageName); 3482 } 3483 3484 final int result = permissionsState.grantRuntimePermission(bp, userId); 3485 switch (result) { 3486 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3487 return; 3488 } 3489 3490 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3491 mHandler.post(new Runnable() { 3492 @Override 3493 public void run() { 3494 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3495 } 3496 }); 3497 } break; 3498 } 3499 3500 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3501 3502 // Not critical if that is lost - app has to request again. 3503 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3504 } 3505 3506 // Only need to do this if user is initialized. Otherwise it's a new user 3507 // and there are no processes running as the user yet and there's no need 3508 // to make an expensive call to remount processes for the changed permissions. 3509 if (READ_EXTERNAL_STORAGE.equals(name) 3510 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3511 final long token = Binder.clearCallingIdentity(); 3512 try { 3513 if (sUserManager.isInitialized(userId)) { 3514 MountServiceInternal mountServiceInternal = LocalServices.getService( 3515 MountServiceInternal.class); 3516 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3517 } 3518 } finally { 3519 Binder.restoreCallingIdentity(token); 3520 } 3521 } 3522 } 3523 3524 @Override 3525 public void revokeRuntimePermission(String packageName, String name, int userId) { 3526 if (!sUserManager.exists(userId)) { 3527 Log.e(TAG, "No such user:" + userId); 3528 return; 3529 } 3530 3531 mContext.enforceCallingOrSelfPermission( 3532 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3533 "revokeRuntimePermission"); 3534 3535 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3536 "revokeRuntimePermission"); 3537 3538 final SettingBase sb; 3539 3540 synchronized (mPackages) { 3541 final PackageParser.Package pkg = mPackages.get(packageName); 3542 if (pkg == null) { 3543 throw new IllegalArgumentException("Unknown package: " + packageName); 3544 } 3545 3546 final BasePermission bp = mSettings.mPermissions.get(name); 3547 if (bp == null) { 3548 throw new IllegalArgumentException("Unknown permission: " + name); 3549 } 3550 3551 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3552 3553 sb = (SettingBase) pkg.mExtras; 3554 if (sb == null) { 3555 throw new IllegalArgumentException("Unknown package: " + packageName); 3556 } 3557 3558 final PermissionsState permissionsState = sb.getPermissionsState(); 3559 3560 final int flags = permissionsState.getPermissionFlags(name, userId); 3561 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3562 throw new SecurityException("Cannot revoke system fixed permission: " 3563 + name + " for package: " + packageName); 3564 } 3565 3566 if (permissionsState.revokeRuntimePermission(bp, userId) == 3567 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3568 return; 3569 } 3570 3571 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3572 3573 // Critical, after this call app should never have the permission. 3574 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3575 } 3576 3577 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3578 } 3579 3580 @Override 3581 public void resetRuntimePermissions() { 3582 mContext.enforceCallingOrSelfPermission( 3583 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3584 "revokeRuntimePermission"); 3585 3586 int callingUid = Binder.getCallingUid(); 3587 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3588 mContext.enforceCallingOrSelfPermission( 3589 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3590 "resetRuntimePermissions"); 3591 } 3592 3593 synchronized (mPackages) { 3594 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3595 for (int userId : UserManagerService.getInstance().getUserIds()) { 3596 final int packageCount = mPackages.size(); 3597 for (int i = 0; i < packageCount; i++) { 3598 PackageParser.Package pkg = mPackages.valueAt(i); 3599 if (!(pkg.mExtras instanceof PackageSetting)) { 3600 continue; 3601 } 3602 PackageSetting ps = (PackageSetting) pkg.mExtras; 3603 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3604 } 3605 } 3606 } 3607 } 3608 3609 @Override 3610 public int getPermissionFlags(String name, String packageName, int userId) { 3611 if (!sUserManager.exists(userId)) { 3612 return 0; 3613 } 3614 3615 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3616 3617 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3618 "getPermissionFlags"); 3619 3620 synchronized (mPackages) { 3621 final PackageParser.Package pkg = mPackages.get(packageName); 3622 if (pkg == null) { 3623 throw new IllegalArgumentException("Unknown package: " + packageName); 3624 } 3625 3626 final BasePermission bp = mSettings.mPermissions.get(name); 3627 if (bp == null) { 3628 throw new IllegalArgumentException("Unknown permission: " + name); 3629 } 3630 3631 SettingBase sb = (SettingBase) pkg.mExtras; 3632 if (sb == null) { 3633 throw new IllegalArgumentException("Unknown package: " + packageName); 3634 } 3635 3636 PermissionsState permissionsState = sb.getPermissionsState(); 3637 return permissionsState.getPermissionFlags(name, userId); 3638 } 3639 } 3640 3641 @Override 3642 public void updatePermissionFlags(String name, String packageName, int flagMask, 3643 int flagValues, int userId) { 3644 if (!sUserManager.exists(userId)) { 3645 return; 3646 } 3647 3648 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3649 3650 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3651 "updatePermissionFlags"); 3652 3653 // Only the system can change these flags and nothing else. 3654 if (getCallingUid() != Process.SYSTEM_UID) { 3655 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3656 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3657 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3658 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3659 } 3660 3661 synchronized (mPackages) { 3662 final PackageParser.Package pkg = mPackages.get(packageName); 3663 if (pkg == null) { 3664 throw new IllegalArgumentException("Unknown package: " + packageName); 3665 } 3666 3667 final BasePermission bp = mSettings.mPermissions.get(name); 3668 if (bp == null) { 3669 throw new IllegalArgumentException("Unknown permission: " + name); 3670 } 3671 3672 SettingBase sb = (SettingBase) pkg.mExtras; 3673 if (sb == null) { 3674 throw new IllegalArgumentException("Unknown package: " + packageName); 3675 } 3676 3677 PermissionsState permissionsState = sb.getPermissionsState(); 3678 3679 // Only the package manager can change flags for system component permissions. 3680 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3681 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3682 return; 3683 } 3684 3685 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3686 3687 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3688 // Install and runtime permissions are stored in different places, 3689 // so figure out what permission changed and persist the change. 3690 if (permissionsState.getInstallPermissionState(name) != null) { 3691 scheduleWriteSettingsLocked(); 3692 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3693 || hadState) { 3694 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3695 } 3696 } 3697 } 3698 } 3699 3700 /** 3701 * Update the permission flags for all packages and runtime permissions of a user in order 3702 * to allow device or profile owner to remove POLICY_FIXED. 3703 */ 3704 @Override 3705 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3706 if (!sUserManager.exists(userId)) { 3707 return; 3708 } 3709 3710 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3711 3712 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3713 "updatePermissionFlagsForAllApps"); 3714 3715 // Only the system can change system fixed flags. 3716 if (getCallingUid() != Process.SYSTEM_UID) { 3717 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3718 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3719 } 3720 3721 synchronized (mPackages) { 3722 boolean changed = false; 3723 final int packageCount = mPackages.size(); 3724 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3725 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3726 SettingBase sb = (SettingBase) pkg.mExtras; 3727 if (sb == null) { 3728 continue; 3729 } 3730 PermissionsState permissionsState = sb.getPermissionsState(); 3731 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3732 userId, flagMask, flagValues); 3733 } 3734 if (changed) { 3735 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3736 } 3737 } 3738 } 3739 3740 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3741 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3742 != PackageManager.PERMISSION_GRANTED 3743 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3744 != PackageManager.PERMISSION_GRANTED) { 3745 throw new SecurityException(message + " requires " 3746 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3747 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3748 } 3749 } 3750 3751 @Override 3752 public boolean shouldShowRequestPermissionRationale(String permissionName, 3753 String packageName, int userId) { 3754 if (UserHandle.getCallingUserId() != userId) { 3755 mContext.enforceCallingPermission( 3756 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3757 "canShowRequestPermissionRationale for user " + userId); 3758 } 3759 3760 final int uid = getPackageUid(packageName, userId); 3761 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3762 return false; 3763 } 3764 3765 if (checkPermission(permissionName, packageName, userId) 3766 == PackageManager.PERMISSION_GRANTED) { 3767 return false; 3768 } 3769 3770 final int flags; 3771 3772 final long identity = Binder.clearCallingIdentity(); 3773 try { 3774 flags = getPermissionFlags(permissionName, 3775 packageName, userId); 3776 } finally { 3777 Binder.restoreCallingIdentity(identity); 3778 } 3779 3780 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3781 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3782 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3783 3784 if ((flags & fixedFlags) != 0) { 3785 return false; 3786 } 3787 3788 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3789 } 3790 3791 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3792 BasePermission bp = mSettings.mPermissions.get(permission); 3793 if (bp == null) { 3794 throw new SecurityException("Missing " + permission + " permission"); 3795 } 3796 3797 SettingBase sb = (SettingBase) pkg.mExtras; 3798 PermissionsState permissionsState = sb.getPermissionsState(); 3799 3800 if (permissionsState.grantInstallPermission(bp) != 3801 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3802 scheduleWriteSettingsLocked(); 3803 } 3804 } 3805 3806 @Override 3807 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3808 mContext.enforceCallingOrSelfPermission( 3809 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3810 "addOnPermissionsChangeListener"); 3811 3812 synchronized (mPackages) { 3813 mOnPermissionChangeListeners.addListenerLocked(listener); 3814 } 3815 } 3816 3817 @Override 3818 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3819 synchronized (mPackages) { 3820 mOnPermissionChangeListeners.removeListenerLocked(listener); 3821 } 3822 } 3823 3824 @Override 3825 public boolean isProtectedBroadcast(String actionName) { 3826 synchronized (mPackages) { 3827 return mProtectedBroadcasts.contains(actionName); 3828 } 3829 } 3830 3831 @Override 3832 public int checkSignatures(String pkg1, String pkg2) { 3833 synchronized (mPackages) { 3834 final PackageParser.Package p1 = mPackages.get(pkg1); 3835 final PackageParser.Package p2 = mPackages.get(pkg2); 3836 if (p1 == null || p1.mExtras == null 3837 || p2 == null || p2.mExtras == null) { 3838 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3839 } 3840 return compareSignatures(p1.mSignatures, p2.mSignatures); 3841 } 3842 } 3843 3844 @Override 3845 public int checkUidSignatures(int uid1, int uid2) { 3846 // Map to base uids. 3847 uid1 = UserHandle.getAppId(uid1); 3848 uid2 = UserHandle.getAppId(uid2); 3849 // reader 3850 synchronized (mPackages) { 3851 Signature[] s1; 3852 Signature[] s2; 3853 Object obj = mSettings.getUserIdLPr(uid1); 3854 if (obj != null) { 3855 if (obj instanceof SharedUserSetting) { 3856 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3857 } else if (obj instanceof PackageSetting) { 3858 s1 = ((PackageSetting)obj).signatures.mSignatures; 3859 } else { 3860 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3861 } 3862 } else { 3863 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3864 } 3865 obj = mSettings.getUserIdLPr(uid2); 3866 if (obj != null) { 3867 if (obj instanceof SharedUserSetting) { 3868 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3869 } else if (obj instanceof PackageSetting) { 3870 s2 = ((PackageSetting)obj).signatures.mSignatures; 3871 } else { 3872 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3873 } 3874 } else { 3875 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3876 } 3877 return compareSignatures(s1, s2); 3878 } 3879 } 3880 3881 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3882 final long identity = Binder.clearCallingIdentity(); 3883 try { 3884 if (sb instanceof SharedUserSetting) { 3885 SharedUserSetting sus = (SharedUserSetting) sb; 3886 final int packageCount = sus.packages.size(); 3887 for (int i = 0; i < packageCount; i++) { 3888 PackageSetting susPs = sus.packages.valueAt(i); 3889 if (userId == UserHandle.USER_ALL) { 3890 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3891 } else { 3892 final int uid = UserHandle.getUid(userId, susPs.appId); 3893 killUid(uid, reason); 3894 } 3895 } 3896 } else if (sb instanceof PackageSetting) { 3897 PackageSetting ps = (PackageSetting) sb; 3898 if (userId == UserHandle.USER_ALL) { 3899 killApplication(ps.pkg.packageName, ps.appId, reason); 3900 } else { 3901 final int uid = UserHandle.getUid(userId, ps.appId); 3902 killUid(uid, reason); 3903 } 3904 } 3905 } finally { 3906 Binder.restoreCallingIdentity(identity); 3907 } 3908 } 3909 3910 private static void killUid(int uid, String reason) { 3911 IActivityManager am = ActivityManagerNative.getDefault(); 3912 if (am != null) { 3913 try { 3914 am.killUid(uid, reason); 3915 } catch (RemoteException e) { 3916 /* ignore - same process */ 3917 } 3918 } 3919 } 3920 3921 /** 3922 * Compares two sets of signatures. Returns: 3923 * <br /> 3924 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3925 * <br /> 3926 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3927 * <br /> 3928 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3929 * <br /> 3930 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3931 * <br /> 3932 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3933 */ 3934 static int compareSignatures(Signature[] s1, Signature[] s2) { 3935 if (s1 == null) { 3936 return s2 == null 3937 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3938 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3939 } 3940 3941 if (s2 == null) { 3942 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3943 } 3944 3945 if (s1.length != s2.length) { 3946 return PackageManager.SIGNATURE_NO_MATCH; 3947 } 3948 3949 // Since both signature sets are of size 1, we can compare without HashSets. 3950 if (s1.length == 1) { 3951 return s1[0].equals(s2[0]) ? 3952 PackageManager.SIGNATURE_MATCH : 3953 PackageManager.SIGNATURE_NO_MATCH; 3954 } 3955 3956 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3957 for (Signature sig : s1) { 3958 set1.add(sig); 3959 } 3960 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3961 for (Signature sig : s2) { 3962 set2.add(sig); 3963 } 3964 // Make sure s2 contains all signatures in s1. 3965 if (set1.equals(set2)) { 3966 return PackageManager.SIGNATURE_MATCH; 3967 } 3968 return PackageManager.SIGNATURE_NO_MATCH; 3969 } 3970 3971 /** 3972 * If the database version for this type of package (internal storage or 3973 * external storage) is less than the version where package signatures 3974 * were updated, return true. 3975 */ 3976 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3977 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3978 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3979 } 3980 3981 /** 3982 * Used for backward compatibility to make sure any packages with 3983 * certificate chains get upgraded to the new style. {@code existingSigs} 3984 * will be in the old format (since they were stored on disk from before the 3985 * system upgrade) and {@code scannedSigs} will be in the newer format. 3986 */ 3987 private int compareSignaturesCompat(PackageSignatures existingSigs, 3988 PackageParser.Package scannedPkg) { 3989 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3990 return PackageManager.SIGNATURE_NO_MATCH; 3991 } 3992 3993 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3994 for (Signature sig : existingSigs.mSignatures) { 3995 existingSet.add(sig); 3996 } 3997 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3998 for (Signature sig : scannedPkg.mSignatures) { 3999 try { 4000 Signature[] chainSignatures = sig.getChainSignatures(); 4001 for (Signature chainSig : chainSignatures) { 4002 scannedCompatSet.add(chainSig); 4003 } 4004 } catch (CertificateEncodingException e) { 4005 scannedCompatSet.add(sig); 4006 } 4007 } 4008 /* 4009 * Make sure the expanded scanned set contains all signatures in the 4010 * existing one. 4011 */ 4012 if (scannedCompatSet.equals(existingSet)) { 4013 // Migrate the old signatures to the new scheme. 4014 existingSigs.assignSignatures(scannedPkg.mSignatures); 4015 // The new KeySets will be re-added later in the scanning process. 4016 synchronized (mPackages) { 4017 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4018 } 4019 return PackageManager.SIGNATURE_MATCH; 4020 } 4021 return PackageManager.SIGNATURE_NO_MATCH; 4022 } 4023 4024 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4025 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4026 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4027 } 4028 4029 private int compareSignaturesRecover(PackageSignatures existingSigs, 4030 PackageParser.Package scannedPkg) { 4031 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4032 return PackageManager.SIGNATURE_NO_MATCH; 4033 } 4034 4035 String msg = null; 4036 try { 4037 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4038 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4039 + scannedPkg.packageName); 4040 return PackageManager.SIGNATURE_MATCH; 4041 } 4042 } catch (CertificateException e) { 4043 msg = e.getMessage(); 4044 } 4045 4046 logCriticalInfo(Log.INFO, 4047 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4048 return PackageManager.SIGNATURE_NO_MATCH; 4049 } 4050 4051 @Override 4052 public String[] getPackagesForUid(int uid) { 4053 uid = UserHandle.getAppId(uid); 4054 // reader 4055 synchronized (mPackages) { 4056 Object obj = mSettings.getUserIdLPr(uid); 4057 if (obj instanceof SharedUserSetting) { 4058 final SharedUserSetting sus = (SharedUserSetting) obj; 4059 final int N = sus.packages.size(); 4060 final String[] res = new String[N]; 4061 final Iterator<PackageSetting> it = sus.packages.iterator(); 4062 int i = 0; 4063 while (it.hasNext()) { 4064 res[i++] = it.next().name; 4065 } 4066 return res; 4067 } else if (obj instanceof PackageSetting) { 4068 final PackageSetting ps = (PackageSetting) obj; 4069 return new String[] { ps.name }; 4070 } 4071 } 4072 return null; 4073 } 4074 4075 @Override 4076 public String getNameForUid(int uid) { 4077 // reader 4078 synchronized (mPackages) { 4079 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4080 if (obj instanceof SharedUserSetting) { 4081 final SharedUserSetting sus = (SharedUserSetting) obj; 4082 return sus.name + ":" + sus.userId; 4083 } else if (obj instanceof PackageSetting) { 4084 final PackageSetting ps = (PackageSetting) obj; 4085 return ps.name; 4086 } 4087 } 4088 return null; 4089 } 4090 4091 @Override 4092 public int getUidForSharedUser(String sharedUserName) { 4093 if(sharedUserName == null) { 4094 return -1; 4095 } 4096 // reader 4097 synchronized (mPackages) { 4098 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4099 if (suid == null) { 4100 return -1; 4101 } 4102 return suid.userId; 4103 } 4104 } 4105 4106 @Override 4107 public int getFlagsForUid(int uid) { 4108 synchronized (mPackages) { 4109 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4110 if (obj instanceof SharedUserSetting) { 4111 final SharedUserSetting sus = (SharedUserSetting) obj; 4112 return sus.pkgFlags; 4113 } else if (obj instanceof PackageSetting) { 4114 final PackageSetting ps = (PackageSetting) obj; 4115 return ps.pkgFlags; 4116 } 4117 } 4118 return 0; 4119 } 4120 4121 @Override 4122 public int getPrivateFlagsForUid(int uid) { 4123 synchronized (mPackages) { 4124 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4125 if (obj instanceof SharedUserSetting) { 4126 final SharedUserSetting sus = (SharedUserSetting) obj; 4127 return sus.pkgPrivateFlags; 4128 } else if (obj instanceof PackageSetting) { 4129 final PackageSetting ps = (PackageSetting) obj; 4130 return ps.pkgPrivateFlags; 4131 } 4132 } 4133 return 0; 4134 } 4135 4136 @Override 4137 public boolean isUidPrivileged(int uid) { 4138 uid = UserHandle.getAppId(uid); 4139 // reader 4140 synchronized (mPackages) { 4141 Object obj = mSettings.getUserIdLPr(uid); 4142 if (obj instanceof SharedUserSetting) { 4143 final SharedUserSetting sus = (SharedUserSetting) obj; 4144 final Iterator<PackageSetting> it = sus.packages.iterator(); 4145 while (it.hasNext()) { 4146 if (it.next().isPrivileged()) { 4147 return true; 4148 } 4149 } 4150 } else if (obj instanceof PackageSetting) { 4151 final PackageSetting ps = (PackageSetting) obj; 4152 return ps.isPrivileged(); 4153 } 4154 } 4155 return false; 4156 } 4157 4158 @Override 4159 public String[] getAppOpPermissionPackages(String permissionName) { 4160 synchronized (mPackages) { 4161 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4162 if (pkgs == null) { 4163 return null; 4164 } 4165 return pkgs.toArray(new String[pkgs.size()]); 4166 } 4167 } 4168 4169 @Override 4170 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4171 int flags, int userId) { 4172 if (!sUserManager.exists(userId)) return null; 4173 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4174 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4175 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4176 } 4177 4178 @Override 4179 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4180 IntentFilter filter, int match, ComponentName activity) { 4181 final int userId = UserHandle.getCallingUserId(); 4182 if (DEBUG_PREFERRED) { 4183 Log.v(TAG, "setLastChosenActivity intent=" + intent 4184 + " resolvedType=" + resolvedType 4185 + " flags=" + flags 4186 + " filter=" + filter 4187 + " match=" + match 4188 + " activity=" + activity); 4189 filter.dump(new PrintStreamPrinter(System.out), " "); 4190 } 4191 intent.setComponent(null); 4192 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4193 // Find any earlier preferred or last chosen entries and nuke them 4194 findPreferredActivity(intent, resolvedType, 4195 flags, query, 0, false, true, false, userId); 4196 // Add the new activity as the last chosen for this filter 4197 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4198 "Setting last chosen"); 4199 } 4200 4201 @Override 4202 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4203 final int userId = UserHandle.getCallingUserId(); 4204 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4205 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4206 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4207 false, false, false, userId); 4208 } 4209 4210 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4211 int flags, List<ResolveInfo> query, int userId) { 4212 if (query != null) { 4213 final int N = query.size(); 4214 if (N == 1) { 4215 return query.get(0); 4216 } else if (N > 1) { 4217 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4218 // If there is more than one activity with the same priority, 4219 // then let the user decide between them. 4220 ResolveInfo r0 = query.get(0); 4221 ResolveInfo r1 = query.get(1); 4222 if (DEBUG_INTENT_MATCHING || debug) { 4223 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4224 + r1.activityInfo.name + "=" + r1.priority); 4225 } 4226 // If the first activity has a higher priority, or a different 4227 // default, then it is always desireable to pick it. 4228 if (r0.priority != r1.priority 4229 || r0.preferredOrder != r1.preferredOrder 4230 || r0.isDefault != r1.isDefault) { 4231 return query.get(0); 4232 } 4233 // If we have saved a preference for a preferred activity for 4234 // this Intent, use that. 4235 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4236 flags, query, r0.priority, true, false, debug, userId); 4237 if (ri != null) { 4238 return ri; 4239 } 4240 if (userId != 0) { 4241 ri = new ResolveInfo(mResolveInfo); 4242 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4243 ri.activityInfo.applicationInfo = new ApplicationInfo( 4244 ri.activityInfo.applicationInfo); 4245 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4246 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4247 return ri; 4248 } 4249 return mResolveInfo; 4250 } 4251 } 4252 return null; 4253 } 4254 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 4259 .get(userId); 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) 4265 : null; 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), " "); 4275 } 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:"); 4280 if (ai != null) { 4281 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4282 } else { 4283 Slog.v(TAG, " null"); 4284 } 4285 } 4286 if (ai == null) { 4287 // This previously registered persistent preferred activity 4288 // component is no longer known. Ignore it and do NOT remove it. 4289 continue; 4290 } 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)) { 4295 continue; 4296 } 4297 if (!ri.activityInfo.name.equals(ai.name)) { 4298 continue; 4299 } 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); 4304 } 4305 return ri; 4306 } 4307 } 4308 } 4309 return null; 4310 } 4311 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; 4316 // writer 4317 synchronized (mPackages) { 4318 if (intent.getSelector() != null) { 4319 intent = intent.getSelector(); 4320 } 4321 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4322 4323 // Try to find a matching persistent preferred activity. 4324 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4325 debug, userId); 4326 4327 // If a persistent preferred activity matched, use it. 4328 if (pri != null) { 4329 return pri; 4330 } 4331 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) 4338 : null; 4339 if (prefs != null && prefs.size() > 0) { 4340 boolean changed = false; 4341 try { 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. 4345 int match = 0; 4346 4347 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4348 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) { 4355 match = ri.match; 4356 } 4357 } 4358 4359 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4360 + Integer.toHexString(match)); 4361 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), " "); 4371 } 4372 if (pa.mPref.mMatch != match) { 4373 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4374 + Integer.toHexString(pa.mPref.mMatch)); 4375 continue; 4376 } 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"); 4381 continue; 4382 } 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:"); 4387 if (ai != null) { 4388 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4389 } else { 4390 Slog.v(TAG, " null"); 4391 } 4392 } 4393 if (ai == 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); 4402 changed = true; 4403 continue; 4404 } 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)) { 4409 continue; 4410 } 4411 if (!ri.activityInfo.name.equals(ai.name)) { 4412 continue; 4413 } 4414 4415 if (removeMatches) { 4416 pir.removeFilter(pa); 4417 changed = true; 4418 if (DEBUG_PREFERRED) { 4419 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4420 } 4421 break; 4422 } 4423 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); 4434 } 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); 4440 changed = true; 4441 return null; 4442 } 4443 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); 4447 return ri; 4448 } 4449 } 4450 } finally { 4451 if (changed) { 4452 if (DEBUG_PREFERRED) { 4453 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4454 } 4455 scheduleWritePackageRestrictionsLocked(userId); 4456 } 4457 } 4458 } 4459 } 4460 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4461 return null; 4462 } 4463 4464 /* 4465 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4466 */ 4467 @Override 4468 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4469 int targetUserId) { 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; 4478 } 4479 } 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; 4487 } 4488 } 4489 return false; 4490 } 4491 4492 private UserInfo getProfileParent(int userId) { 4493 final long identity = Binder.clearCallingIdentity(); 4494 try { 4495 return sUserManager.getProfileParent(userId); 4496 } finally { 4497 Binder.restoreCallingIdentity(identity); 4498 } 4499 } 4500 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); 4506 } 4507 return null; 4508 } 4509 4510 @Override 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(); 4516 if (comp == null) { 4517 if (intent.getSelector() != null) { 4518 intent = intent.getSelector(); 4519 comp = intent.getComponent(); 4520 } 4521 } 4522 4523 if (comp != null) { 4524 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4525 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4526 if (ai != null) { 4527 final ResolveInfo ri = new ResolveInfo(); 4528 ri.activityInfo = ai; 4529 list.add(ri); 4530 } 4531 return list; 4532 } 4533 4534 // reader 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); 4547 } 4548 4549 // Check for results in the current profile. 4550 List<ResolveInfo> result = mActivities.queryIntent( 4551 intent, resolvedType, flags, userId); 4552 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); 4559 } 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); 4567 } 4568 if (xpDomainInfo != null) { 4569 if (xpResolveInfo != null) { 4570 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4571 // in the result. 4572 result.remove(xpResolveInfo); 4573 } 4574 if (result.size() == 0) { 4575 result.add(xpDomainInfo.resolveInfo); 4576 return result; 4577 } 4578 } else if (result.size() <= 1) { 4579 return result; 4580 } 4581 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4582 xpDomainInfo, userId); 4583 Collections.sort(result, mResolvePrioritySorter); 4584 } 4585 return result; 4586 } 4587 final PackageParser.Package pkg = mPackages.get(pkgName); 4588 if (pkg != null) { 4589 return filterIfNotPrimaryUser( 4590 mActivities.queryIntentForPackage( 4591 intent, resolvedType, flags, pkg.activities, userId), 4592 userId); 4593 } 4594 return new ArrayList<ResolveInfo>(); 4595 } 4596 } 4597 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; 4603 } 4604 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, 4608 sourceUserId)) { 4609 return null; 4610 } 4611 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4612 resolvedType, flags, parentUserId); 4613 4614 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4615 return null; 4616 } 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) { 4624 continue; 4625 } 4626 String packageName = riTargetUser.activityInfo.packageName; 4627 PackageSetting ps = mSettings.mPackages.get(packageName); 4628 if (ps == null) { 4629 continue; 4630 } 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(null, sourceUserId, parentUserId); 4637 result.bestDomainVerificationStatus = status; 4638 } else { 4639 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4640 result.bestDomainVerificationStatus); 4641 } 4642 } 4643 // Don't consider matches with status NEVER across profiles. 4644 if (result != null && result.bestDomainVerificationStatus 4645 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4646 return null; 4647 } 4648 return result; 4649 } 4650 4651 /** 4652 * Verification statuses are ordered from the worse to the best, except for 4653 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4654 */ 4655 private int bestDomainVerificationStatus(int status1, int status2) { 4656 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4657 return status2; 4658 } 4659 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4660 return status1; 4661 } 4662 return (int) MathUtils.max(status1, status2); 4663 } 4664 4665 private boolean isUserEnabled(int userId) { 4666 long callingId = Binder.clearCallingIdentity(); 4667 try { 4668 UserInfo userInfo = sUserManager.getUserInfo(userId); 4669 return userInfo != null && userInfo.isEnabled(); 4670 } finally { 4671 Binder.restoreCallingIdentity(callingId); 4672 } 4673 } 4674 4675 /** 4676 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4677 * 4678 * @return filtered list 4679 */ 4680 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4681 if (userId == UserHandle.USER_OWNER) { 4682 return resolveInfos; 4683 } 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); 4688 } 4689 } 4690 return resolveInfos; 4691 } 4692 4693 private static boolean hasWebURI(Intent intent) { 4694 if (intent.getData() == null) { 4695 return false; 4696 } 4697 final String scheme = intent.getScheme(); 4698 if (TextUtils.isEmpty(scheme)) { 4699 return false; 4700 } 4701 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4702 } 4703 4704 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4705 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4706 int userId) { 4707 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4708 4709 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4710 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4711 candidates.size()); 4712 } 4713 4714 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4715 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4716 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4717 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4718 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4719 4720 synchronized (mPackages) { 4721 final int count = candidates.size(); 4722 // First, try to use linked apps. Partition the candidates into four lists: 4723 // one for the final results, one for the "do not use ever", one for "undefined status" 4724 // and finally one for "browser app type". 4725 for (int n=0; n<count; n++) { 4726 ResolveInfo info = candidates.get(n); 4727 String packageName = info.activityInfo.packageName; 4728 PackageSetting ps = mSettings.mPackages.get(packageName); 4729 if (ps != null) { 4730 // Add to the special match all list (Browser use case) 4731 if (info.handleAllWebDataURI) { 4732 matchAllList.add(info); 4733 continue; 4734 } 4735 // Try to get the status from User settings first 4736 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4737 int status = (int)(packedStatus >> 32); 4738 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4739 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4740 if (DEBUG_DOMAIN_VERIFICATION) { 4741 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4742 + " : linkgen=" + linkGeneration); 4743 } 4744 // Use link-enabled generation as preferredOrder, i.e. 4745 // prefer newly-enabled over earlier-enabled. 4746 info.preferredOrder = linkGeneration; 4747 alwaysList.add(info); 4748 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4749 if (DEBUG_DOMAIN_VERIFICATION) { 4750 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4751 } 4752 neverList.add(info); 4753 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4754 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4755 if (DEBUG_DOMAIN_VERIFICATION) { 4756 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4757 } 4758 undefinedList.add(info); 4759 } 4760 } 4761 } 4762 // First try to add the "always" resolution(s) for the current user, if any 4763 if (alwaysList.size() > 0) { 4764 result.addAll(alwaysList); 4765 // if there is an "always" for the parent user, add it. 4766 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4767 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4768 result.add(xpDomainInfo.resolveInfo); 4769 } else { 4770 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4771 result.addAll(undefinedList); 4772 if (xpDomainInfo != null && ( 4773 xpDomainInfo.bestDomainVerificationStatus 4774 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4775 || xpDomainInfo.bestDomainVerificationStatus 4776 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4777 result.add(xpDomainInfo.resolveInfo); 4778 } 4779 // Also add Browsers (all of them or only the default one) 4780 if ((matchFlags & MATCH_ALL) != 0) { 4781 result.addAll(matchAllList); 4782 } else { 4783 // Browser/generic handling case. If there's a default browser, go straight 4784 // to that (but only if there is no other higher-priority match). 4785 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4786 int maxMatchPrio = 0; 4787 ResolveInfo defaultBrowserMatch = null; 4788 final int numCandidates = matchAllList.size(); 4789 for (int n = 0; n < numCandidates; n++) { 4790 ResolveInfo info = matchAllList.get(n); 4791 // track the highest overall match priority... 4792 if (info.priority > maxMatchPrio) { 4793 maxMatchPrio = info.priority; 4794 } 4795 // ...and the highest-priority default browser match 4796 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4797 if (defaultBrowserMatch == null 4798 || (defaultBrowserMatch.priority < info.priority)) { 4799 if (debug) { 4800 Slog.v(TAG, "Considering default browser match " + info); 4801 } 4802 defaultBrowserMatch = info; 4803 } 4804 } 4805 } 4806 if (defaultBrowserMatch != null 4807 && defaultBrowserMatch.priority >= maxMatchPrio 4808 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4809 { 4810 if (debug) { 4811 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4812 } 4813 result.add(defaultBrowserMatch); 4814 } else { 4815 result.addAll(matchAllList); 4816 } 4817 } 4818 4819 // If there is nothing selected, add all candidates and remove the ones that the user 4820 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4821 if (result.size() == 0) { 4822 result.addAll(candidates); 4823 result.removeAll(neverList); 4824 } 4825 } 4826 } 4827 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4828 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4829 result.size()); 4830 for (ResolveInfo info : result) { 4831 Slog.v(TAG, " + " + info.activityInfo); 4832 } 4833 } 4834 return result; 4835 } 4836 4837 // Returns a packed value as a long: 4838 // 4839 // high 'int'-sized word: link status: undefined/ask/never/always. 4840 // low 'int'-sized word: relative priority among 'always' results. 4841 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4842 long result = ps.getDomainVerificationStatusForUser(userId); 4843 // if none available, get the master status 4844 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4845 if (ps.getIntentFilterVerificationInfo() != null) { 4846 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4847 } 4848 } 4849 return result; 4850 } 4851 4852 private ResolveInfo querySkipCurrentProfileIntents( 4853 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4854 int flags, int sourceUserId) { 4855 if (matchingFilters != null) { 4856 int size = matchingFilters.size(); 4857 for (int i = 0; i < size; i ++) { 4858 CrossProfileIntentFilter filter = matchingFilters.get(i); 4859 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4860 // Checking if there are activities in the target user that can handle the 4861 // intent. 4862 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4863 flags, sourceUserId); 4864 if (resolveInfo != null) { 4865 return resolveInfo; 4866 } 4867 } 4868 } 4869 } 4870 return null; 4871 } 4872 4873 // Return matching ResolveInfo if any for skip current profile intent filters. 4874 private ResolveInfo queryCrossProfileIntents( 4875 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4876 int flags, int sourceUserId) { 4877 if (matchingFilters != null) { 4878 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4879 // match the same intent. For performance reasons, it is better not to 4880 // run queryIntent twice for the same userId 4881 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4882 int size = matchingFilters.size(); 4883 for (int i = 0; i < size; i++) { 4884 CrossProfileIntentFilter filter = matchingFilters.get(i); 4885 int targetUserId = filter.getTargetUserId(); 4886 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4887 && !alreadyTriedUserIds.get(targetUserId)) { 4888 // Checking if there are activities in the target user that can handle the 4889 // intent. 4890 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4891 flags, sourceUserId); 4892 if (resolveInfo != null) return resolveInfo; 4893 alreadyTriedUserIds.put(targetUserId, true); 4894 } 4895 } 4896 } 4897 return null; 4898 } 4899 4900 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4901 String resolvedType, int flags, int sourceUserId) { 4902 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4903 resolvedType, flags, filter.getTargetUserId()); 4904 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4905 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4906 } 4907 return null; 4908 } 4909 4910 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4911 int sourceUserId, int targetUserId) { 4912 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4913 String className; 4914 if (targetUserId == UserHandle.USER_OWNER) { 4915 className = FORWARD_INTENT_TO_USER_OWNER; 4916 } else { 4917 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4918 } 4919 ComponentName forwardingActivityComponentName = new ComponentName( 4920 mAndroidApplication.packageName, className); 4921 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4922 sourceUserId); 4923 if (targetUserId == UserHandle.USER_OWNER) { 4924 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4925 forwardingResolveInfo.noResourceId = true; 4926 } 4927 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4928 forwardingResolveInfo.priority = 0; 4929 forwardingResolveInfo.preferredOrder = 0; 4930 forwardingResolveInfo.match = 0; 4931 forwardingResolveInfo.isDefault = true; 4932 forwardingResolveInfo.filter = filter; 4933 forwardingResolveInfo.targetUserId = targetUserId; 4934 return forwardingResolveInfo; 4935 } 4936 4937 @Override 4938 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4939 Intent[] specifics, String[] specificTypes, Intent intent, 4940 String resolvedType, int flags, int userId) { 4941 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4942 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4943 false, "query intent activity options"); 4944 final String resultsAction = intent.getAction(); 4945 4946 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4947 | PackageManager.GET_RESOLVED_FILTER, userId); 4948 4949 if (DEBUG_INTENT_MATCHING) { 4950 Log.v(TAG, "Query " + intent + ": " + results); 4951 } 4952 4953 int specificsPos = 0; 4954 int N; 4955 4956 // todo: note that the algorithm used here is O(N^2). This 4957 // isn't a problem in our current environment, but if we start running 4958 // into situations where we have more than 5 or 10 matches then this 4959 // should probably be changed to something smarter... 4960 4961 // First we go through and resolve each of the specific items 4962 // that were supplied, taking care of removing any corresponding 4963 // duplicate items in the generic resolve list. 4964 if (specifics != null) { 4965 for (int i=0; i<specifics.length; i++) { 4966 final Intent sintent = specifics[i]; 4967 if (sintent == null) { 4968 continue; 4969 } 4970 4971 if (DEBUG_INTENT_MATCHING) { 4972 Log.v(TAG, "Specific #" + i + ": " + sintent); 4973 } 4974 4975 String action = sintent.getAction(); 4976 if (resultsAction != null && resultsAction.equals(action)) { 4977 // If this action was explicitly requested, then don't 4978 // remove things that have it. 4979 action = null; 4980 } 4981 4982 ResolveInfo ri = null; 4983 ActivityInfo ai = null; 4984 4985 ComponentName comp = sintent.getComponent(); 4986 if (comp == null) { 4987 ri = resolveIntent( 4988 sintent, 4989 specificTypes != null ? specificTypes[i] : null, 4990 flags, userId); 4991 if (ri == null) { 4992 continue; 4993 } 4994 if (ri == mResolveInfo) { 4995 // ACK! Must do something better with this. 4996 } 4997 ai = ri.activityInfo; 4998 comp = new ComponentName(ai.applicationInfo.packageName, 4999 ai.name); 5000 } else { 5001 ai = getActivityInfo(comp, flags, userId); 5002 if (ai == null) { 5003 continue; 5004 } 5005 } 5006 5007 // Look for any generic query activities that are duplicates 5008 // of this specific one, and remove them from the results. 5009 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5010 N = results.size(); 5011 int j; 5012 for (j=specificsPos; j<N; j++) { 5013 ResolveInfo sri = results.get(j); 5014 if ((sri.activityInfo.name.equals(comp.getClassName()) 5015 && sri.activityInfo.applicationInfo.packageName.equals( 5016 comp.getPackageName())) 5017 || (action != null && sri.filter.matchAction(action))) { 5018 results.remove(j); 5019 if (DEBUG_INTENT_MATCHING) Log.v( 5020 TAG, "Removing duplicate item from " + j 5021 + " due to specific " + specificsPos); 5022 if (ri == null) { 5023 ri = sri; 5024 } 5025 j--; 5026 N--; 5027 } 5028 } 5029 5030 // Add this specific item to its proper place. 5031 if (ri == null) { 5032 ri = new ResolveInfo(); 5033 ri.activityInfo = ai; 5034 } 5035 results.add(specificsPos, ri); 5036 ri.specificIndex = i; 5037 specificsPos++; 5038 } 5039 } 5040 5041 // Now we go through the remaining generic results and remove any 5042 // duplicate actions that are found here. 5043 N = results.size(); 5044 for (int i=specificsPos; i<N-1; i++) { 5045 final ResolveInfo rii = results.get(i); 5046 if (rii.filter == null) { 5047 continue; 5048 } 5049 5050 // Iterate over all of the actions of this result's intent 5051 // filter... typically this should be just one. 5052 final Iterator<String> it = rii.filter.actionsIterator(); 5053 if (it == null) { 5054 continue; 5055 } 5056 while (it.hasNext()) { 5057 final String action = it.next(); 5058 if (resultsAction != null && resultsAction.equals(action)) { 5059 // If this action was explicitly requested, then don't 5060 // remove things that have it. 5061 continue; 5062 } 5063 for (int j=i+1; j<N; j++) { 5064 final ResolveInfo rij = results.get(j); 5065 if (rij.filter != null && rij.filter.hasAction(action)) { 5066 results.remove(j); 5067 if (DEBUG_INTENT_MATCHING) Log.v( 5068 TAG, "Removing duplicate item from " + j 5069 + " due to action " + action + " at " + i); 5070 j--; 5071 N--; 5072 } 5073 } 5074 } 5075 5076 // If the caller didn't request filter information, drop it now 5077 // so we don't have to marshall/unmarshall it. 5078 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5079 rii.filter = null; 5080 } 5081 } 5082 5083 // Filter out the caller activity if so requested. 5084 if (caller != null) { 5085 N = results.size(); 5086 for (int i=0; i<N; i++) { 5087 ActivityInfo ainfo = results.get(i).activityInfo; 5088 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5089 && caller.getClassName().equals(ainfo.name)) { 5090 results.remove(i); 5091 break; 5092 } 5093 } 5094 } 5095 5096 // If the caller didn't request filter information, 5097 // drop them now so we don't have to 5098 // marshall/unmarshall it. 5099 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5100 N = results.size(); 5101 for (int i=0; i<N; i++) { 5102 results.get(i).filter = null; 5103 } 5104 } 5105 5106 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5107 return results; 5108 } 5109 5110 @Override 5111 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5112 int userId) { 5113 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5114 ComponentName comp = intent.getComponent(); 5115 if (comp == null) { 5116 if (intent.getSelector() != null) { 5117 intent = intent.getSelector(); 5118 comp = intent.getComponent(); 5119 } 5120 } 5121 if (comp != null) { 5122 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5123 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5124 if (ai != null) { 5125 ResolveInfo ri = new ResolveInfo(); 5126 ri.activityInfo = ai; 5127 list.add(ri); 5128 } 5129 return list; 5130 } 5131 5132 // reader 5133 synchronized (mPackages) { 5134 String pkgName = intent.getPackage(); 5135 if (pkgName == null) { 5136 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5137 } 5138 final PackageParser.Package pkg = mPackages.get(pkgName); 5139 if (pkg != null) { 5140 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5141 userId); 5142 } 5143 return null; 5144 } 5145 } 5146 5147 @Override 5148 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5149 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5150 if (!sUserManager.exists(userId)) return null; 5151 if (query != null) { 5152 if (query.size() >= 1) { 5153 // If there is more than one service with the same priority, 5154 // just arbitrarily pick the first one. 5155 return query.get(0); 5156 } 5157 } 5158 return null; 5159 } 5160 5161 @Override 5162 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5163 int userId) { 5164 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5165 ComponentName comp = intent.getComponent(); 5166 if (comp == null) { 5167 if (intent.getSelector() != null) { 5168 intent = intent.getSelector(); 5169 comp = intent.getComponent(); 5170 } 5171 } 5172 if (comp != null) { 5173 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5174 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5175 if (si != null) { 5176 final ResolveInfo ri = new ResolveInfo(); 5177 ri.serviceInfo = si; 5178 list.add(ri); 5179 } 5180 return list; 5181 } 5182 5183 // reader 5184 synchronized (mPackages) { 5185 String pkgName = intent.getPackage(); 5186 if (pkgName == null) { 5187 return mServices.queryIntent(intent, resolvedType, flags, userId); 5188 } 5189 final PackageParser.Package pkg = mPackages.get(pkgName); 5190 if (pkg != null) { 5191 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5192 userId); 5193 } 5194 return null; 5195 } 5196 } 5197 5198 @Override 5199 public List<ResolveInfo> queryIntentContentProviders( 5200 Intent intent, String resolvedType, int flags, int userId) { 5201 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5202 ComponentName comp = intent.getComponent(); 5203 if (comp == null) { 5204 if (intent.getSelector() != null) { 5205 intent = intent.getSelector(); 5206 comp = intent.getComponent(); 5207 } 5208 } 5209 if (comp != null) { 5210 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5211 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5212 if (pi != null) { 5213 final ResolveInfo ri = new ResolveInfo(); 5214 ri.providerInfo = pi; 5215 list.add(ri); 5216 } 5217 return list; 5218 } 5219 5220 // reader 5221 synchronized (mPackages) { 5222 String pkgName = intent.getPackage(); 5223 if (pkgName == null) { 5224 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5225 } 5226 final PackageParser.Package pkg = mPackages.get(pkgName); 5227 if (pkg != null) { 5228 return mProviders.queryIntentForPackage( 5229 intent, resolvedType, flags, pkg.providers, userId); 5230 } 5231 return null; 5232 } 5233 } 5234 5235 @Override 5236 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5237 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5238 5239 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5240 5241 // writer 5242 synchronized (mPackages) { 5243 ArrayList<PackageInfo> list; 5244 if (listUninstalled) { 5245 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5246 for (PackageSetting ps : mSettings.mPackages.values()) { 5247 PackageInfo pi; 5248 if (ps.pkg != null) { 5249 pi = generatePackageInfo(ps.pkg, flags, userId); 5250 } else { 5251 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5252 } 5253 if (pi != null) { 5254 list.add(pi); 5255 } 5256 } 5257 } else { 5258 list = new ArrayList<PackageInfo>(mPackages.size()); 5259 for (PackageParser.Package p : mPackages.values()) { 5260 PackageInfo pi = generatePackageInfo(p, flags, userId); 5261 if (pi != null) { 5262 list.add(pi); 5263 } 5264 } 5265 } 5266 5267 return new ParceledListSlice<PackageInfo>(list); 5268 } 5269 } 5270 5271 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5272 String[] permissions, boolean[] tmp, int flags, int userId) { 5273 int numMatch = 0; 5274 final PermissionsState permissionsState = ps.getPermissionsState(); 5275 for (int i=0; i<permissions.length; i++) { 5276 final String permission = permissions[i]; 5277 if (permissionsState.hasPermission(permission, userId)) { 5278 tmp[i] = true; 5279 numMatch++; 5280 } else { 5281 tmp[i] = false; 5282 } 5283 } 5284 if (numMatch == 0) { 5285 return; 5286 } 5287 PackageInfo pi; 5288 if (ps.pkg != null) { 5289 pi = generatePackageInfo(ps.pkg, flags, userId); 5290 } else { 5291 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5292 } 5293 // The above might return null in cases of uninstalled apps or install-state 5294 // skew across users/profiles. 5295 if (pi != null) { 5296 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5297 if (numMatch == permissions.length) { 5298 pi.requestedPermissions = permissions; 5299 } else { 5300 pi.requestedPermissions = new String[numMatch]; 5301 numMatch = 0; 5302 for (int i=0; i<permissions.length; i++) { 5303 if (tmp[i]) { 5304 pi.requestedPermissions[numMatch] = permissions[i]; 5305 numMatch++; 5306 } 5307 } 5308 } 5309 } 5310 list.add(pi); 5311 } 5312 } 5313 5314 @Override 5315 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5316 String[] permissions, int flags, int userId) { 5317 if (!sUserManager.exists(userId)) return null; 5318 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5319 5320 // writer 5321 synchronized (mPackages) { 5322 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5323 boolean[] tmpBools = new boolean[permissions.length]; 5324 if (listUninstalled) { 5325 for (PackageSetting ps : mSettings.mPackages.values()) { 5326 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5327 } 5328 } else { 5329 for (PackageParser.Package pkg : mPackages.values()) { 5330 PackageSetting ps = (PackageSetting)pkg.mExtras; 5331 if (ps != null) { 5332 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5333 userId); 5334 } 5335 } 5336 } 5337 5338 return new ParceledListSlice<PackageInfo>(list); 5339 } 5340 } 5341 5342 @Override 5343 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5344 if (!sUserManager.exists(userId)) return null; 5345 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5346 5347 // writer 5348 synchronized (mPackages) { 5349 ArrayList<ApplicationInfo> list; 5350 if (listUninstalled) { 5351 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5352 for (PackageSetting ps : mSettings.mPackages.values()) { 5353 ApplicationInfo ai; 5354 if (ps.pkg != null) { 5355 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5356 ps.readUserState(userId), userId); 5357 } else { 5358 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5359 } 5360 if (ai != null) { 5361 list.add(ai); 5362 } 5363 } 5364 } else { 5365 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5366 for (PackageParser.Package p : mPackages.values()) { 5367 if (p.mExtras != null) { 5368 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5369 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5370 if (ai != null) { 5371 list.add(ai); 5372 } 5373 } 5374 } 5375 } 5376 5377 return new ParceledListSlice<ApplicationInfo>(list); 5378 } 5379 } 5380 5381 public List<ApplicationInfo> getPersistentApplications(int flags) { 5382 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5383 5384 // reader 5385 synchronized (mPackages) { 5386 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5387 final int userId = UserHandle.getCallingUserId(); 5388 while (i.hasNext()) { 5389 final PackageParser.Package p = i.next(); 5390 if (p.applicationInfo != null 5391 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5392 && (!mSafeMode || isSystemApp(p))) { 5393 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5394 if (ps != null) { 5395 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5396 ps.readUserState(userId), userId); 5397 if (ai != null) { 5398 finalList.add(ai); 5399 } 5400 } 5401 } 5402 } 5403 } 5404 5405 return finalList; 5406 } 5407 5408 @Override 5409 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5410 if (!sUserManager.exists(userId)) return null; 5411 // reader 5412 synchronized (mPackages) { 5413 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5414 PackageSetting ps = provider != null 5415 ? mSettings.mPackages.get(provider.owner.packageName) 5416 : null; 5417 return ps != null 5418 && mSettings.isEnabledLPr(provider.info, flags, userId) 5419 && (!mSafeMode || (provider.info.applicationInfo.flags 5420 &ApplicationInfo.FLAG_SYSTEM) != 0) 5421 ? PackageParser.generateProviderInfo(provider, flags, 5422 ps.readUserState(userId), userId) 5423 : null; 5424 } 5425 } 5426 5427 /** 5428 * @deprecated 5429 */ 5430 @Deprecated 5431 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5432 // reader 5433 synchronized (mPackages) { 5434 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5435 .entrySet().iterator(); 5436 final int userId = UserHandle.getCallingUserId(); 5437 while (i.hasNext()) { 5438 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5439 PackageParser.Provider p = entry.getValue(); 5440 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5441 5442 if (ps != null && p.syncable 5443 && (!mSafeMode || (p.info.applicationInfo.flags 5444 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5445 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5446 ps.readUserState(userId), userId); 5447 if (info != null) { 5448 outNames.add(entry.getKey()); 5449 outInfo.add(info); 5450 } 5451 } 5452 } 5453 } 5454 } 5455 5456 @Override 5457 public List<ProviderInfo> queryContentProviders(String processName, 5458 int uid, int flags) { 5459 ArrayList<ProviderInfo> finalList = null; 5460 // reader 5461 synchronized (mPackages) { 5462 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5463 final int userId = processName != null ? 5464 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5465 while (i.hasNext()) { 5466 final PackageParser.Provider p = i.next(); 5467 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5468 if (ps != null && p.info.authority != null 5469 && (processName == null 5470 || (p.info.processName.equals(processName) 5471 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5472 && mSettings.isEnabledLPr(p.info, flags, userId) 5473 && (!mSafeMode 5474 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5475 if (finalList == null) { 5476 finalList = new ArrayList<ProviderInfo>(3); 5477 } 5478 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5479 ps.readUserState(userId), userId); 5480 if (info != null) { 5481 finalList.add(info); 5482 } 5483 } 5484 } 5485 } 5486 5487 if (finalList != null) { 5488 Collections.sort(finalList, mProviderInitOrderSorter); 5489 } 5490 5491 return finalList; 5492 } 5493 5494 @Override 5495 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5496 int flags) { 5497 // reader 5498 synchronized (mPackages) { 5499 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5500 return PackageParser.generateInstrumentationInfo(i, flags); 5501 } 5502 } 5503 5504 @Override 5505 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5506 int flags) { 5507 ArrayList<InstrumentationInfo> finalList = 5508 new ArrayList<InstrumentationInfo>(); 5509 5510 // reader 5511 synchronized (mPackages) { 5512 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5513 while (i.hasNext()) { 5514 final PackageParser.Instrumentation p = i.next(); 5515 if (targetPackage == null 5516 || targetPackage.equals(p.info.targetPackage)) { 5517 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5518 flags); 5519 if (ii != null) { 5520 finalList.add(ii); 5521 } 5522 } 5523 } 5524 } 5525 5526 return finalList; 5527 } 5528 5529 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5530 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5531 if (overlays == null) { 5532 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5533 return; 5534 } 5535 for (PackageParser.Package opkg : overlays.values()) { 5536 // Not much to do if idmap fails: we already logged the error 5537 // and we certainly don't want to abort installation of pkg simply 5538 // because an overlay didn't fit properly. For these reasons, 5539 // ignore the return value of createIdmapForPackagePairLI. 5540 createIdmapForPackagePairLI(pkg, opkg); 5541 } 5542 } 5543 5544 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5545 PackageParser.Package opkg) { 5546 if (!opkg.mTrustedOverlay) { 5547 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5548 opkg.baseCodePath + ": overlay not trusted"); 5549 return false; 5550 } 5551 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5552 if (overlaySet == null) { 5553 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5554 opkg.baseCodePath + " but target package has no known overlays"); 5555 return false; 5556 } 5557 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5558 // TODO: generate idmap for split APKs 5559 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5560 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5561 + opkg.baseCodePath); 5562 return false; 5563 } 5564 PackageParser.Package[] overlayArray = 5565 overlaySet.values().toArray(new PackageParser.Package[0]); 5566 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5567 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5568 return p1.mOverlayPriority - p2.mOverlayPriority; 5569 } 5570 }; 5571 Arrays.sort(overlayArray, cmp); 5572 5573 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5574 int i = 0; 5575 for (PackageParser.Package p : overlayArray) { 5576 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5577 } 5578 return true; 5579 } 5580 5581 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5582 final File[] files = dir.listFiles(); 5583 if (ArrayUtils.isEmpty(files)) { 5584 Log.d(TAG, "No files in app dir " + dir); 5585 return; 5586 } 5587 5588 if (DEBUG_PACKAGE_SCANNING) { 5589 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5590 + " flags=0x" + Integer.toHexString(parseFlags)); 5591 } 5592 5593 for (File file : files) { 5594 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5595 && !PackageInstallerService.isStageName(file.getName()); 5596 if (!isPackage) { 5597 // Ignore entries which are not packages 5598 continue; 5599 } 5600 try { 5601 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5602 scanFlags, currentTime, null); 5603 } catch (PackageManagerException e) { 5604 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5605 5606 // Delete invalid userdata apps 5607 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5608 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5609 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5610 if (file.isDirectory()) { 5611 mInstaller.rmPackageDir(file.getAbsolutePath()); 5612 } else { 5613 file.delete(); 5614 } 5615 } 5616 } 5617 } 5618 } 5619 5620 private static File getSettingsProblemFile() { 5621 File dataDir = Environment.getDataDirectory(); 5622 File systemDir = new File(dataDir, "system"); 5623 File fname = new File(systemDir, "uiderrors.txt"); 5624 return fname; 5625 } 5626 5627 static void reportSettingsProblem(int priority, String msg) { 5628 logCriticalInfo(priority, msg); 5629 } 5630 5631 static void logCriticalInfo(int priority, String msg) { 5632 Slog.println(priority, TAG, msg); 5633 EventLogTags.writePmCriticalInfo(msg); 5634 try { 5635 File fname = getSettingsProblemFile(); 5636 FileOutputStream out = new FileOutputStream(fname, true); 5637 PrintWriter pw = new FastPrintWriter(out); 5638 SimpleDateFormat formatter = new SimpleDateFormat(); 5639 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5640 pw.println(dateString + ": " + msg); 5641 pw.close(); 5642 FileUtils.setPermissions( 5643 fname.toString(), 5644 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5645 -1, -1); 5646 } catch (java.io.IOException e) { 5647 } 5648 } 5649 5650 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5651 PackageParser.Package pkg, File srcFile, int parseFlags) 5652 throws PackageManagerException { 5653 if (ps != null 5654 && ps.codePath.equals(srcFile) 5655 && ps.timeStamp == srcFile.lastModified() 5656 && !isCompatSignatureUpdateNeeded(pkg) 5657 && !isRecoverSignatureUpdateNeeded(pkg)) { 5658 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5659 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5660 ArraySet<PublicKey> signingKs; 5661 synchronized (mPackages) { 5662 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5663 } 5664 if (ps.signatures.mSignatures != null 5665 && ps.signatures.mSignatures.length != 0 5666 && signingKs != null) { 5667 // Optimization: reuse the existing cached certificates 5668 // if the package appears to be unchanged. 5669 pkg.mSignatures = ps.signatures.mSignatures; 5670 pkg.mSigningKeys = signingKs; 5671 return; 5672 } 5673 5674 Slog.w(TAG, "PackageSetting for " + ps.name 5675 + " is missing signatures. Collecting certs again to recover them."); 5676 } else { 5677 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5678 } 5679 5680 try { 5681 pp.collectCertificates(pkg, parseFlags); 5682 pp.collectManifestDigest(pkg); 5683 } catch (PackageParserException e) { 5684 throw PackageManagerException.from(e); 5685 } 5686 } 5687 5688 /** 5689 * Traces a package scan. 5690 * @see #scanPackageLI(File, int, int, long, UserHandle) 5691 */ 5692 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 5693 long currentTime, UserHandle user) throws PackageManagerException { 5694 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 5695 try { 5696 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 5697 } finally { 5698 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5699 } 5700 } 5701 5702 /** 5703 * Scans a package and returns the newly parsed package. 5704 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 5705 */ 5706 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5707 long currentTime, UserHandle user) throws PackageManagerException { 5708 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5709 parseFlags |= mDefParseFlags; 5710 PackageParser pp = new PackageParser(); 5711 pp.setSeparateProcesses(mSeparateProcesses); 5712 pp.setOnlyCoreApps(mOnlyCore); 5713 pp.setDisplayMetrics(mMetrics); 5714 5715 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5716 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5717 } 5718 5719 final PackageParser.Package pkg; 5720 try { 5721 pkg = pp.parsePackage(scanFile, parseFlags); 5722 } catch (PackageParserException e) { 5723 throw PackageManagerException.from(e); 5724 } 5725 5726 PackageSetting ps = null; 5727 PackageSetting updatedPkg; 5728 // reader 5729 synchronized (mPackages) { 5730 // Look to see if we already know about this package. 5731 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5732 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5733 // This package has been renamed to its original name. Let's 5734 // use that. 5735 ps = mSettings.peekPackageLPr(oldName); 5736 } 5737 // If there was no original package, see one for the real package name. 5738 if (ps == null) { 5739 ps = mSettings.peekPackageLPr(pkg.packageName); 5740 } 5741 // Check to see if this package could be hiding/updating a system 5742 // package. Must look for it either under the original or real 5743 // package name depending on our state. 5744 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5745 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5746 } 5747 boolean updatedPkgBetter = false; 5748 // First check if this is a system package that may involve an update 5749 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5750 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5751 // it needs to drop FLAG_PRIVILEGED. 5752 if (locationIsPrivileged(scanFile)) { 5753 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5754 } else { 5755 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5756 } 5757 5758 if (ps != null && !ps.codePath.equals(scanFile)) { 5759 // The path has changed from what was last scanned... check the 5760 // version of the new path against what we have stored to determine 5761 // what to do. 5762 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5763 if (pkg.mVersionCode <= ps.versionCode) { 5764 // The system package has been updated and the code path does not match 5765 // Ignore entry. Skip it. 5766 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5767 + " ignored: updated version " + ps.versionCode 5768 + " better than this " + pkg.mVersionCode); 5769 if (!updatedPkg.codePath.equals(scanFile)) { 5770 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5771 + ps.name + " changing from " + updatedPkg.codePathString 5772 + " to " + scanFile); 5773 updatedPkg.codePath = scanFile; 5774 updatedPkg.codePathString = scanFile.toString(); 5775 updatedPkg.resourcePath = scanFile; 5776 updatedPkg.resourcePathString = scanFile.toString(); 5777 } 5778 updatedPkg.pkg = pkg; 5779 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5780 "Package " + ps.name + " at " + scanFile 5781 + " ignored: updated version " + ps.versionCode 5782 + " better than this " + pkg.mVersionCode); 5783 } else { 5784 // The current app on the system partition is better than 5785 // what we have updated to on the data partition; switch 5786 // back to the system partition version. 5787 // At this point, its safely assumed that package installation for 5788 // apps in system partition will go through. If not there won't be a working 5789 // version of the app 5790 // writer 5791 synchronized (mPackages) { 5792 // Just remove the loaded entries from package lists. 5793 mPackages.remove(ps.name); 5794 } 5795 5796 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5797 + " reverting from " + ps.codePathString 5798 + ": new version " + pkg.mVersionCode 5799 + " better than installed " + ps.versionCode); 5800 5801 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5802 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5803 synchronized (mInstallLock) { 5804 args.cleanUpResourcesLI(); 5805 } 5806 synchronized (mPackages) { 5807 mSettings.enableSystemPackageLPw(ps.name); 5808 } 5809 updatedPkgBetter = true; 5810 } 5811 } 5812 } 5813 5814 if (updatedPkg != null) { 5815 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5816 // initially 5817 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5818 5819 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5820 // flag set initially 5821 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5822 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5823 } 5824 } 5825 5826 // Verify certificates against what was last scanned 5827 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5828 5829 /* 5830 * A new system app appeared, but we already had a non-system one of the 5831 * same name installed earlier. 5832 */ 5833 boolean shouldHideSystemApp = false; 5834 if (updatedPkg == null && ps != null 5835 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5836 /* 5837 * Check to make sure the signatures match first. If they don't, 5838 * wipe the installed application and its data. 5839 */ 5840 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5841 != PackageManager.SIGNATURE_MATCH) { 5842 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5843 + " signatures don't match existing userdata copy; removing"); 5844 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5845 ps = null; 5846 } else { 5847 /* 5848 * If the newly-added system app is an older version than the 5849 * already installed version, hide it. It will be scanned later 5850 * and re-added like an update. 5851 */ 5852 if (pkg.mVersionCode <= ps.versionCode) { 5853 shouldHideSystemApp = true; 5854 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5855 + " but new version " + pkg.mVersionCode + " better than installed " 5856 + ps.versionCode + "; hiding system"); 5857 } else { 5858 /* 5859 * The newly found system app is a newer version that the 5860 * one previously installed. Simply remove the 5861 * already-installed application and replace it with our own 5862 * while keeping the application data. 5863 */ 5864 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5865 + " reverting from " + ps.codePathString + ": new version " 5866 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5867 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5868 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5869 synchronized (mInstallLock) { 5870 args.cleanUpResourcesLI(); 5871 } 5872 } 5873 } 5874 } 5875 5876 // The apk is forward locked (not public) if its code and resources 5877 // are kept in different files. (except for app in either system or 5878 // vendor path). 5879 // TODO grab this value from PackageSettings 5880 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5881 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5882 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5883 } 5884 } 5885 5886 // TODO: extend to support forward-locked splits 5887 String resourcePath = null; 5888 String baseResourcePath = null; 5889 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5890 if (ps != null && ps.resourcePathString != null) { 5891 resourcePath = ps.resourcePathString; 5892 baseResourcePath = ps.resourcePathString; 5893 } else { 5894 // Should not happen at all. Just log an error. 5895 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5896 } 5897 } else { 5898 resourcePath = pkg.codePath; 5899 baseResourcePath = pkg.baseCodePath; 5900 } 5901 5902 // Set application objects path explicitly. 5903 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5904 pkg.applicationInfo.setCodePath(pkg.codePath); 5905 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5906 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5907 pkg.applicationInfo.setResourcePath(resourcePath); 5908 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5909 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5910 5911 // Note that we invoke the following method only if we are about to unpack an application 5912 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5913 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5914 5915 /* 5916 * If the system app should be overridden by a previously installed 5917 * data, hide the system app now and let the /data/app scan pick it up 5918 * again. 5919 */ 5920 if (shouldHideSystemApp) { 5921 synchronized (mPackages) { 5922 /* 5923 * We have to grant systems permissions before we hide, because 5924 * grantPermissions will assume the package update is trying to 5925 * expand its permissions. 5926 */ 5927 grantPermissionsLPw(pkg, true, pkg.packageName); 5928 mSettings.disableSystemPackageLPw(pkg.packageName); 5929 } 5930 } 5931 5932 return scannedPkg; 5933 } 5934 5935 private static String fixProcessName(String defProcessName, 5936 String processName, int uid) { 5937 if (processName == null) { 5938 return defProcessName; 5939 } 5940 return processName; 5941 } 5942 5943 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5944 throws PackageManagerException { 5945 if (pkgSetting.signatures.mSignatures != null) { 5946 // Already existing package. Make sure signatures match 5947 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5948 == PackageManager.SIGNATURE_MATCH; 5949 if (!match) { 5950 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5951 == PackageManager.SIGNATURE_MATCH; 5952 } 5953 if (!match) { 5954 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5955 == PackageManager.SIGNATURE_MATCH; 5956 } 5957 if (!match) { 5958 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5959 + pkg.packageName + " signatures do not match the " 5960 + "previously installed version; ignoring!"); 5961 } 5962 } 5963 5964 // Check for shared user signatures 5965 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5966 // Already existing package. Make sure signatures match 5967 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5968 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5969 if (!match) { 5970 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5971 == PackageManager.SIGNATURE_MATCH; 5972 } 5973 if (!match) { 5974 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5975 == PackageManager.SIGNATURE_MATCH; 5976 } 5977 if (!match) { 5978 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5979 "Package " + pkg.packageName 5980 + " has no signatures that match those in shared user " 5981 + pkgSetting.sharedUser.name + "; ignoring!"); 5982 } 5983 } 5984 } 5985 5986 /** 5987 * Enforces that only the system UID or root's UID can call a method exposed 5988 * via Binder. 5989 * 5990 * @param message used as message if SecurityException is thrown 5991 * @throws SecurityException if the caller is not system or root 5992 */ 5993 private static final void enforceSystemOrRoot(String message) { 5994 final int uid = Binder.getCallingUid(); 5995 if (uid != Process.SYSTEM_UID && uid != 0) { 5996 throw new SecurityException(message); 5997 } 5998 } 5999 6000 @Override 6001 public void performBootDexOpt() { 6002 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6003 6004 // Before everything else, see whether we need to fstrim. 6005 try { 6006 IMountService ms = PackageHelper.getMountService(); 6007 if (ms != null) { 6008 final boolean isUpgrade = isUpgrade(); 6009 boolean doTrim = isUpgrade; 6010 if (doTrim) { 6011 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6012 } else { 6013 final long interval = android.provider.Settings.Global.getLong( 6014 mContext.getContentResolver(), 6015 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6016 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6017 if (interval > 0) { 6018 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6019 if (timeSinceLast > interval) { 6020 doTrim = true; 6021 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6022 + "; running immediately"); 6023 } 6024 } 6025 } 6026 if (doTrim) { 6027 if (!isFirstBoot()) { 6028 try { 6029 ActivityManagerNative.getDefault().showBootMessage( 6030 mContext.getResources().getString( 6031 R.string.android_upgrading_fstrim), true); 6032 } catch (RemoteException e) { 6033 } 6034 } 6035 ms.runMaintenance(); 6036 } 6037 } else { 6038 Slog.e(TAG, "Mount service unavailable!"); 6039 } 6040 } catch (RemoteException e) { 6041 // Can't happen; MountService is local 6042 } 6043 6044 final ArraySet<PackageParser.Package> pkgs; 6045 synchronized (mPackages) { 6046 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6047 } 6048 6049 if (pkgs != null) { 6050 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6051 // in case the device runs out of space. 6052 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6053 // Give priority to core apps. 6054 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6055 PackageParser.Package pkg = it.next(); 6056 if (pkg.coreApp) { 6057 if (DEBUG_DEXOPT) { 6058 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6059 } 6060 sortedPkgs.add(pkg); 6061 it.remove(); 6062 } 6063 } 6064 // Give priority to system apps that listen for pre boot complete. 6065 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6066 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 6067 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6068 PackageParser.Package pkg = it.next(); 6069 if (pkgNames.contains(pkg.packageName)) { 6070 if (DEBUG_DEXOPT) { 6071 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6072 } 6073 sortedPkgs.add(pkg); 6074 it.remove(); 6075 } 6076 } 6077 // Give priority to system apps. 6078 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6079 PackageParser.Package pkg = it.next(); 6080 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6081 if (DEBUG_DEXOPT) { 6082 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6083 } 6084 sortedPkgs.add(pkg); 6085 it.remove(); 6086 } 6087 } 6088 // Give priority to updated system apps. 6089 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6090 PackageParser.Package pkg = it.next(); 6091 if (pkg.isUpdatedSystemApp()) { 6092 if (DEBUG_DEXOPT) { 6093 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6094 } 6095 sortedPkgs.add(pkg); 6096 it.remove(); 6097 } 6098 } 6099 // Give priority to apps that listen for boot complete. 6100 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6101 pkgNames = getPackageNamesForIntent(intent); 6102 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6103 PackageParser.Package pkg = it.next(); 6104 if (pkgNames.contains(pkg.packageName)) { 6105 if (DEBUG_DEXOPT) { 6106 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6107 } 6108 sortedPkgs.add(pkg); 6109 it.remove(); 6110 } 6111 } 6112 // Filter out packages that aren't recently used. 6113 filterRecentlyUsedApps(pkgs); 6114 // Add all remaining apps. 6115 for (PackageParser.Package pkg : pkgs) { 6116 if (DEBUG_DEXOPT) { 6117 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6118 } 6119 sortedPkgs.add(pkg); 6120 } 6121 6122 // If we want to be lazy, filter everything that wasn't recently used. 6123 if (mLazyDexOpt) { 6124 filterRecentlyUsedApps(sortedPkgs); 6125 } 6126 6127 int i = 0; 6128 int total = sortedPkgs.size(); 6129 File dataDir = Environment.getDataDirectory(); 6130 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6131 if (lowThreshold == 0) { 6132 throw new IllegalStateException("Invalid low memory threshold"); 6133 } 6134 for (PackageParser.Package pkg : sortedPkgs) { 6135 long usableSpace = dataDir.getUsableSpace(); 6136 if (usableSpace < lowThreshold) { 6137 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6138 break; 6139 } 6140 performBootDexOpt(pkg, ++i, total); 6141 } 6142 } 6143 } 6144 6145 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6146 // Filter out packages that aren't recently used. 6147 // 6148 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6149 // should do a full dexopt. 6150 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6151 int total = pkgs.size(); 6152 int skipped = 0; 6153 long now = System.currentTimeMillis(); 6154 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6155 PackageParser.Package pkg = i.next(); 6156 long then = pkg.mLastPackageUsageTimeInMills; 6157 if (then + mDexOptLRUThresholdInMills < now) { 6158 if (DEBUG_DEXOPT) { 6159 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6160 ((then == 0) ? "never" : new Date(then))); 6161 } 6162 i.remove(); 6163 skipped++; 6164 } 6165 } 6166 if (DEBUG_DEXOPT) { 6167 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6168 } 6169 } 6170 } 6171 6172 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6173 List<ResolveInfo> ris = null; 6174 try { 6175 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6176 intent, null, 0, UserHandle.USER_OWNER); 6177 } catch (RemoteException e) { 6178 } 6179 ArraySet<String> pkgNames = new ArraySet<String>(); 6180 if (ris != null) { 6181 for (ResolveInfo ri : ris) { 6182 pkgNames.add(ri.activityInfo.packageName); 6183 } 6184 } 6185 return pkgNames; 6186 } 6187 6188 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6189 if (DEBUG_DEXOPT) { 6190 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6191 } 6192 if (!isFirstBoot()) { 6193 try { 6194 ActivityManagerNative.getDefault().showBootMessage( 6195 mContext.getResources().getString(R.string.android_upgrading_apk, 6196 curr, total), true); 6197 } catch (RemoteException e) { 6198 } 6199 } 6200 PackageParser.Package p = pkg; 6201 synchronized (mInstallLock) { 6202 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6203 false /* force dex */, false /* defer */, true /* include dependencies */); 6204 } 6205 } 6206 6207 @Override 6208 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6209 return performDexOpt(packageName, instructionSet, false); 6210 } 6211 6212 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6213 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6214 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6215 if (!dexopt && !updateUsage) { 6216 // We aren't going to dexopt or update usage, so bail early. 6217 return false; 6218 } 6219 PackageParser.Package p; 6220 final String targetInstructionSet; 6221 synchronized (mPackages) { 6222 p = mPackages.get(packageName); 6223 if (p == null) { 6224 return false; 6225 } 6226 if (updateUsage) { 6227 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6228 } 6229 mPackageUsage.write(false); 6230 if (!dexopt) { 6231 // We aren't going to dexopt, so bail early. 6232 return false; 6233 } 6234 6235 targetInstructionSet = instructionSet != null ? instructionSet : 6236 getPrimaryInstructionSet(p.applicationInfo); 6237 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6238 return false; 6239 } 6240 } 6241 long callingId = Binder.clearCallingIdentity(); 6242 try { 6243 synchronized (mInstallLock) { 6244 final String[] instructionSets = new String[] { targetInstructionSet }; 6245 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6246 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6247 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6248 } 6249 } finally { 6250 Binder.restoreCallingIdentity(callingId); 6251 } 6252 } 6253 6254 public ArraySet<String> getPackagesThatNeedDexOpt() { 6255 ArraySet<String> pkgs = null; 6256 synchronized (mPackages) { 6257 for (PackageParser.Package p : mPackages.values()) { 6258 if (DEBUG_DEXOPT) { 6259 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6260 } 6261 if (!p.mDexOptPerformed.isEmpty()) { 6262 continue; 6263 } 6264 if (pkgs == null) { 6265 pkgs = new ArraySet<String>(); 6266 } 6267 pkgs.add(p.packageName); 6268 } 6269 } 6270 return pkgs; 6271 } 6272 6273 public void shutdown() { 6274 mPackageUsage.write(true); 6275 } 6276 6277 @Override 6278 public void forceDexOpt(String packageName) { 6279 enforceSystemOrRoot("forceDexOpt"); 6280 6281 PackageParser.Package pkg; 6282 synchronized (mPackages) { 6283 pkg = mPackages.get(packageName); 6284 if (pkg == null) { 6285 throw new IllegalArgumentException("Missing package: " + packageName); 6286 } 6287 } 6288 6289 synchronized (mInstallLock) { 6290 final String[] instructionSets = new String[] { 6291 getPrimaryInstructionSet(pkg.applicationInfo) }; 6292 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6293 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6294 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6295 throw new IllegalStateException("Failed to dexopt: " + res); 6296 } 6297 } 6298 } 6299 6300 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6301 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6302 Slog.w(TAG, "Unable to update from " + oldPkg.name 6303 + " to " + newPkg.packageName 6304 + ": old package not in system partition"); 6305 return false; 6306 } else if (mPackages.get(oldPkg.name) != null) { 6307 Slog.w(TAG, "Unable to update from " + oldPkg.name 6308 + " to " + newPkg.packageName 6309 + ": old package still exists"); 6310 return false; 6311 } 6312 return true; 6313 } 6314 6315 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6316 int[] users = sUserManager.getUserIds(); 6317 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6318 if (res < 0) { 6319 return res; 6320 } 6321 for (int user : users) { 6322 if (user != 0) { 6323 res = mInstaller.createUserData(volumeUuid, packageName, 6324 UserHandle.getUid(user, uid), user, seinfo); 6325 if (res < 0) { 6326 return res; 6327 } 6328 } 6329 } 6330 return res; 6331 } 6332 6333 private int removeDataDirsLI(String volumeUuid, String packageName) { 6334 int[] users = sUserManager.getUserIds(); 6335 int res = 0; 6336 for (int user : users) { 6337 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6338 if (resInner < 0) { 6339 res = resInner; 6340 } 6341 } 6342 6343 return res; 6344 } 6345 6346 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6347 int[] users = sUserManager.getUserIds(); 6348 int res = 0; 6349 for (int user : users) { 6350 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6351 if (resInner < 0) { 6352 res = resInner; 6353 } 6354 } 6355 return res; 6356 } 6357 6358 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6359 PackageParser.Package changingLib) { 6360 if (file.path != null) { 6361 usesLibraryFiles.add(file.path); 6362 return; 6363 } 6364 PackageParser.Package p = mPackages.get(file.apk); 6365 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6366 // If we are doing this while in the middle of updating a library apk, 6367 // then we need to make sure to use that new apk for determining the 6368 // dependencies here. (We haven't yet finished committing the new apk 6369 // to the package manager state.) 6370 if (p == null || p.packageName.equals(changingLib.packageName)) { 6371 p = changingLib; 6372 } 6373 } 6374 if (p != null) { 6375 usesLibraryFiles.addAll(p.getAllCodePaths()); 6376 } 6377 } 6378 6379 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6380 PackageParser.Package changingLib) throws PackageManagerException { 6381 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6382 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6383 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6384 for (int i=0; i<N; i++) { 6385 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6386 if (file == null) { 6387 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6388 "Package " + pkg.packageName + " requires unavailable shared library " 6389 + pkg.usesLibraries.get(i) + "; failing!"); 6390 } 6391 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6392 } 6393 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6394 for (int i=0; i<N; i++) { 6395 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6396 if (file == null) { 6397 Slog.w(TAG, "Package " + pkg.packageName 6398 + " desires unavailable shared library " 6399 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6400 } else { 6401 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6402 } 6403 } 6404 N = usesLibraryFiles.size(); 6405 if (N > 0) { 6406 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6407 } else { 6408 pkg.usesLibraryFiles = null; 6409 } 6410 } 6411 } 6412 6413 private static boolean hasString(List<String> list, List<String> which) { 6414 if (list == null) { 6415 return false; 6416 } 6417 for (int i=list.size()-1; i>=0; i--) { 6418 for (int j=which.size()-1; j>=0; j--) { 6419 if (which.get(j).equals(list.get(i))) { 6420 return true; 6421 } 6422 } 6423 } 6424 return false; 6425 } 6426 6427 private void updateAllSharedLibrariesLPw() { 6428 for (PackageParser.Package pkg : mPackages.values()) { 6429 try { 6430 updateSharedLibrariesLPw(pkg, null); 6431 } catch (PackageManagerException e) { 6432 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6433 } 6434 } 6435 } 6436 6437 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6438 PackageParser.Package changingPkg) { 6439 ArrayList<PackageParser.Package> res = null; 6440 for (PackageParser.Package pkg : mPackages.values()) { 6441 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6442 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6443 if (res == null) { 6444 res = new ArrayList<PackageParser.Package>(); 6445 } 6446 res.add(pkg); 6447 try { 6448 updateSharedLibrariesLPw(pkg, changingPkg); 6449 } catch (PackageManagerException e) { 6450 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6451 } 6452 } 6453 } 6454 return res; 6455 } 6456 6457 /** 6458 * Derive the value of the {@code cpuAbiOverride} based on the provided 6459 * value and an optional stored value from the package settings. 6460 */ 6461 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6462 String cpuAbiOverride = null; 6463 6464 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6465 cpuAbiOverride = null; 6466 } else if (abiOverride != null) { 6467 cpuAbiOverride = abiOverride; 6468 } else if (settings != null) { 6469 cpuAbiOverride = settings.cpuAbiOverrideString; 6470 } 6471 6472 return cpuAbiOverride; 6473 } 6474 6475 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6476 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6477 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6478 try { 6479 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6480 } finally { 6481 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6482 } 6483 } 6484 6485 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6486 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6487 boolean success = false; 6488 try { 6489 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6490 currentTime, user); 6491 success = true; 6492 return res; 6493 } finally { 6494 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6495 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6496 } 6497 } 6498 } 6499 6500 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6501 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6502 final File scanFile = new File(pkg.codePath); 6503 if (pkg.applicationInfo.getCodePath() == null || 6504 pkg.applicationInfo.getResourcePath() == null) { 6505 // Bail out. The resource and code paths haven't been set. 6506 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6507 "Code and resource paths haven't been set correctly"); 6508 } 6509 6510 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6511 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6512 } else { 6513 // Only allow system apps to be flagged as core apps. 6514 pkg.coreApp = false; 6515 } 6516 6517 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6518 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6519 } 6520 6521 if (mCustomResolverComponentName != null && 6522 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6523 setUpCustomResolverActivity(pkg); 6524 } 6525 6526 if (pkg.packageName.equals("android")) { 6527 synchronized (mPackages) { 6528 if (mAndroidApplication != null) { 6529 Slog.w(TAG, "*************************************************"); 6530 Slog.w(TAG, "Core android package being redefined. Skipping."); 6531 Slog.w(TAG, " file=" + scanFile); 6532 Slog.w(TAG, "*************************************************"); 6533 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6534 "Core android package being redefined. Skipping."); 6535 } 6536 6537 // Set up information for our fall-back user intent resolution activity. 6538 mPlatformPackage = pkg; 6539 pkg.mVersionCode = mSdkVersion; 6540 mAndroidApplication = pkg.applicationInfo; 6541 6542 if (!mResolverReplaced) { 6543 mResolveActivity.applicationInfo = mAndroidApplication; 6544 mResolveActivity.name = ResolverActivity.class.getName(); 6545 mResolveActivity.packageName = mAndroidApplication.packageName; 6546 mResolveActivity.processName = "system:ui"; 6547 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6548 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6549 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6550 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6551 mResolveActivity.exported = true; 6552 mResolveActivity.enabled = true; 6553 mResolveInfo.activityInfo = mResolveActivity; 6554 mResolveInfo.priority = 0; 6555 mResolveInfo.preferredOrder = 0; 6556 mResolveInfo.match = 0; 6557 mResolveComponentName = new ComponentName( 6558 mAndroidApplication.packageName, mResolveActivity.name); 6559 } 6560 } 6561 } 6562 6563 if (DEBUG_PACKAGE_SCANNING) { 6564 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6565 Log.d(TAG, "Scanning package " + pkg.packageName); 6566 } 6567 6568 if (mPackages.containsKey(pkg.packageName) 6569 || mSharedLibraries.containsKey(pkg.packageName)) { 6570 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6571 "Application package " + pkg.packageName 6572 + " already installed. Skipping duplicate."); 6573 } 6574 6575 // If we're only installing presumed-existing packages, require that the 6576 // scanned APK is both already known and at the path previously established 6577 // for it. Previously unknown packages we pick up normally, but if we have an 6578 // a priori expectation about this package's install presence, enforce it. 6579 // With a singular exception for new system packages. When an OTA contains 6580 // a new system package, we allow the codepath to change from a system location 6581 // to the user-installed location. If we don't allow this change, any newer, 6582 // user-installed version of the application will be ignored. 6583 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6584 if (mExpectingBetter.containsKey(pkg.packageName)) { 6585 logCriticalInfo(Log.WARN, 6586 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6587 } else { 6588 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6589 if (known != null) { 6590 if (DEBUG_PACKAGE_SCANNING) { 6591 Log.d(TAG, "Examining " + pkg.codePath 6592 + " and requiring known paths " + known.codePathString 6593 + " & " + known.resourcePathString); 6594 } 6595 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6596 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6597 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6598 "Application package " + pkg.packageName 6599 + " found at " + pkg.applicationInfo.getCodePath() 6600 + " but expected at " + known.codePathString + "; ignoring."); 6601 } 6602 } 6603 } 6604 } 6605 6606 // Initialize package source and resource directories 6607 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6608 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6609 6610 SharedUserSetting suid = null; 6611 PackageSetting pkgSetting = null; 6612 6613 if (!isSystemApp(pkg)) { 6614 // Only system apps can use these features. 6615 pkg.mOriginalPackages = null; 6616 pkg.mRealPackage = null; 6617 pkg.mAdoptPermissions = null; 6618 } 6619 6620 // writer 6621 synchronized (mPackages) { 6622 if (pkg.mSharedUserId != null) { 6623 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6624 if (suid == null) { 6625 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6626 "Creating application package " + pkg.packageName 6627 + " for shared user failed"); 6628 } 6629 if (DEBUG_PACKAGE_SCANNING) { 6630 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6631 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6632 + "): packages=" + suid.packages); 6633 } 6634 } 6635 6636 // Check if we are renaming from an original package name. 6637 PackageSetting origPackage = null; 6638 String realName = null; 6639 if (pkg.mOriginalPackages != null) { 6640 // This package may need to be renamed to a previously 6641 // installed name. Let's check on that... 6642 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6643 if (pkg.mOriginalPackages.contains(renamed)) { 6644 // This package had originally been installed as the 6645 // original name, and we have already taken care of 6646 // transitioning to the new one. Just update the new 6647 // one to continue using the old name. 6648 realName = pkg.mRealPackage; 6649 if (!pkg.packageName.equals(renamed)) { 6650 // Callers into this function may have already taken 6651 // care of renaming the package; only do it here if 6652 // it is not already done. 6653 pkg.setPackageName(renamed); 6654 } 6655 6656 } else { 6657 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6658 if ((origPackage = mSettings.peekPackageLPr( 6659 pkg.mOriginalPackages.get(i))) != null) { 6660 // We do have the package already installed under its 6661 // original name... should we use it? 6662 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6663 // New package is not compatible with original. 6664 origPackage = null; 6665 continue; 6666 } else if (origPackage.sharedUser != null) { 6667 // Make sure uid is compatible between packages. 6668 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6669 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6670 + " to " + pkg.packageName + ": old uid " 6671 + origPackage.sharedUser.name 6672 + " differs from " + pkg.mSharedUserId); 6673 origPackage = null; 6674 continue; 6675 } 6676 } else { 6677 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6678 + pkg.packageName + " to old name " + origPackage.name); 6679 } 6680 break; 6681 } 6682 } 6683 } 6684 } 6685 6686 if (mTransferedPackages.contains(pkg.packageName)) { 6687 Slog.w(TAG, "Package " + pkg.packageName 6688 + " was transferred to another, but its .apk remains"); 6689 } 6690 6691 // Just create the setting, don't add it yet. For already existing packages 6692 // the PkgSetting exists already and doesn't have to be created. 6693 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6694 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6695 pkg.applicationInfo.primaryCpuAbi, 6696 pkg.applicationInfo.secondaryCpuAbi, 6697 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6698 user, false); 6699 if (pkgSetting == null) { 6700 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6701 "Creating application package " + pkg.packageName + " failed"); 6702 } 6703 6704 if (pkgSetting.origPackage != null) { 6705 // If we are first transitioning from an original package, 6706 // fix up the new package's name now. We need to do this after 6707 // looking up the package under its new name, so getPackageLP 6708 // can take care of fiddling things correctly. 6709 pkg.setPackageName(origPackage.name); 6710 6711 // File a report about this. 6712 String msg = "New package " + pkgSetting.realName 6713 + " renamed to replace old package " + pkgSetting.name; 6714 reportSettingsProblem(Log.WARN, msg); 6715 6716 // Make a note of it. 6717 mTransferedPackages.add(origPackage.name); 6718 6719 // No longer need to retain this. 6720 pkgSetting.origPackage = null; 6721 } 6722 6723 if (realName != null) { 6724 // Make a note of it. 6725 mTransferedPackages.add(pkg.packageName); 6726 } 6727 6728 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6729 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6730 } 6731 6732 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6733 // Check all shared libraries and map to their actual file path. 6734 // We only do this here for apps not on a system dir, because those 6735 // are the only ones that can fail an install due to this. We 6736 // will take care of the system apps by updating all of their 6737 // library paths after the scan is done. 6738 updateSharedLibrariesLPw(pkg, null); 6739 } 6740 6741 if (mFoundPolicyFile) { 6742 SELinuxMMAC.assignSeinfoValue(pkg); 6743 } 6744 6745 pkg.applicationInfo.uid = pkgSetting.appId; 6746 pkg.mExtras = pkgSetting; 6747 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6748 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6749 // We just determined the app is signed correctly, so bring 6750 // over the latest parsed certs. 6751 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6752 } else { 6753 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6754 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6755 "Package " + pkg.packageName + " upgrade keys do not match the " 6756 + "previously installed version"); 6757 } else { 6758 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6759 String msg = "System package " + pkg.packageName 6760 + " signature changed; retaining data."; 6761 reportSettingsProblem(Log.WARN, msg); 6762 } 6763 } 6764 } else { 6765 try { 6766 verifySignaturesLP(pkgSetting, pkg); 6767 // We just determined the app is signed correctly, so bring 6768 // over the latest parsed certs. 6769 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6770 } catch (PackageManagerException e) { 6771 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6772 throw e; 6773 } 6774 // The signature has changed, but this package is in the system 6775 // image... let's recover! 6776 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6777 // However... if this package is part of a shared user, but it 6778 // doesn't match the signature of the shared user, let's fail. 6779 // What this means is that you can't change the signatures 6780 // associated with an overall shared user, which doesn't seem all 6781 // that unreasonable. 6782 if (pkgSetting.sharedUser != null) { 6783 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6784 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6785 throw new PackageManagerException( 6786 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6787 "Signature mismatch for shared user : " 6788 + pkgSetting.sharedUser); 6789 } 6790 } 6791 // File a report about this. 6792 String msg = "System package " + pkg.packageName 6793 + " signature changed; retaining data."; 6794 reportSettingsProblem(Log.WARN, msg); 6795 } 6796 } 6797 // Verify that this new package doesn't have any content providers 6798 // that conflict with existing packages. Only do this if the 6799 // package isn't already installed, since we don't want to break 6800 // things that are installed. 6801 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6802 final int N = pkg.providers.size(); 6803 int i; 6804 for (i=0; i<N; i++) { 6805 PackageParser.Provider p = pkg.providers.get(i); 6806 if (p.info.authority != null) { 6807 String names[] = p.info.authority.split(";"); 6808 for (int j = 0; j < names.length; j++) { 6809 if (mProvidersByAuthority.containsKey(names[j])) { 6810 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6811 final String otherPackageName = 6812 ((other != null && other.getComponentName() != null) ? 6813 other.getComponentName().getPackageName() : "?"); 6814 throw new PackageManagerException( 6815 INSTALL_FAILED_CONFLICTING_PROVIDER, 6816 "Can't install because provider name " + names[j] 6817 + " (in package " + pkg.applicationInfo.packageName 6818 + ") is already used by " + otherPackageName); 6819 } 6820 } 6821 } 6822 } 6823 } 6824 6825 if (pkg.mAdoptPermissions != null) { 6826 // This package wants to adopt ownership of permissions from 6827 // another package. 6828 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6829 final String origName = pkg.mAdoptPermissions.get(i); 6830 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6831 if (orig != null) { 6832 if (verifyPackageUpdateLPr(orig, pkg)) { 6833 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6834 + pkg.packageName); 6835 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6836 } 6837 } 6838 } 6839 } 6840 } 6841 6842 final String pkgName = pkg.packageName; 6843 6844 final long scanFileTime = scanFile.lastModified(); 6845 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6846 pkg.applicationInfo.processName = fixProcessName( 6847 pkg.applicationInfo.packageName, 6848 pkg.applicationInfo.processName, 6849 pkg.applicationInfo.uid); 6850 6851 File dataPath; 6852 if (mPlatformPackage == pkg) { 6853 // The system package is special. 6854 dataPath = new File(Environment.getDataDirectory(), "system"); 6855 6856 pkg.applicationInfo.dataDir = dataPath.getPath(); 6857 6858 } else { 6859 // This is a normal package, need to make its data directory. 6860 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6861 UserHandle.USER_OWNER, pkg.packageName); 6862 6863 boolean uidError = false; 6864 if (dataPath.exists()) { 6865 int currentUid = 0; 6866 try { 6867 StructStat stat = Os.stat(dataPath.getPath()); 6868 currentUid = stat.st_uid; 6869 } catch (ErrnoException e) { 6870 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6871 } 6872 6873 // If we have mismatched owners for the data path, we have a problem. 6874 if (currentUid != pkg.applicationInfo.uid) { 6875 boolean recovered = false; 6876 if (currentUid == 0) { 6877 // The directory somehow became owned by root. Wow. 6878 // This is probably because the system was stopped while 6879 // installd was in the middle of messing with its libs 6880 // directory. Ask installd to fix that. 6881 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6882 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6883 if (ret >= 0) { 6884 recovered = true; 6885 String msg = "Package " + pkg.packageName 6886 + " unexpectedly changed to uid 0; recovered to " + 6887 + pkg.applicationInfo.uid; 6888 reportSettingsProblem(Log.WARN, msg); 6889 } 6890 } 6891 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6892 || (scanFlags&SCAN_BOOTING) != 0)) { 6893 // If this is a system app, we can at least delete its 6894 // current data so the application will still work. 6895 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6896 if (ret >= 0) { 6897 // TODO: Kill the processes first 6898 // Old data gone! 6899 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6900 ? "System package " : "Third party package "; 6901 String msg = prefix + pkg.packageName 6902 + " has changed from uid: " 6903 + currentUid + " to " 6904 + pkg.applicationInfo.uid + "; old data erased"; 6905 reportSettingsProblem(Log.WARN, msg); 6906 recovered = true; 6907 6908 // And now re-install the app. 6909 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6910 pkg.applicationInfo.seinfo); 6911 if (ret == -1) { 6912 // Ack should not happen! 6913 msg = prefix + pkg.packageName 6914 + " could not have data directory re-created after delete."; 6915 reportSettingsProblem(Log.WARN, msg); 6916 throw new PackageManagerException( 6917 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6918 } 6919 } 6920 if (!recovered) { 6921 mHasSystemUidErrors = true; 6922 } 6923 } else if (!recovered) { 6924 // If we allow this install to proceed, we will be broken. 6925 // Abort, abort! 6926 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6927 "scanPackageLI"); 6928 } 6929 if (!recovered) { 6930 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6931 + pkg.applicationInfo.uid + "/fs_" 6932 + currentUid; 6933 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6934 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6935 String msg = "Package " + pkg.packageName 6936 + " has mismatched uid: " 6937 + currentUid + " on disk, " 6938 + pkg.applicationInfo.uid + " in settings"; 6939 // writer 6940 synchronized (mPackages) { 6941 mSettings.mReadMessages.append(msg); 6942 mSettings.mReadMessages.append('\n'); 6943 uidError = true; 6944 if (!pkgSetting.uidError) { 6945 reportSettingsProblem(Log.ERROR, msg); 6946 } 6947 } 6948 } 6949 } 6950 pkg.applicationInfo.dataDir = dataPath.getPath(); 6951 if (mShouldRestoreconData) { 6952 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6953 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6954 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6955 } 6956 } else { 6957 if (DEBUG_PACKAGE_SCANNING) { 6958 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6959 Log.v(TAG, "Want this data dir: " + dataPath); 6960 } 6961 //invoke installer to do the actual installation 6962 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6963 pkg.applicationInfo.seinfo); 6964 if (ret < 0) { 6965 // Error from installer 6966 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6967 "Unable to create data dirs [errorCode=" + ret + "]"); 6968 } 6969 6970 if (dataPath.exists()) { 6971 pkg.applicationInfo.dataDir = dataPath.getPath(); 6972 } else { 6973 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6974 pkg.applicationInfo.dataDir = null; 6975 } 6976 } 6977 6978 pkgSetting.uidError = uidError; 6979 } 6980 6981 final String path = scanFile.getPath(); 6982 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6983 6984 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6985 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6986 6987 // Some system apps still use directory structure for native libraries 6988 // in which case we might end up not detecting abi solely based on apk 6989 // structure. Try to detect abi based on directory structure. 6990 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6991 pkg.applicationInfo.primaryCpuAbi == null) { 6992 setBundledAppAbisAndRoots(pkg, pkgSetting); 6993 setNativeLibraryPaths(pkg); 6994 } 6995 6996 } else { 6997 if ((scanFlags & SCAN_MOVE) != 0) { 6998 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6999 // but we already have this packages package info in the PackageSetting. We just 7000 // use that and derive the native library path based on the new codepath. 7001 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7002 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7003 } 7004 7005 // Set native library paths again. For moves, the path will be updated based on the 7006 // ABIs we've determined above. For non-moves, the path will be updated based on the 7007 // ABIs we determined during compilation, but the path will depend on the final 7008 // package path (after the rename away from the stage path). 7009 setNativeLibraryPaths(pkg); 7010 } 7011 7012 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7013 final int[] userIds = sUserManager.getUserIds(); 7014 synchronized (mInstallLock) { 7015 // Make sure all user data directories are ready to roll; we're okay 7016 // if they already exist 7017 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7018 for (int userId : userIds) { 7019 if (userId != 0) { 7020 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7021 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7022 pkg.applicationInfo.seinfo); 7023 } 7024 } 7025 } 7026 7027 // Create a native library symlink only if we have native libraries 7028 // and if the native libraries are 32 bit libraries. We do not provide 7029 // this symlink for 64 bit libraries. 7030 if (pkg.applicationInfo.primaryCpuAbi != null && 7031 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7032 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7033 try { 7034 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7035 for (int userId : userIds) { 7036 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7037 nativeLibPath, userId) < 0) { 7038 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7039 "Failed linking native library dir (user=" + userId + ")"); 7040 } 7041 } 7042 } finally { 7043 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7044 } 7045 } 7046 } 7047 7048 // This is a special case for the "system" package, where the ABI is 7049 // dictated by the zygote configuration (and init.rc). We should keep track 7050 // of this ABI so that we can deal with "normal" applications that run under 7051 // the same UID correctly. 7052 if (mPlatformPackage == pkg) { 7053 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7054 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7055 } 7056 7057 // If there's a mismatch between the abi-override in the package setting 7058 // and the abiOverride specified for the install. Warn about this because we 7059 // would've already compiled the app without taking the package setting into 7060 // account. 7061 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7062 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7063 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7064 " for package: " + pkg.packageName); 7065 } 7066 } 7067 7068 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7069 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7070 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7071 7072 // Copy the derived override back to the parsed package, so that we can 7073 // update the package settings accordingly. 7074 pkg.cpuAbiOverride = cpuAbiOverride; 7075 7076 if (DEBUG_ABI_SELECTION) { 7077 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7078 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7079 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7080 } 7081 7082 // Push the derived path down into PackageSettings so we know what to 7083 // clean up at uninstall time. 7084 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7085 7086 if (DEBUG_ABI_SELECTION) { 7087 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7088 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7089 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7090 } 7091 7092 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7093 // We don't do this here during boot because we can do it all 7094 // at once after scanning all existing packages. 7095 // 7096 // We also do this *before* we perform dexopt on this package, so that 7097 // we can avoid redundant dexopts, and also to make sure we've got the 7098 // code and package path correct. 7099 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7100 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7101 } 7102 7103 if ((scanFlags & SCAN_NO_DEX) == 0) { 7104 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7105 7106 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7107 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7108 7109 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7110 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7111 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7112 } 7113 } 7114 if (mFactoryTest && pkg.requestedPermissions.contains( 7115 android.Manifest.permission.FACTORY_TEST)) { 7116 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7117 } 7118 7119 ArrayList<PackageParser.Package> clientLibPkgs = null; 7120 7121 // writer 7122 synchronized (mPackages) { 7123 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7124 // Only system apps can add new shared libraries. 7125 if (pkg.libraryNames != null) { 7126 for (int i=0; i<pkg.libraryNames.size(); i++) { 7127 String name = pkg.libraryNames.get(i); 7128 boolean allowed = false; 7129 if (pkg.isUpdatedSystemApp()) { 7130 // New library entries can only be added through the 7131 // system image. This is important to get rid of a lot 7132 // of nasty edge cases: for example if we allowed a non- 7133 // system update of the app to add a library, then uninstalling 7134 // the update would make the library go away, and assumptions 7135 // we made such as through app install filtering would now 7136 // have allowed apps on the device which aren't compatible 7137 // with it. Better to just have the restriction here, be 7138 // conservative, and create many fewer cases that can negatively 7139 // impact the user experience. 7140 final PackageSetting sysPs = mSettings 7141 .getDisabledSystemPkgLPr(pkg.packageName); 7142 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7143 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7144 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7145 allowed = true; 7146 allowed = true; 7147 break; 7148 } 7149 } 7150 } 7151 } else { 7152 allowed = true; 7153 } 7154 if (allowed) { 7155 if (!mSharedLibraries.containsKey(name)) { 7156 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7157 } else if (!name.equals(pkg.packageName)) { 7158 Slog.w(TAG, "Package " + pkg.packageName + " library " 7159 + name + " already exists; skipping"); 7160 } 7161 } else { 7162 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7163 + name + " that is not declared on system image; skipping"); 7164 } 7165 } 7166 if ((scanFlags&SCAN_BOOTING) == 0) { 7167 // If we are not booting, we need to update any applications 7168 // that are clients of our shared library. If we are booting, 7169 // this will all be done once the scan is complete. 7170 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7171 } 7172 } 7173 } 7174 } 7175 7176 // We also need to dexopt any apps that are dependent on this library. Note that 7177 // if these fail, we should abort the install since installing the library will 7178 // result in some apps being broken. 7179 if (clientLibPkgs != null) { 7180 if ((scanFlags & SCAN_NO_DEX) == 0) { 7181 for (int i = 0; i < clientLibPkgs.size(); i++) { 7182 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7183 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7184 null /* instruction sets */, forceDex, 7185 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7186 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7187 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7188 "scanPackageLI failed to dexopt clientLibPkgs"); 7189 } 7190 } 7191 } 7192 } 7193 7194 // Request the ActivityManager to kill the process(only for existing packages) 7195 // so that we do not end up in a confused state while the user is still using the older 7196 // version of the application while the new one gets installed. 7197 if ((scanFlags & SCAN_REPLACING) != 0) { 7198 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7199 7200 killApplication(pkg.applicationInfo.packageName, 7201 pkg.applicationInfo.uid, "replace pkg"); 7202 7203 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7204 } 7205 7206 // Also need to kill any apps that are dependent on the library. 7207 if (clientLibPkgs != null) { 7208 for (int i=0; i<clientLibPkgs.size(); i++) { 7209 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7210 killApplication(clientPkg.applicationInfo.packageName, 7211 clientPkg.applicationInfo.uid, "update lib"); 7212 } 7213 } 7214 7215 // Make sure we're not adding any bogus keyset info 7216 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7217 ksms.assertScannedPackageValid(pkg); 7218 7219 // writer 7220 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7221 7222 boolean createIdmapFailed = false; 7223 synchronized (mPackages) { 7224 // We don't expect installation to fail beyond this point 7225 7226 // Add the new setting to mSettings 7227 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7228 // Add the new setting to mPackages 7229 mPackages.put(pkg.applicationInfo.packageName, pkg); 7230 // Make sure we don't accidentally delete its data. 7231 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7232 while (iter.hasNext()) { 7233 PackageCleanItem item = iter.next(); 7234 if (pkgName.equals(item.packageName)) { 7235 iter.remove(); 7236 } 7237 } 7238 7239 // Take care of first install / last update times. 7240 if (currentTime != 0) { 7241 if (pkgSetting.firstInstallTime == 0) { 7242 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7243 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7244 pkgSetting.lastUpdateTime = currentTime; 7245 } 7246 } else if (pkgSetting.firstInstallTime == 0) { 7247 // We need *something*. Take time time stamp of the file. 7248 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7249 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7250 if (scanFileTime != pkgSetting.timeStamp) { 7251 // A package on the system image has changed; consider this 7252 // to be an update. 7253 pkgSetting.lastUpdateTime = scanFileTime; 7254 } 7255 } 7256 7257 // Add the package's KeySets to the global KeySetManagerService 7258 ksms.addScannedPackageLPw(pkg); 7259 7260 int N = pkg.providers.size(); 7261 StringBuilder r = null; 7262 int i; 7263 for (i=0; i<N; i++) { 7264 PackageParser.Provider p = pkg.providers.get(i); 7265 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7266 p.info.processName, pkg.applicationInfo.uid); 7267 mProviders.addProvider(p); 7268 p.syncable = p.info.isSyncable; 7269 if (p.info.authority != null) { 7270 String names[] = p.info.authority.split(";"); 7271 p.info.authority = null; 7272 for (int j = 0; j < names.length; j++) { 7273 if (j == 1 && p.syncable) { 7274 // We only want the first authority for a provider to possibly be 7275 // syncable, so if we already added this provider using a different 7276 // authority clear the syncable flag. We copy the provider before 7277 // changing it because the mProviders object contains a reference 7278 // to a provider that we don't want to change. 7279 // Only do this for the second authority since the resulting provider 7280 // object can be the same for all future authorities for this provider. 7281 p = new PackageParser.Provider(p); 7282 p.syncable = false; 7283 } 7284 if (!mProvidersByAuthority.containsKey(names[j])) { 7285 mProvidersByAuthority.put(names[j], p); 7286 if (p.info.authority == null) { 7287 p.info.authority = names[j]; 7288 } else { 7289 p.info.authority = p.info.authority + ";" + names[j]; 7290 } 7291 if (DEBUG_PACKAGE_SCANNING) { 7292 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7293 Log.d(TAG, "Registered content provider: " + names[j] 7294 + ", className = " + p.info.name + ", isSyncable = " 7295 + p.info.isSyncable); 7296 } 7297 } else { 7298 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7299 Slog.w(TAG, "Skipping provider name " + names[j] + 7300 " (in package " + pkg.applicationInfo.packageName + 7301 "): name already used by " 7302 + ((other != null && other.getComponentName() != null) 7303 ? other.getComponentName().getPackageName() : "?")); 7304 } 7305 } 7306 } 7307 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7308 if (r == null) { 7309 r = new StringBuilder(256); 7310 } else { 7311 r.append(' '); 7312 } 7313 r.append(p.info.name); 7314 } 7315 } 7316 if (r != null) { 7317 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7318 } 7319 7320 N = pkg.services.size(); 7321 r = null; 7322 for (i=0; i<N; i++) { 7323 PackageParser.Service s = pkg.services.get(i); 7324 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7325 s.info.processName, pkg.applicationInfo.uid); 7326 mServices.addService(s); 7327 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7328 if (r == null) { 7329 r = new StringBuilder(256); 7330 } else { 7331 r.append(' '); 7332 } 7333 r.append(s.info.name); 7334 } 7335 } 7336 if (r != null) { 7337 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7338 } 7339 7340 N = pkg.receivers.size(); 7341 r = null; 7342 for (i=0; i<N; i++) { 7343 PackageParser.Activity a = pkg.receivers.get(i); 7344 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7345 a.info.processName, pkg.applicationInfo.uid); 7346 mReceivers.addActivity(a, "receiver"); 7347 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7348 if (r == null) { 7349 r = new StringBuilder(256); 7350 } else { 7351 r.append(' '); 7352 } 7353 r.append(a.info.name); 7354 } 7355 } 7356 if (r != null) { 7357 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7358 } 7359 7360 N = pkg.activities.size(); 7361 r = null; 7362 for (i=0; i<N; i++) { 7363 PackageParser.Activity a = pkg.activities.get(i); 7364 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7365 a.info.processName, pkg.applicationInfo.uid); 7366 mActivities.addActivity(a, "activity"); 7367 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7368 if (r == null) { 7369 r = new StringBuilder(256); 7370 } else { 7371 r.append(' '); 7372 } 7373 r.append(a.info.name); 7374 } 7375 } 7376 if (r != null) { 7377 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7378 } 7379 7380 N = pkg.permissionGroups.size(); 7381 r = null; 7382 for (i=0; i<N; i++) { 7383 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7384 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7385 if (cur == null) { 7386 mPermissionGroups.put(pg.info.name, pg); 7387 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7388 if (r == null) { 7389 r = new StringBuilder(256); 7390 } else { 7391 r.append(' '); 7392 } 7393 r.append(pg.info.name); 7394 } 7395 } else { 7396 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7397 + pg.info.packageName + " ignored: original from " 7398 + cur.info.packageName); 7399 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7400 if (r == null) { 7401 r = new StringBuilder(256); 7402 } else { 7403 r.append(' '); 7404 } 7405 r.append("DUP:"); 7406 r.append(pg.info.name); 7407 } 7408 } 7409 } 7410 if (r != null) { 7411 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7412 } 7413 7414 N = pkg.permissions.size(); 7415 r = null; 7416 for (i=0; i<N; i++) { 7417 PackageParser.Permission p = pkg.permissions.get(i); 7418 7419 // Assume by default that we did not install this permission into the system. 7420 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7421 7422 // Now that permission groups have a special meaning, we ignore permission 7423 // groups for legacy apps to prevent unexpected behavior. In particular, 7424 // permissions for one app being granted to someone just becuase they happen 7425 // to be in a group defined by another app (before this had no implications). 7426 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7427 p.group = mPermissionGroups.get(p.info.group); 7428 // Warn for a permission in an unknown group. 7429 if (p.info.group != null && p.group == null) { 7430 Slog.w(TAG, "Permission " + p.info.name + " from package " 7431 + p.info.packageName + " in an unknown group " + p.info.group); 7432 } 7433 } 7434 7435 ArrayMap<String, BasePermission> permissionMap = 7436 p.tree ? mSettings.mPermissionTrees 7437 : mSettings.mPermissions; 7438 BasePermission bp = permissionMap.get(p.info.name); 7439 7440 // Allow system apps to redefine non-system permissions 7441 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7442 final boolean currentOwnerIsSystem = (bp.perm != null 7443 && isSystemApp(bp.perm.owner)); 7444 if (isSystemApp(p.owner)) { 7445 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7446 // It's a built-in permission and no owner, take ownership now 7447 bp.packageSetting = pkgSetting; 7448 bp.perm = p; 7449 bp.uid = pkg.applicationInfo.uid; 7450 bp.sourcePackage = p.info.packageName; 7451 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7452 } else if (!currentOwnerIsSystem) { 7453 String msg = "New decl " + p.owner + " of permission " 7454 + p.info.name + " is system; overriding " + bp.sourcePackage; 7455 reportSettingsProblem(Log.WARN, msg); 7456 bp = null; 7457 } 7458 } 7459 } 7460 7461 if (bp == null) { 7462 bp = new BasePermission(p.info.name, p.info.packageName, 7463 BasePermission.TYPE_NORMAL); 7464 permissionMap.put(p.info.name, bp); 7465 } 7466 7467 if (bp.perm == null) { 7468 if (bp.sourcePackage == null 7469 || bp.sourcePackage.equals(p.info.packageName)) { 7470 BasePermission tree = findPermissionTreeLP(p.info.name); 7471 if (tree == null 7472 || tree.sourcePackage.equals(p.info.packageName)) { 7473 bp.packageSetting = pkgSetting; 7474 bp.perm = p; 7475 bp.uid = pkg.applicationInfo.uid; 7476 bp.sourcePackage = p.info.packageName; 7477 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7478 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7479 if (r == null) { 7480 r = new StringBuilder(256); 7481 } else { 7482 r.append(' '); 7483 } 7484 r.append(p.info.name); 7485 } 7486 } else { 7487 Slog.w(TAG, "Permission " + p.info.name + " from package " 7488 + p.info.packageName + " ignored: base tree " 7489 + tree.name + " is from package " 7490 + tree.sourcePackage); 7491 } 7492 } else { 7493 Slog.w(TAG, "Permission " + p.info.name + " from package " 7494 + p.info.packageName + " ignored: original from " 7495 + bp.sourcePackage); 7496 } 7497 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7498 if (r == null) { 7499 r = new StringBuilder(256); 7500 } else { 7501 r.append(' '); 7502 } 7503 r.append("DUP:"); 7504 r.append(p.info.name); 7505 } 7506 if (bp.perm == p) { 7507 bp.protectionLevel = p.info.protectionLevel; 7508 } 7509 } 7510 7511 if (r != null) { 7512 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7513 } 7514 7515 N = pkg.instrumentation.size(); 7516 r = null; 7517 for (i=0; i<N; i++) { 7518 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7519 a.info.packageName = pkg.applicationInfo.packageName; 7520 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7521 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7522 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7523 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7524 a.info.dataDir = pkg.applicationInfo.dataDir; 7525 7526 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7527 // need other information about the application, like the ABI and what not ? 7528 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7529 mInstrumentation.put(a.getComponentName(), a); 7530 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7531 if (r == null) { 7532 r = new StringBuilder(256); 7533 } else { 7534 r.append(' '); 7535 } 7536 r.append(a.info.name); 7537 } 7538 } 7539 if (r != null) { 7540 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7541 } 7542 7543 if (pkg.protectedBroadcasts != null) { 7544 N = pkg.protectedBroadcasts.size(); 7545 for (i=0; i<N; i++) { 7546 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7547 } 7548 } 7549 7550 pkgSetting.setTimeStamp(scanFileTime); 7551 7552 // Create idmap files for pairs of (packages, overlay packages). 7553 // Note: "android", ie framework-res.apk, is handled by native layers. 7554 if (pkg.mOverlayTarget != null) { 7555 // This is an overlay package. 7556 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7557 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7558 mOverlays.put(pkg.mOverlayTarget, 7559 new ArrayMap<String, PackageParser.Package>()); 7560 } 7561 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7562 map.put(pkg.packageName, pkg); 7563 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7564 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7565 createIdmapFailed = true; 7566 } 7567 } 7568 } else if (mOverlays.containsKey(pkg.packageName) && 7569 !pkg.packageName.equals("android")) { 7570 // This is a regular package, with one or more known overlay packages. 7571 createIdmapsForPackageLI(pkg); 7572 } 7573 } 7574 7575 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7576 7577 if (createIdmapFailed) { 7578 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7579 "scanPackageLI failed to createIdmap"); 7580 } 7581 return pkg; 7582 } 7583 7584 /** 7585 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7586 * is derived purely on the basis of the contents of {@code scanFile} and 7587 * {@code cpuAbiOverride}. 7588 * 7589 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7590 */ 7591 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7592 String cpuAbiOverride, boolean extractLibs) 7593 throws PackageManagerException { 7594 // TODO: We can probably be smarter about this stuff. For installed apps, 7595 // we can calculate this information at install time once and for all. For 7596 // system apps, we can probably assume that this information doesn't change 7597 // after the first boot scan. As things stand, we do lots of unnecessary work. 7598 7599 // Give ourselves some initial paths; we'll come back for another 7600 // pass once we've determined ABI below. 7601 setNativeLibraryPaths(pkg); 7602 7603 // We would never need to extract libs for forward-locked and external packages, 7604 // since the container service will do it for us. We shouldn't attempt to 7605 // extract libs from system app when it was not updated. 7606 if (pkg.isForwardLocked() || isExternal(pkg) || 7607 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7608 extractLibs = false; 7609 } 7610 7611 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7612 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7613 7614 NativeLibraryHelper.Handle handle = null; 7615 try { 7616 handle = NativeLibraryHelper.Handle.create(pkg); 7617 // TODO(multiArch): This can be null for apps that didn't go through the 7618 // usual installation process. We can calculate it again, like we 7619 // do during install time. 7620 // 7621 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7622 // unnecessary. 7623 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7624 7625 // Null out the abis so that they can be recalculated. 7626 pkg.applicationInfo.primaryCpuAbi = null; 7627 pkg.applicationInfo.secondaryCpuAbi = null; 7628 if (isMultiArch(pkg.applicationInfo)) { 7629 // Warn if we've set an abiOverride for multi-lib packages.. 7630 // By definition, we need to copy both 32 and 64 bit libraries for 7631 // such packages. 7632 if (pkg.cpuAbiOverride != null 7633 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7634 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7635 } 7636 7637 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7638 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7639 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7640 if (extractLibs) { 7641 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7642 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7643 useIsaSpecificSubdirs); 7644 } else { 7645 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7646 } 7647 } 7648 7649 maybeThrowExceptionForMultiArchCopy( 7650 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7651 7652 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7653 if (extractLibs) { 7654 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7655 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7656 useIsaSpecificSubdirs); 7657 } else { 7658 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7659 } 7660 } 7661 7662 maybeThrowExceptionForMultiArchCopy( 7663 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7664 7665 if (abi64 >= 0) { 7666 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7667 } 7668 7669 if (abi32 >= 0) { 7670 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7671 if (abi64 >= 0) { 7672 pkg.applicationInfo.secondaryCpuAbi = abi; 7673 } else { 7674 pkg.applicationInfo.primaryCpuAbi = abi; 7675 } 7676 } 7677 } else { 7678 String[] abiList = (cpuAbiOverride != null) ? 7679 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7680 7681 // Enable gross and lame hacks for apps that are built with old 7682 // SDK tools. We must scan their APKs for renderscript bitcode and 7683 // not launch them if it's present. Don't bother checking on devices 7684 // that don't have 64 bit support. 7685 boolean needsRenderScriptOverride = false; 7686 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7687 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7688 abiList = Build.SUPPORTED_32_BIT_ABIS; 7689 needsRenderScriptOverride = true; 7690 } 7691 7692 final int copyRet; 7693 if (extractLibs) { 7694 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7695 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7696 } else { 7697 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7698 } 7699 7700 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7701 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7702 "Error unpackaging native libs for app, errorCode=" + copyRet); 7703 } 7704 7705 if (copyRet >= 0) { 7706 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7707 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7708 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7709 } else if (needsRenderScriptOverride) { 7710 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7711 } 7712 } 7713 } catch (IOException ioe) { 7714 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7715 } finally { 7716 IoUtils.closeQuietly(handle); 7717 } 7718 7719 // Now that we've calculated the ABIs and determined if it's an internal app, 7720 // we will go ahead and populate the nativeLibraryPath. 7721 setNativeLibraryPaths(pkg); 7722 } 7723 7724 /** 7725 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7726 * i.e, so that all packages can be run inside a single process if required. 7727 * 7728 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7729 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7730 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7731 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7732 * updating a package that belongs to a shared user. 7733 * 7734 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7735 * adds unnecessary complexity. 7736 */ 7737 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7738 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7739 String requiredInstructionSet = null; 7740 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7741 requiredInstructionSet = VMRuntime.getInstructionSet( 7742 scannedPackage.applicationInfo.primaryCpuAbi); 7743 } 7744 7745 PackageSetting requirer = null; 7746 for (PackageSetting ps : packagesForUser) { 7747 // If packagesForUser contains scannedPackage, we skip it. This will happen 7748 // when scannedPackage is an update of an existing package. Without this check, 7749 // we will never be able to change the ABI of any package belonging to a shared 7750 // user, even if it's compatible with other packages. 7751 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7752 if (ps.primaryCpuAbiString == null) { 7753 continue; 7754 } 7755 7756 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7757 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7758 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7759 // this but there's not much we can do. 7760 String errorMessage = "Instruction set mismatch, " 7761 + ((requirer == null) ? "[caller]" : requirer) 7762 + " requires " + requiredInstructionSet + " whereas " + ps 7763 + " requires " + instructionSet; 7764 Slog.w(TAG, errorMessage); 7765 } 7766 7767 if (requiredInstructionSet == null) { 7768 requiredInstructionSet = instructionSet; 7769 requirer = ps; 7770 } 7771 } 7772 } 7773 7774 if (requiredInstructionSet != null) { 7775 String adjustedAbi; 7776 if (requirer != null) { 7777 // requirer != null implies that either scannedPackage was null or that scannedPackage 7778 // did not require an ABI, in which case we have to adjust scannedPackage to match 7779 // the ABI of the set (which is the same as requirer's ABI) 7780 adjustedAbi = requirer.primaryCpuAbiString; 7781 if (scannedPackage != null) { 7782 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7783 } 7784 } else { 7785 // requirer == null implies that we're updating all ABIs in the set to 7786 // match scannedPackage. 7787 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7788 } 7789 7790 for (PackageSetting ps : packagesForUser) { 7791 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7792 if (ps.primaryCpuAbiString != null) { 7793 continue; 7794 } 7795 7796 ps.primaryCpuAbiString = adjustedAbi; 7797 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7798 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7799 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7800 7801 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7802 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7803 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7804 ps.primaryCpuAbiString = null; 7805 ps.pkg.applicationInfo.primaryCpuAbi = null; 7806 return; 7807 } else { 7808 mInstaller.rmdex(ps.codePathString, 7809 getDexCodeInstructionSet(getPreferredInstructionSet())); 7810 } 7811 } 7812 } 7813 } 7814 } 7815 } 7816 7817 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7818 synchronized (mPackages) { 7819 mResolverReplaced = true; 7820 // Set up information for custom user intent resolution activity. 7821 mResolveActivity.applicationInfo = pkg.applicationInfo; 7822 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7823 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7824 mResolveActivity.processName = pkg.applicationInfo.packageName; 7825 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7826 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7827 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7828 mResolveActivity.theme = 0; 7829 mResolveActivity.exported = true; 7830 mResolveActivity.enabled = true; 7831 mResolveInfo.activityInfo = mResolveActivity; 7832 mResolveInfo.priority = 0; 7833 mResolveInfo.preferredOrder = 0; 7834 mResolveInfo.match = 0; 7835 mResolveComponentName = mCustomResolverComponentName; 7836 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7837 mResolveComponentName); 7838 } 7839 } 7840 7841 private static String calculateBundledApkRoot(final String codePathString) { 7842 final File codePath = new File(codePathString); 7843 final File codeRoot; 7844 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7845 codeRoot = Environment.getRootDirectory(); 7846 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7847 codeRoot = Environment.getOemDirectory(); 7848 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7849 codeRoot = Environment.getVendorDirectory(); 7850 } else { 7851 // Unrecognized code path; take its top real segment as the apk root: 7852 // e.g. /something/app/blah.apk => /something 7853 try { 7854 File f = codePath.getCanonicalFile(); 7855 File parent = f.getParentFile(); // non-null because codePath is a file 7856 File tmp; 7857 while ((tmp = parent.getParentFile()) != null) { 7858 f = parent; 7859 parent = tmp; 7860 } 7861 codeRoot = f; 7862 Slog.w(TAG, "Unrecognized code path " 7863 + codePath + " - using " + codeRoot); 7864 } catch (IOException e) { 7865 // Can't canonicalize the code path -- shenanigans? 7866 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7867 return Environment.getRootDirectory().getPath(); 7868 } 7869 } 7870 return codeRoot.getPath(); 7871 } 7872 7873 /** 7874 * Derive and set the location of native libraries for the given package, 7875 * which varies depending on where and how the package was installed. 7876 */ 7877 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7878 final ApplicationInfo info = pkg.applicationInfo; 7879 final String codePath = pkg.codePath; 7880 final File codeFile = new File(codePath); 7881 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7882 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7883 7884 info.nativeLibraryRootDir = null; 7885 info.nativeLibraryRootRequiresIsa = false; 7886 info.nativeLibraryDir = null; 7887 info.secondaryNativeLibraryDir = null; 7888 7889 if (isApkFile(codeFile)) { 7890 // Monolithic install 7891 if (bundledApp) { 7892 // If "/system/lib64/apkname" exists, assume that is the per-package 7893 // native library directory to use; otherwise use "/system/lib/apkname". 7894 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7895 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7896 getPrimaryInstructionSet(info)); 7897 7898 // This is a bundled system app so choose the path based on the ABI. 7899 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7900 // is just the default path. 7901 final String apkName = deriveCodePathName(codePath); 7902 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7903 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7904 apkName).getAbsolutePath(); 7905 7906 if (info.secondaryCpuAbi != null) { 7907 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7908 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7909 secondaryLibDir, apkName).getAbsolutePath(); 7910 } 7911 } else if (asecApp) { 7912 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7913 .getAbsolutePath(); 7914 } else { 7915 final String apkName = deriveCodePathName(codePath); 7916 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7917 .getAbsolutePath(); 7918 } 7919 7920 info.nativeLibraryRootRequiresIsa = false; 7921 info.nativeLibraryDir = info.nativeLibraryRootDir; 7922 } else { 7923 // Cluster install 7924 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7925 info.nativeLibraryRootRequiresIsa = true; 7926 7927 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7928 getPrimaryInstructionSet(info)).getAbsolutePath(); 7929 7930 if (info.secondaryCpuAbi != null) { 7931 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7932 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7933 } 7934 } 7935 } 7936 7937 /** 7938 * Calculate the abis and roots for a bundled app. These can uniquely 7939 * be determined from the contents of the system partition, i.e whether 7940 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7941 * of this information, and instead assume that the system was built 7942 * sensibly. 7943 */ 7944 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7945 PackageSetting pkgSetting) { 7946 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7947 7948 // If "/system/lib64/apkname" exists, assume that is the per-package 7949 // native library directory to use; otherwise use "/system/lib/apkname". 7950 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7951 setBundledAppAbi(pkg, apkRoot, apkName); 7952 // pkgSetting might be null during rescan following uninstall of updates 7953 // to a bundled app, so accommodate that possibility. The settings in 7954 // that case will be established later from the parsed package. 7955 // 7956 // If the settings aren't null, sync them up with what we've just derived. 7957 // note that apkRoot isn't stored in the package settings. 7958 if (pkgSetting != null) { 7959 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7960 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7961 } 7962 } 7963 7964 /** 7965 * Deduces the ABI of a bundled app and sets the relevant fields on the 7966 * parsed pkg object. 7967 * 7968 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7969 * under which system libraries are installed. 7970 * @param apkName the name of the installed package. 7971 */ 7972 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7973 final File codeFile = new File(pkg.codePath); 7974 7975 final boolean has64BitLibs; 7976 final boolean has32BitLibs; 7977 if (isApkFile(codeFile)) { 7978 // Monolithic install 7979 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7980 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7981 } else { 7982 // Cluster install 7983 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7984 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7985 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7986 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7987 has64BitLibs = (new File(rootDir, isa)).exists(); 7988 } else { 7989 has64BitLibs = false; 7990 } 7991 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7992 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7993 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7994 has32BitLibs = (new File(rootDir, isa)).exists(); 7995 } else { 7996 has32BitLibs = false; 7997 } 7998 } 7999 8000 if (has64BitLibs && !has32BitLibs) { 8001 // The package has 64 bit libs, but not 32 bit libs. Its primary 8002 // ABI should be 64 bit. We can safely assume here that the bundled 8003 // native libraries correspond to the most preferred ABI in the list. 8004 8005 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8006 pkg.applicationInfo.secondaryCpuAbi = null; 8007 } else if (has32BitLibs && !has64BitLibs) { 8008 // The package has 32 bit libs but not 64 bit libs. Its primary 8009 // ABI should be 32 bit. 8010 8011 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8012 pkg.applicationInfo.secondaryCpuAbi = null; 8013 } else if (has32BitLibs && has64BitLibs) { 8014 // The application has both 64 and 32 bit bundled libraries. We check 8015 // here that the app declares multiArch support, and warn if it doesn't. 8016 // 8017 // We will be lenient here and record both ABIs. The primary will be the 8018 // ABI that's higher on the list, i.e, a device that's configured to prefer 8019 // 64 bit apps will see a 64 bit primary ABI, 8020 8021 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8022 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8023 } 8024 8025 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8026 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8027 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8028 } else { 8029 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8030 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8031 } 8032 } else { 8033 pkg.applicationInfo.primaryCpuAbi = null; 8034 pkg.applicationInfo.secondaryCpuAbi = null; 8035 } 8036 } 8037 8038 private void killApplication(String pkgName, int appId, String reason) { 8039 // Request the ActivityManager to kill the process(only for existing packages) 8040 // so that we do not end up in a confused state while the user is still using the older 8041 // version of the application while the new one gets installed. 8042 IActivityManager am = ActivityManagerNative.getDefault(); 8043 if (am != null) { 8044 try { 8045 am.killApplicationWithAppId(pkgName, appId, reason); 8046 } catch (RemoteException e) { 8047 } 8048 } 8049 } 8050 8051 void removePackageLI(PackageSetting ps, boolean chatty) { 8052 if (DEBUG_INSTALL) { 8053 if (chatty) 8054 Log.d(TAG, "Removing package " + ps.name); 8055 } 8056 8057 // writer 8058 synchronized (mPackages) { 8059 mPackages.remove(ps.name); 8060 final PackageParser.Package pkg = ps.pkg; 8061 if (pkg != null) { 8062 cleanPackageDataStructuresLILPw(pkg, chatty); 8063 } 8064 } 8065 } 8066 8067 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8068 if (DEBUG_INSTALL) { 8069 if (chatty) 8070 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8071 } 8072 8073 // writer 8074 synchronized (mPackages) { 8075 mPackages.remove(pkg.applicationInfo.packageName); 8076 cleanPackageDataStructuresLILPw(pkg, chatty); 8077 } 8078 } 8079 8080 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8081 int N = pkg.providers.size(); 8082 StringBuilder r = null; 8083 int i; 8084 for (i=0; i<N; i++) { 8085 PackageParser.Provider p = pkg.providers.get(i); 8086 mProviders.removeProvider(p); 8087 if (p.info.authority == null) { 8088 8089 /* There was another ContentProvider with this authority when 8090 * this app was installed so this authority is null, 8091 * Ignore it as we don't have to unregister the provider. 8092 */ 8093 continue; 8094 } 8095 String names[] = p.info.authority.split(";"); 8096 for (int j = 0; j < names.length; j++) { 8097 if (mProvidersByAuthority.get(names[j]) == p) { 8098 mProvidersByAuthority.remove(names[j]); 8099 if (DEBUG_REMOVE) { 8100 if (chatty) 8101 Log.d(TAG, "Unregistered content provider: " + names[j] 8102 + ", className = " + p.info.name + ", isSyncable = " 8103 + p.info.isSyncable); 8104 } 8105 } 8106 } 8107 if (DEBUG_REMOVE && chatty) { 8108 if (r == null) { 8109 r = new StringBuilder(256); 8110 } else { 8111 r.append(' '); 8112 } 8113 r.append(p.info.name); 8114 } 8115 } 8116 if (r != null) { 8117 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8118 } 8119 8120 N = pkg.services.size(); 8121 r = null; 8122 for (i=0; i<N; i++) { 8123 PackageParser.Service s = pkg.services.get(i); 8124 mServices.removeService(s); 8125 if (chatty) { 8126 if (r == null) { 8127 r = new StringBuilder(256); 8128 } else { 8129 r.append(' '); 8130 } 8131 r.append(s.info.name); 8132 } 8133 } 8134 if (r != null) { 8135 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8136 } 8137 8138 N = pkg.receivers.size(); 8139 r = null; 8140 for (i=0; i<N; i++) { 8141 PackageParser.Activity a = pkg.receivers.get(i); 8142 mReceivers.removeActivity(a, "receiver"); 8143 if (DEBUG_REMOVE && chatty) { 8144 if (r == null) { 8145 r = new StringBuilder(256); 8146 } else { 8147 r.append(' '); 8148 } 8149 r.append(a.info.name); 8150 } 8151 } 8152 if (r != null) { 8153 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8154 } 8155 8156 N = pkg.activities.size(); 8157 r = null; 8158 for (i=0; i<N; i++) { 8159 PackageParser.Activity a = pkg.activities.get(i); 8160 mActivities.removeActivity(a, "activity"); 8161 if (DEBUG_REMOVE && chatty) { 8162 if (r == null) { 8163 r = new StringBuilder(256); 8164 } else { 8165 r.append(' '); 8166 } 8167 r.append(a.info.name); 8168 } 8169 } 8170 if (r != null) { 8171 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8172 } 8173 8174 N = pkg.permissions.size(); 8175 r = null; 8176 for (i=0; i<N; i++) { 8177 PackageParser.Permission p = pkg.permissions.get(i); 8178 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8179 if (bp == null) { 8180 bp = mSettings.mPermissionTrees.get(p.info.name); 8181 } 8182 if (bp != null && bp.perm == p) { 8183 bp.perm = null; 8184 if (DEBUG_REMOVE && chatty) { 8185 if (r == null) { 8186 r = new StringBuilder(256); 8187 } else { 8188 r.append(' '); 8189 } 8190 r.append(p.info.name); 8191 } 8192 } 8193 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8194 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8195 if (appOpPerms != null) { 8196 appOpPerms.remove(pkg.packageName); 8197 } 8198 } 8199 } 8200 if (r != null) { 8201 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8202 } 8203 8204 N = pkg.requestedPermissions.size(); 8205 r = null; 8206 for (i=0; i<N; i++) { 8207 String perm = pkg.requestedPermissions.get(i); 8208 BasePermission bp = mSettings.mPermissions.get(perm); 8209 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8210 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8211 if (appOpPerms != null) { 8212 appOpPerms.remove(pkg.packageName); 8213 if (appOpPerms.isEmpty()) { 8214 mAppOpPermissionPackages.remove(perm); 8215 } 8216 } 8217 } 8218 } 8219 if (r != null) { 8220 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8221 } 8222 8223 N = pkg.instrumentation.size(); 8224 r = null; 8225 for (i=0; i<N; i++) { 8226 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8227 mInstrumentation.remove(a.getComponentName()); 8228 if (DEBUG_REMOVE && chatty) { 8229 if (r == null) { 8230 r = new StringBuilder(256); 8231 } else { 8232 r.append(' '); 8233 } 8234 r.append(a.info.name); 8235 } 8236 } 8237 if (r != null) { 8238 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8239 } 8240 8241 r = null; 8242 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8243 // Only system apps can hold shared libraries. 8244 if (pkg.libraryNames != null) { 8245 for (i=0; i<pkg.libraryNames.size(); i++) { 8246 String name = pkg.libraryNames.get(i); 8247 SharedLibraryEntry cur = mSharedLibraries.get(name); 8248 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8249 mSharedLibraries.remove(name); 8250 if (DEBUG_REMOVE && chatty) { 8251 if (r == null) { 8252 r = new StringBuilder(256); 8253 } else { 8254 r.append(' '); 8255 } 8256 r.append(name); 8257 } 8258 } 8259 } 8260 } 8261 } 8262 if (r != null) { 8263 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8264 } 8265 } 8266 8267 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8268 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8269 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8270 return true; 8271 } 8272 } 8273 return false; 8274 } 8275 8276 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8277 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8278 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8279 8280 private void updatePermissionsLPw(String changingPkg, 8281 PackageParser.Package pkgInfo, int flags) { 8282 // Make sure there are no dangling permission trees. 8283 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8284 while (it.hasNext()) { 8285 final BasePermission bp = it.next(); 8286 if (bp.packageSetting == null) { 8287 // We may not yet have parsed the package, so just see if 8288 // we still know about its settings. 8289 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8290 } 8291 if (bp.packageSetting == null) { 8292 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8293 + " from package " + bp.sourcePackage); 8294 it.remove(); 8295 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8296 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8297 Slog.i(TAG, "Removing old permission tree: " + bp.name 8298 + " from package " + bp.sourcePackage); 8299 flags |= UPDATE_PERMISSIONS_ALL; 8300 it.remove(); 8301 } 8302 } 8303 } 8304 8305 // Make sure all dynamic permissions have been assigned to a package, 8306 // and make sure there are no dangling permissions. 8307 it = mSettings.mPermissions.values().iterator(); 8308 while (it.hasNext()) { 8309 final BasePermission bp = it.next(); 8310 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8311 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8312 + bp.name + " pkg=" + bp.sourcePackage 8313 + " info=" + bp.pendingInfo); 8314 if (bp.packageSetting == null && bp.pendingInfo != null) { 8315 final BasePermission tree = findPermissionTreeLP(bp.name); 8316 if (tree != null && tree.perm != null) { 8317 bp.packageSetting = tree.packageSetting; 8318 bp.perm = new PackageParser.Permission(tree.perm.owner, 8319 new PermissionInfo(bp.pendingInfo)); 8320 bp.perm.info.packageName = tree.perm.info.packageName; 8321 bp.perm.info.name = bp.name; 8322 bp.uid = tree.uid; 8323 } 8324 } 8325 } 8326 if (bp.packageSetting == null) { 8327 // We may not yet have parsed the package, so just see if 8328 // we still know about its settings. 8329 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8330 } 8331 if (bp.packageSetting == null) { 8332 Slog.w(TAG, "Removing dangling permission: " + bp.name 8333 + " from package " + bp.sourcePackage); 8334 it.remove(); 8335 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8336 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8337 Slog.i(TAG, "Removing old permission: " + bp.name 8338 + " from package " + bp.sourcePackage); 8339 flags |= UPDATE_PERMISSIONS_ALL; 8340 it.remove(); 8341 } 8342 } 8343 } 8344 8345 // Now update the permissions for all packages, in particular 8346 // replace the granted permissions of the system packages. 8347 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8348 for (PackageParser.Package pkg : mPackages.values()) { 8349 if (pkg != pkgInfo) { 8350 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8351 changingPkg); 8352 } 8353 } 8354 } 8355 8356 if (pkgInfo != null) { 8357 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8358 } 8359 } 8360 8361 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8362 String packageOfInterest) { 8363 // IMPORTANT: There are two types of permissions: install and runtime. 8364 // Install time permissions are granted when the app is installed to 8365 // all device users and users added in the future. Runtime permissions 8366 // are granted at runtime explicitly to specific users. Normal and signature 8367 // protected permissions are install time permissions. Dangerous permissions 8368 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8369 // otherwise they are runtime permissions. This function does not manage 8370 // runtime permissions except for the case an app targeting Lollipop MR1 8371 // being upgraded to target a newer SDK, in which case dangerous permissions 8372 // are transformed from install time to runtime ones. 8373 8374 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8375 if (ps == null) { 8376 return; 8377 } 8378 8379 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8380 8381 PermissionsState permissionsState = ps.getPermissionsState(); 8382 PermissionsState origPermissions = permissionsState; 8383 8384 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8385 8386 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8387 8388 boolean changedInstallPermission = false; 8389 8390 if (replace) { 8391 ps.installPermissionsFixed = false; 8392 if (!ps.isSharedUser()) { 8393 origPermissions = new PermissionsState(permissionsState); 8394 permissionsState.reset(); 8395 } 8396 } 8397 8398 permissionsState.setGlobalGids(mGlobalGids); 8399 8400 final int N = pkg.requestedPermissions.size(); 8401 for (int i=0; i<N; i++) { 8402 final String name = pkg.requestedPermissions.get(i); 8403 final BasePermission bp = mSettings.mPermissions.get(name); 8404 8405 if (DEBUG_INSTALL) { 8406 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8407 } 8408 8409 if (bp == null || bp.packageSetting == null) { 8410 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8411 Slog.w(TAG, "Unknown permission " + name 8412 + " in package " + pkg.packageName); 8413 } 8414 continue; 8415 } 8416 8417 final String perm = bp.name; 8418 boolean allowedSig = false; 8419 int grant = GRANT_DENIED; 8420 8421 // Keep track of app op permissions. 8422 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8423 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8424 if (pkgs == null) { 8425 pkgs = new ArraySet<>(); 8426 mAppOpPermissionPackages.put(bp.name, pkgs); 8427 } 8428 pkgs.add(pkg.packageName); 8429 } 8430 8431 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8432 switch (level) { 8433 case PermissionInfo.PROTECTION_NORMAL: { 8434 // For all apps normal permissions are install time ones. 8435 grant = GRANT_INSTALL; 8436 } break; 8437 8438 case PermissionInfo.PROTECTION_DANGEROUS: { 8439 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8440 // For legacy apps dangerous permissions are install time ones. 8441 grant = GRANT_INSTALL_LEGACY; 8442 } else if (origPermissions.hasInstallPermission(bp.name)) { 8443 // For legacy apps that became modern, install becomes runtime. 8444 grant = GRANT_UPGRADE; 8445 } else { 8446 // For modern apps keep runtime permissions unchanged. 8447 grant = GRANT_RUNTIME; 8448 } 8449 } break; 8450 8451 case PermissionInfo.PROTECTION_SIGNATURE: { 8452 // For all apps signature permissions are install time ones. 8453 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8454 if (allowedSig) { 8455 grant = GRANT_INSTALL; 8456 } 8457 } break; 8458 } 8459 8460 if (DEBUG_INSTALL) { 8461 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8462 } 8463 8464 if (grant != GRANT_DENIED) { 8465 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8466 // If this is an existing, non-system package, then 8467 // we can't add any new permissions to it. 8468 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8469 // Except... if this is a permission that was added 8470 // to the platform (note: need to only do this when 8471 // updating the platform). 8472 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8473 grant = GRANT_DENIED; 8474 } 8475 } 8476 } 8477 8478 switch (grant) { 8479 case GRANT_INSTALL: { 8480 // Revoke this as runtime permission to handle the case of 8481 // a runtime permission being downgraded to an install one. 8482 for (int userId : UserManagerService.getInstance().getUserIds()) { 8483 if (origPermissions.getRuntimePermissionState( 8484 bp.name, userId) != null) { 8485 // Revoke the runtime permission and clear the flags. 8486 origPermissions.revokeRuntimePermission(bp, userId); 8487 origPermissions.updatePermissionFlags(bp, userId, 8488 PackageManager.MASK_PERMISSION_FLAGS, 0); 8489 // If we revoked a permission permission, we have to write. 8490 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8491 changedRuntimePermissionUserIds, userId); 8492 } 8493 } 8494 // Grant an install permission. 8495 if (permissionsState.grantInstallPermission(bp) != 8496 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8497 changedInstallPermission = true; 8498 } 8499 } break; 8500 8501 case GRANT_INSTALL_LEGACY: { 8502 // Grant an install permission. 8503 if (permissionsState.grantInstallPermission(bp) != 8504 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8505 changedInstallPermission = true; 8506 } 8507 } break; 8508 8509 case GRANT_RUNTIME: { 8510 // Grant previously granted runtime permissions. 8511 for (int userId : UserManagerService.getInstance().getUserIds()) { 8512 PermissionState permissionState = origPermissions 8513 .getRuntimePermissionState(bp.name, userId); 8514 final int flags = permissionState != null 8515 ? permissionState.getFlags() : 0; 8516 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8517 if (permissionsState.grantRuntimePermission(bp, userId) == 8518 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8519 // If we cannot put the permission as it was, we have to write. 8520 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8521 changedRuntimePermissionUserIds, userId); 8522 } 8523 } 8524 // Propagate the permission flags. 8525 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8526 } 8527 } break; 8528 8529 case GRANT_UPGRADE: { 8530 // Grant runtime permissions for a previously held install permission. 8531 PermissionState permissionState = origPermissions 8532 .getInstallPermissionState(bp.name); 8533 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8534 8535 if (origPermissions.revokeInstallPermission(bp) 8536 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8537 // We will be transferring the permission flags, so clear them. 8538 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8539 PackageManager.MASK_PERMISSION_FLAGS, 0); 8540 changedInstallPermission = true; 8541 } 8542 8543 // If the permission is not to be promoted to runtime we ignore it and 8544 // also its other flags as they are not applicable to install permissions. 8545 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8546 for (int userId : currentUserIds) { 8547 if (permissionsState.grantRuntimePermission(bp, userId) != 8548 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8549 // Transfer the permission flags. 8550 permissionsState.updatePermissionFlags(bp, userId, 8551 flags, flags); 8552 // If we granted the permission, we have to write. 8553 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8554 changedRuntimePermissionUserIds, userId); 8555 } 8556 } 8557 } 8558 } break; 8559 8560 default: { 8561 if (packageOfInterest == null 8562 || packageOfInterest.equals(pkg.packageName)) { 8563 Slog.w(TAG, "Not granting permission " + perm 8564 + " to package " + pkg.packageName 8565 + " because it was previously installed without"); 8566 } 8567 } break; 8568 } 8569 } else { 8570 if (permissionsState.revokeInstallPermission(bp) != 8571 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8572 // Also drop the permission flags. 8573 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8574 PackageManager.MASK_PERMISSION_FLAGS, 0); 8575 changedInstallPermission = true; 8576 Slog.i(TAG, "Un-granting permission " + perm 8577 + " from package " + pkg.packageName 8578 + " (protectionLevel=" + bp.protectionLevel 8579 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8580 + ")"); 8581 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8582 // Don't print warning for app op permissions, since it is fine for them 8583 // not to be granted, there is a UI for the user to decide. 8584 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8585 Slog.w(TAG, "Not granting permission " + perm 8586 + " to package " + pkg.packageName 8587 + " (protectionLevel=" + bp.protectionLevel 8588 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8589 + ")"); 8590 } 8591 } 8592 } 8593 } 8594 8595 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8596 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8597 // This is the first that we have heard about this package, so the 8598 // permissions we have now selected are fixed until explicitly 8599 // changed. 8600 ps.installPermissionsFixed = true; 8601 } 8602 8603 // Persist the runtime permissions state for users with changes. 8604 for (int userId : changedRuntimePermissionUserIds) { 8605 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8606 } 8607 8608 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8609 } 8610 8611 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8612 boolean allowed = false; 8613 final int NP = PackageParser.NEW_PERMISSIONS.length; 8614 for (int ip=0; ip<NP; ip++) { 8615 final PackageParser.NewPermissionInfo npi 8616 = PackageParser.NEW_PERMISSIONS[ip]; 8617 if (npi.name.equals(perm) 8618 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8619 allowed = true; 8620 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8621 + pkg.packageName); 8622 break; 8623 } 8624 } 8625 return allowed; 8626 } 8627 8628 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8629 BasePermission bp, PermissionsState origPermissions) { 8630 boolean allowed; 8631 allowed = (compareSignatures( 8632 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8633 == PackageManager.SIGNATURE_MATCH) 8634 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8635 == PackageManager.SIGNATURE_MATCH); 8636 if (!allowed && (bp.protectionLevel 8637 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8638 if (isSystemApp(pkg)) { 8639 // For updated system applications, a system permission 8640 // is granted only if it had been defined by the original application. 8641 if (pkg.isUpdatedSystemApp()) { 8642 final PackageSetting sysPs = mSettings 8643 .getDisabledSystemPkgLPr(pkg.packageName); 8644 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8645 // If the original was granted this permission, we take 8646 // that grant decision as read and propagate it to the 8647 // update. 8648 if (sysPs.isPrivileged()) { 8649 allowed = true; 8650 } 8651 } else { 8652 // The system apk may have been updated with an older 8653 // version of the one on the data partition, but which 8654 // granted a new system permission that it didn't have 8655 // before. In this case we do want to allow the app to 8656 // now get the new permission if the ancestral apk is 8657 // privileged to get it. 8658 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8659 for (int j=0; 8660 j<sysPs.pkg.requestedPermissions.size(); j++) { 8661 if (perm.equals( 8662 sysPs.pkg.requestedPermissions.get(j))) { 8663 allowed = true; 8664 break; 8665 } 8666 } 8667 } 8668 } 8669 } else { 8670 allowed = isPrivilegedApp(pkg); 8671 } 8672 } 8673 } 8674 if (!allowed) { 8675 if (!allowed && (bp.protectionLevel 8676 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8677 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8678 // If this was a previously normal/dangerous permission that got moved 8679 // to a system permission as part of the runtime permission redesign, then 8680 // we still want to blindly grant it to old apps. 8681 allowed = true; 8682 } 8683 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8684 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8685 // If this permission is to be granted to the system installer and 8686 // this app is an installer, then it gets the permission. 8687 allowed = true; 8688 } 8689 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8690 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8691 // If this permission is to be granted to the system verifier and 8692 // this app is a verifier, then it gets the permission. 8693 allowed = true; 8694 } 8695 if (!allowed && (bp.protectionLevel 8696 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8697 && isSystemApp(pkg)) { 8698 // Any pre-installed system app is allowed to get this permission. 8699 allowed = true; 8700 } 8701 if (!allowed && (bp.protectionLevel 8702 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8703 // For development permissions, a development permission 8704 // is granted only if it was already granted. 8705 allowed = origPermissions.hasInstallPermission(perm); 8706 } 8707 } 8708 return allowed; 8709 } 8710 8711 final class ActivityIntentResolver 8712 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8713 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8714 boolean defaultOnly, int userId) { 8715 if (!sUserManager.exists(userId)) return null; 8716 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8717 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8718 } 8719 8720 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8721 int userId) { 8722 if (!sUserManager.exists(userId)) return null; 8723 mFlags = flags; 8724 return super.queryIntent(intent, resolvedType, 8725 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8726 } 8727 8728 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8729 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8730 if (!sUserManager.exists(userId)) return null; 8731 if (packageActivities == null) { 8732 return null; 8733 } 8734 mFlags = flags; 8735 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8736 final int N = packageActivities.size(); 8737 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8738 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8739 8740 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8741 for (int i = 0; i < N; ++i) { 8742 intentFilters = packageActivities.get(i).intents; 8743 if (intentFilters != null && intentFilters.size() > 0) { 8744 PackageParser.ActivityIntentInfo[] array = 8745 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8746 intentFilters.toArray(array); 8747 listCut.add(array); 8748 } 8749 } 8750 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8751 } 8752 8753 public final void addActivity(PackageParser.Activity a, String type) { 8754 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8755 mActivities.put(a.getComponentName(), a); 8756 if (DEBUG_SHOW_INFO) 8757 Log.v( 8758 TAG, " " + type + " " + 8759 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8760 if (DEBUG_SHOW_INFO) 8761 Log.v(TAG, " Class=" + a.info.name); 8762 final int NI = a.intents.size(); 8763 for (int j=0; j<NI; j++) { 8764 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8765 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8766 intent.setPriority(0); 8767 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8768 + a.className + " with priority > 0, forcing to 0"); 8769 } 8770 if (DEBUG_SHOW_INFO) { 8771 Log.v(TAG, " IntentFilter:"); 8772 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8773 } 8774 if (!intent.debugCheck()) { 8775 Log.w(TAG, "==> For Activity " + a.info.name); 8776 } 8777 addFilter(intent); 8778 } 8779 } 8780 8781 public final void removeActivity(PackageParser.Activity a, String type) { 8782 mActivities.remove(a.getComponentName()); 8783 if (DEBUG_SHOW_INFO) { 8784 Log.v(TAG, " " + type + " " 8785 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8786 : a.info.name) + ":"); 8787 Log.v(TAG, " Class=" + a.info.name); 8788 } 8789 final int NI = a.intents.size(); 8790 for (int j=0; j<NI; j++) { 8791 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8792 if (DEBUG_SHOW_INFO) { 8793 Log.v(TAG, " IntentFilter:"); 8794 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8795 } 8796 removeFilter(intent); 8797 } 8798 } 8799 8800 @Override 8801 protected boolean allowFilterResult( 8802 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8803 ActivityInfo filterAi = filter.activity.info; 8804 for (int i=dest.size()-1; i>=0; i--) { 8805 ActivityInfo destAi = dest.get(i).activityInfo; 8806 if (destAi.name == filterAi.name 8807 && destAi.packageName == filterAi.packageName) { 8808 return false; 8809 } 8810 } 8811 return true; 8812 } 8813 8814 @Override 8815 protected ActivityIntentInfo[] newArray(int size) { 8816 return new ActivityIntentInfo[size]; 8817 } 8818 8819 @Override 8820 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8821 if (!sUserManager.exists(userId)) return true; 8822 PackageParser.Package p = filter.activity.owner; 8823 if (p != null) { 8824 PackageSetting ps = (PackageSetting)p.mExtras; 8825 if (ps != null) { 8826 // System apps are never considered stopped for purposes of 8827 // filtering, because there may be no way for the user to 8828 // actually re-launch them. 8829 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8830 && ps.getStopped(userId); 8831 } 8832 } 8833 return false; 8834 } 8835 8836 @Override 8837 protected boolean isPackageForFilter(String packageName, 8838 PackageParser.ActivityIntentInfo info) { 8839 return packageName.equals(info.activity.owner.packageName); 8840 } 8841 8842 @Override 8843 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8844 int match, int userId) { 8845 if (!sUserManager.exists(userId)) return null; 8846 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8847 return null; 8848 } 8849 final PackageParser.Activity activity = info.activity; 8850 if (mSafeMode && (activity.info.applicationInfo.flags 8851 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8852 return null; 8853 } 8854 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8855 if (ps == null) { 8856 return null; 8857 } 8858 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8859 ps.readUserState(userId), userId); 8860 if (ai == null) { 8861 return null; 8862 } 8863 final ResolveInfo res = new ResolveInfo(); 8864 res.activityInfo = ai; 8865 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8866 res.filter = info; 8867 } 8868 if (info != null) { 8869 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8870 } 8871 res.priority = info.getPriority(); 8872 res.preferredOrder = activity.owner.mPreferredOrder; 8873 //System.out.println("Result: " + res.activityInfo.className + 8874 // " = " + res.priority); 8875 res.match = match; 8876 res.isDefault = info.hasDefault; 8877 res.labelRes = info.labelRes; 8878 res.nonLocalizedLabel = info.nonLocalizedLabel; 8879 if (userNeedsBadging(userId)) { 8880 res.noResourceId = true; 8881 } else { 8882 res.icon = info.icon; 8883 } 8884 res.iconResourceId = info.icon; 8885 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8886 return res; 8887 } 8888 8889 @Override 8890 protected void sortResults(List<ResolveInfo> results) { 8891 Collections.sort(results, mResolvePrioritySorter); 8892 } 8893 8894 @Override 8895 protected void dumpFilter(PrintWriter out, String prefix, 8896 PackageParser.ActivityIntentInfo filter) { 8897 out.print(prefix); out.print( 8898 Integer.toHexString(System.identityHashCode(filter.activity))); 8899 out.print(' '); 8900 filter.activity.printComponentShortName(out); 8901 out.print(" filter "); 8902 out.println(Integer.toHexString(System.identityHashCode(filter))); 8903 } 8904 8905 @Override 8906 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8907 return filter.activity; 8908 } 8909 8910 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8911 PackageParser.Activity activity = (PackageParser.Activity)label; 8912 out.print(prefix); out.print( 8913 Integer.toHexString(System.identityHashCode(activity))); 8914 out.print(' '); 8915 activity.printComponentShortName(out); 8916 if (count > 1) { 8917 out.print(" ("); out.print(count); out.print(" filters)"); 8918 } 8919 out.println(); 8920 } 8921 8922// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8923// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8924// final List<ResolveInfo> retList = Lists.newArrayList(); 8925// while (i.hasNext()) { 8926// final ResolveInfo resolveInfo = i.next(); 8927// if (isEnabledLP(resolveInfo.activityInfo)) { 8928// retList.add(resolveInfo); 8929// } 8930// } 8931// return retList; 8932// } 8933 8934 // Keys are String (activity class name), values are Activity. 8935 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8936 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8937 private int mFlags; 8938 } 8939 8940 private final class ServiceIntentResolver 8941 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8942 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8943 boolean defaultOnly, int userId) { 8944 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8945 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8946 } 8947 8948 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8949 int userId) { 8950 if (!sUserManager.exists(userId)) return null; 8951 mFlags = flags; 8952 return super.queryIntent(intent, resolvedType, 8953 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8954 } 8955 8956 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8957 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8958 if (!sUserManager.exists(userId)) return null; 8959 if (packageServices == null) { 8960 return null; 8961 } 8962 mFlags = flags; 8963 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8964 final int N = packageServices.size(); 8965 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8966 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8967 8968 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8969 for (int i = 0; i < N; ++i) { 8970 intentFilters = packageServices.get(i).intents; 8971 if (intentFilters != null && intentFilters.size() > 0) { 8972 PackageParser.ServiceIntentInfo[] array = 8973 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8974 intentFilters.toArray(array); 8975 listCut.add(array); 8976 } 8977 } 8978 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8979 } 8980 8981 public final void addService(PackageParser.Service s) { 8982 mServices.put(s.getComponentName(), s); 8983 if (DEBUG_SHOW_INFO) { 8984 Log.v(TAG, " " 8985 + (s.info.nonLocalizedLabel != null 8986 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8987 Log.v(TAG, " Class=" + s.info.name); 8988 } 8989 final int NI = s.intents.size(); 8990 int j; 8991 for (j=0; j<NI; j++) { 8992 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8993 if (DEBUG_SHOW_INFO) { 8994 Log.v(TAG, " IntentFilter:"); 8995 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8996 } 8997 if (!intent.debugCheck()) { 8998 Log.w(TAG, "==> For Service " + s.info.name); 8999 } 9000 addFilter(intent); 9001 } 9002 } 9003 9004 public final void removeService(PackageParser.Service s) { 9005 mServices.remove(s.getComponentName()); 9006 if (DEBUG_SHOW_INFO) { 9007 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9008 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9009 Log.v(TAG, " Class=" + s.info.name); 9010 } 9011 final int NI = s.intents.size(); 9012 int j; 9013 for (j=0; j<NI; j++) { 9014 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9015 if (DEBUG_SHOW_INFO) { 9016 Log.v(TAG, " IntentFilter:"); 9017 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9018 } 9019 removeFilter(intent); 9020 } 9021 } 9022 9023 @Override 9024 protected boolean allowFilterResult( 9025 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9026 ServiceInfo filterSi = filter.service.info; 9027 for (int i=dest.size()-1; i>=0; i--) { 9028 ServiceInfo destAi = dest.get(i).serviceInfo; 9029 if (destAi.name == filterSi.name 9030 && destAi.packageName == filterSi.packageName) { 9031 return false; 9032 } 9033 } 9034 return true; 9035 } 9036 9037 @Override 9038 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9039 return new PackageParser.ServiceIntentInfo[size]; 9040 } 9041 9042 @Override 9043 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9044 if (!sUserManager.exists(userId)) return true; 9045 PackageParser.Package p = filter.service.owner; 9046 if (p != null) { 9047 PackageSetting ps = (PackageSetting)p.mExtras; 9048 if (ps != null) { 9049 // System apps are never considered stopped for purposes of 9050 // filtering, because there may be no way for the user to 9051 // actually re-launch them. 9052 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9053 && ps.getStopped(userId); 9054 } 9055 } 9056 return false; 9057 } 9058 9059 @Override 9060 protected boolean isPackageForFilter(String packageName, 9061 PackageParser.ServiceIntentInfo info) { 9062 return packageName.equals(info.service.owner.packageName); 9063 } 9064 9065 @Override 9066 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9067 int match, int userId) { 9068 if (!sUserManager.exists(userId)) return null; 9069 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9070 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9071 return null; 9072 } 9073 final PackageParser.Service service = info.service; 9074 if (mSafeMode && (service.info.applicationInfo.flags 9075 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9076 return null; 9077 } 9078 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9079 if (ps == null) { 9080 return null; 9081 } 9082 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9083 ps.readUserState(userId), userId); 9084 if (si == null) { 9085 return null; 9086 } 9087 final ResolveInfo res = new ResolveInfo(); 9088 res.serviceInfo = si; 9089 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9090 res.filter = filter; 9091 } 9092 res.priority = info.getPriority(); 9093 res.preferredOrder = service.owner.mPreferredOrder; 9094 res.match = match; 9095 res.isDefault = info.hasDefault; 9096 res.labelRes = info.labelRes; 9097 res.nonLocalizedLabel = info.nonLocalizedLabel; 9098 res.icon = info.icon; 9099 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9100 return res; 9101 } 9102 9103 @Override 9104 protected void sortResults(List<ResolveInfo> results) { 9105 Collections.sort(results, mResolvePrioritySorter); 9106 } 9107 9108 @Override 9109 protected void dumpFilter(PrintWriter out, String prefix, 9110 PackageParser.ServiceIntentInfo filter) { 9111 out.print(prefix); out.print( 9112 Integer.toHexString(System.identityHashCode(filter.service))); 9113 out.print(' '); 9114 filter.service.printComponentShortName(out); 9115 out.print(" filter "); 9116 out.println(Integer.toHexString(System.identityHashCode(filter))); 9117 } 9118 9119 @Override 9120 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9121 return filter.service; 9122 } 9123 9124 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9125 PackageParser.Service service = (PackageParser.Service)label; 9126 out.print(prefix); out.print( 9127 Integer.toHexString(System.identityHashCode(service))); 9128 out.print(' '); 9129 service.printComponentShortName(out); 9130 if (count > 1) { 9131 out.print(" ("); out.print(count); out.print(" filters)"); 9132 } 9133 out.println(); 9134 } 9135 9136// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9137// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9138// final List<ResolveInfo> retList = Lists.newArrayList(); 9139// while (i.hasNext()) { 9140// final ResolveInfo resolveInfo = (ResolveInfo) i; 9141// if (isEnabledLP(resolveInfo.serviceInfo)) { 9142// retList.add(resolveInfo); 9143// } 9144// } 9145// return retList; 9146// } 9147 9148 // Keys are String (activity class name), values are Activity. 9149 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9150 = new ArrayMap<ComponentName, PackageParser.Service>(); 9151 private int mFlags; 9152 }; 9153 9154 private final class ProviderIntentResolver 9155 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9156 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9157 boolean defaultOnly, int userId) { 9158 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9159 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9160 } 9161 9162 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9163 int userId) { 9164 if (!sUserManager.exists(userId)) 9165 return null; 9166 mFlags = flags; 9167 return super.queryIntent(intent, resolvedType, 9168 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9169 } 9170 9171 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9172 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9173 if (!sUserManager.exists(userId)) 9174 return null; 9175 if (packageProviders == null) { 9176 return null; 9177 } 9178 mFlags = flags; 9179 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9180 final int N = packageProviders.size(); 9181 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9182 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9183 9184 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9185 for (int i = 0; i < N; ++i) { 9186 intentFilters = packageProviders.get(i).intents; 9187 if (intentFilters != null && intentFilters.size() > 0) { 9188 PackageParser.ProviderIntentInfo[] array = 9189 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9190 intentFilters.toArray(array); 9191 listCut.add(array); 9192 } 9193 } 9194 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9195 } 9196 9197 public final void addProvider(PackageParser.Provider p) { 9198 if (mProviders.containsKey(p.getComponentName())) { 9199 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9200 return; 9201 } 9202 9203 mProviders.put(p.getComponentName(), p); 9204 if (DEBUG_SHOW_INFO) { 9205 Log.v(TAG, " " 9206 + (p.info.nonLocalizedLabel != null 9207 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9208 Log.v(TAG, " Class=" + p.info.name); 9209 } 9210 final int NI = p.intents.size(); 9211 int j; 9212 for (j = 0; j < NI; j++) { 9213 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9214 if (DEBUG_SHOW_INFO) { 9215 Log.v(TAG, " IntentFilter:"); 9216 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9217 } 9218 if (!intent.debugCheck()) { 9219 Log.w(TAG, "==> For Provider " + p.info.name); 9220 } 9221 addFilter(intent); 9222 } 9223 } 9224 9225 public final void removeProvider(PackageParser.Provider p) { 9226 mProviders.remove(p.getComponentName()); 9227 if (DEBUG_SHOW_INFO) { 9228 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9229 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9230 Log.v(TAG, " Class=" + p.info.name); 9231 } 9232 final int NI = p.intents.size(); 9233 int j; 9234 for (j = 0; j < NI; j++) { 9235 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9236 if (DEBUG_SHOW_INFO) { 9237 Log.v(TAG, " IntentFilter:"); 9238 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9239 } 9240 removeFilter(intent); 9241 } 9242 } 9243 9244 @Override 9245 protected boolean allowFilterResult( 9246 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9247 ProviderInfo filterPi = filter.provider.info; 9248 for (int i = dest.size() - 1; i >= 0; i--) { 9249 ProviderInfo destPi = dest.get(i).providerInfo; 9250 if (destPi.name == filterPi.name 9251 && destPi.packageName == filterPi.packageName) { 9252 return false; 9253 } 9254 } 9255 return true; 9256 } 9257 9258 @Override 9259 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9260 return new PackageParser.ProviderIntentInfo[size]; 9261 } 9262 9263 @Override 9264 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9265 if (!sUserManager.exists(userId)) 9266 return true; 9267 PackageParser.Package p = filter.provider.owner; 9268 if (p != null) { 9269 PackageSetting ps = (PackageSetting) p.mExtras; 9270 if (ps != null) { 9271 // System apps are never considered stopped for purposes of 9272 // filtering, because there may be no way for the user to 9273 // actually re-launch them. 9274 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9275 && ps.getStopped(userId); 9276 } 9277 } 9278 return false; 9279 } 9280 9281 @Override 9282 protected boolean isPackageForFilter(String packageName, 9283 PackageParser.ProviderIntentInfo info) { 9284 return packageName.equals(info.provider.owner.packageName); 9285 } 9286 9287 @Override 9288 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9289 int match, int userId) { 9290 if (!sUserManager.exists(userId)) 9291 return null; 9292 final PackageParser.ProviderIntentInfo info = filter; 9293 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9294 return null; 9295 } 9296 final PackageParser.Provider provider = info.provider; 9297 if (mSafeMode && (provider.info.applicationInfo.flags 9298 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9299 return null; 9300 } 9301 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9302 if (ps == null) { 9303 return null; 9304 } 9305 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9306 ps.readUserState(userId), userId); 9307 if (pi == null) { 9308 return null; 9309 } 9310 final ResolveInfo res = new ResolveInfo(); 9311 res.providerInfo = pi; 9312 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9313 res.filter = filter; 9314 } 9315 res.priority = info.getPriority(); 9316 res.preferredOrder = provider.owner.mPreferredOrder; 9317 res.match = match; 9318 res.isDefault = info.hasDefault; 9319 res.labelRes = info.labelRes; 9320 res.nonLocalizedLabel = info.nonLocalizedLabel; 9321 res.icon = info.icon; 9322 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9323 return res; 9324 } 9325 9326 @Override 9327 protected void sortResults(List<ResolveInfo> results) { 9328 Collections.sort(results, mResolvePrioritySorter); 9329 } 9330 9331 @Override 9332 protected void dumpFilter(PrintWriter out, String prefix, 9333 PackageParser.ProviderIntentInfo filter) { 9334 out.print(prefix); 9335 out.print( 9336 Integer.toHexString(System.identityHashCode(filter.provider))); 9337 out.print(' '); 9338 filter.provider.printComponentShortName(out); 9339 out.print(" filter "); 9340 out.println(Integer.toHexString(System.identityHashCode(filter))); 9341 } 9342 9343 @Override 9344 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9345 return filter.provider; 9346 } 9347 9348 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9349 PackageParser.Provider provider = (PackageParser.Provider)label; 9350 out.print(prefix); out.print( 9351 Integer.toHexString(System.identityHashCode(provider))); 9352 out.print(' '); 9353 provider.printComponentShortName(out); 9354 if (count > 1) { 9355 out.print(" ("); out.print(count); out.print(" filters)"); 9356 } 9357 out.println(); 9358 } 9359 9360 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9361 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9362 private int mFlags; 9363 }; 9364 9365 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9366 new Comparator<ResolveInfo>() { 9367 public int compare(ResolveInfo r1, ResolveInfo r2) { 9368 int v1 = r1.priority; 9369 int v2 = r2.priority; 9370 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9371 if (v1 != v2) { 9372 return (v1 > v2) ? -1 : 1; 9373 } 9374 v1 = r1.preferredOrder; 9375 v2 = r2.preferredOrder; 9376 if (v1 != v2) { 9377 return (v1 > v2) ? -1 : 1; 9378 } 9379 if (r1.isDefault != r2.isDefault) { 9380 return r1.isDefault ? -1 : 1; 9381 } 9382 v1 = r1.match; 9383 v2 = r2.match; 9384 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9385 if (v1 != v2) { 9386 return (v1 > v2) ? -1 : 1; 9387 } 9388 if (r1.system != r2.system) { 9389 return r1.system ? -1 : 1; 9390 } 9391 return 0; 9392 } 9393 }; 9394 9395 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9396 new Comparator<ProviderInfo>() { 9397 public int compare(ProviderInfo p1, ProviderInfo p2) { 9398 final int v1 = p1.initOrder; 9399 final int v2 = p2.initOrder; 9400 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9401 } 9402 }; 9403 9404 final void sendPackageBroadcast(final String action, final String pkg, 9405 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9406 final int[] userIds) { 9407 mHandler.post(new Runnable() { 9408 @Override 9409 public void run() { 9410 try { 9411 final IActivityManager am = ActivityManagerNative.getDefault(); 9412 if (am == null) return; 9413 final int[] resolvedUserIds; 9414 if (userIds == null) { 9415 resolvedUserIds = am.getRunningUserIds(); 9416 } else { 9417 resolvedUserIds = userIds; 9418 } 9419 for (int id : resolvedUserIds) { 9420 final Intent intent = new Intent(action, 9421 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9422 if (extras != null) { 9423 intent.putExtras(extras); 9424 } 9425 if (targetPkg != null) { 9426 intent.setPackage(targetPkg); 9427 } 9428 // Modify the UID when posting to other users 9429 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9430 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9431 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9432 intent.putExtra(Intent.EXTRA_UID, uid); 9433 } 9434 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9435 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9436 if (DEBUG_BROADCASTS) { 9437 RuntimeException here = new RuntimeException("here"); 9438 here.fillInStackTrace(); 9439 Slog.d(TAG, "Sending to user " + id + ": " 9440 + intent.toShortString(false, true, false, false) 9441 + " " + intent.getExtras(), here); 9442 } 9443 am.broadcastIntent(null, intent, null, finishedReceiver, 9444 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9445 null, finishedReceiver != null, false, id); 9446 } 9447 } catch (RemoteException ex) { 9448 } 9449 } 9450 }); 9451 } 9452 9453 /** 9454 * Check if the external storage media is available. This is true if there 9455 * is a mounted external storage medium or if the external storage is 9456 * emulated. 9457 */ 9458 private boolean isExternalMediaAvailable() { 9459 return mMediaMounted || Environment.isExternalStorageEmulated(); 9460 } 9461 9462 @Override 9463 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9464 // writer 9465 synchronized (mPackages) { 9466 if (!isExternalMediaAvailable()) { 9467 // If the external storage is no longer mounted at this point, 9468 // the caller may not have been able to delete all of this 9469 // packages files and can not delete any more. Bail. 9470 return null; 9471 } 9472 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9473 if (lastPackage != null) { 9474 pkgs.remove(lastPackage); 9475 } 9476 if (pkgs.size() > 0) { 9477 return pkgs.get(0); 9478 } 9479 } 9480 return null; 9481 } 9482 9483 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9484 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9485 userId, andCode ? 1 : 0, packageName); 9486 if (mSystemReady) { 9487 msg.sendToTarget(); 9488 } else { 9489 if (mPostSystemReadyMessages == null) { 9490 mPostSystemReadyMessages = new ArrayList<>(); 9491 } 9492 mPostSystemReadyMessages.add(msg); 9493 } 9494 } 9495 9496 void startCleaningPackages() { 9497 // reader 9498 synchronized (mPackages) { 9499 if (!isExternalMediaAvailable()) { 9500 return; 9501 } 9502 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9503 return; 9504 } 9505 } 9506 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9507 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9508 IActivityManager am = ActivityManagerNative.getDefault(); 9509 if (am != null) { 9510 try { 9511 am.startService(null, intent, null, mContext.getOpPackageName(), 9512 UserHandle.USER_OWNER); 9513 } catch (RemoteException e) { 9514 } 9515 } 9516 } 9517 9518 @Override 9519 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9520 int installFlags, String installerPackageName, VerificationParams verificationParams, 9521 String packageAbiOverride) { 9522 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9523 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9524 } 9525 9526 @Override 9527 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9528 int installFlags, String installerPackageName, VerificationParams verificationParams, 9529 String packageAbiOverride, int userId) { 9530 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9531 9532 final int callingUid = Binder.getCallingUid(); 9533 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9534 9535 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9536 try { 9537 if (observer != null) { 9538 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9539 } 9540 } catch (RemoteException re) { 9541 } 9542 return; 9543 } 9544 9545 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9546 installFlags |= PackageManager.INSTALL_FROM_ADB; 9547 9548 } else { 9549 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9550 // about installerPackageName. 9551 9552 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9553 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9554 } 9555 9556 UserHandle user; 9557 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9558 user = UserHandle.ALL; 9559 } else { 9560 user = new UserHandle(userId); 9561 } 9562 9563 // Only system components can circumvent runtime permissions when installing. 9564 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9565 && mContext.checkCallingOrSelfPermission(Manifest.permission 9566 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9567 throw new SecurityException("You need the " 9568 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9569 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9570 } 9571 9572 verificationParams.setInstallerUid(callingUid); 9573 9574 final File originFile = new File(originPath); 9575 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9576 9577 final Message msg = mHandler.obtainMessage(INIT_COPY); 9578 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9579 null, verificationParams, user, packageAbiOverride, null); 9580 mHandler.sendMessage(msg); 9581 } 9582 9583 void installStage(String packageName, File stagedDir, String stagedCid, 9584 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9585 String installerPackageName, int installerUid, UserHandle user) { 9586 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9587 params.referrerUri, installerUid, null); 9588 verifParams.setInstallerUid(installerUid); 9589 9590 final OriginInfo origin; 9591 if (stagedDir != null) { 9592 origin = OriginInfo.fromStagedFile(stagedDir); 9593 } else { 9594 origin = OriginInfo.fromStagedContainer(stagedCid); 9595 } 9596 9597 final Message msg = mHandler.obtainMessage(INIT_COPY); 9598 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9599 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9600 params.grantedRuntimePermissions); 9601 9602 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9603 System.identityHashCode(msg.obj)); 9604 9605 mHandler.sendMessage(msg); 9606 } 9607 9608 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9609 Bundle extras = new Bundle(1); 9610 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9611 9612 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9613 packageName, extras, null, null, new int[] {userId}); 9614 try { 9615 IActivityManager am = ActivityManagerNative.getDefault(); 9616 final boolean isSystem = 9617 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9618 if (isSystem && am.isUserRunning(userId, false)) { 9619 // The just-installed/enabled app is bundled on the system, so presumed 9620 // to be able to run automatically without needing an explicit launch. 9621 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9622 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9623 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9624 .setPackage(packageName); 9625 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9626 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9627 } 9628 } catch (RemoteException e) { 9629 // shouldn't happen 9630 Slog.w(TAG, "Unable to bootstrap installed package", e); 9631 } 9632 } 9633 9634 @Override 9635 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9636 int userId) { 9637 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9638 PackageSetting pkgSetting; 9639 final int uid = Binder.getCallingUid(); 9640 enforceCrossUserPermission(uid, userId, true, true, 9641 "setApplicationHiddenSetting for user " + userId); 9642 9643 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9644 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9645 return false; 9646 } 9647 9648 long callingId = Binder.clearCallingIdentity(); 9649 try { 9650 boolean sendAdded = false; 9651 boolean sendRemoved = false; 9652 // writer 9653 synchronized (mPackages) { 9654 pkgSetting = mSettings.mPackages.get(packageName); 9655 if (pkgSetting == null) { 9656 return false; 9657 } 9658 if (pkgSetting.getHidden(userId) != hidden) { 9659 pkgSetting.setHidden(hidden, userId); 9660 mSettings.writePackageRestrictionsLPr(userId); 9661 if (hidden) { 9662 sendRemoved = true; 9663 } else { 9664 sendAdded = true; 9665 } 9666 } 9667 } 9668 if (sendAdded) { 9669 sendPackageAddedForUser(packageName, pkgSetting, userId); 9670 return true; 9671 } 9672 if (sendRemoved) { 9673 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9674 "hiding pkg"); 9675 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9676 return true; 9677 } 9678 } finally { 9679 Binder.restoreCallingIdentity(callingId); 9680 } 9681 return false; 9682 } 9683 9684 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9685 int userId) { 9686 final PackageRemovedInfo info = new PackageRemovedInfo(); 9687 info.removedPackage = packageName; 9688 info.removedUsers = new int[] {userId}; 9689 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9690 info.sendBroadcast(false, false, false); 9691 } 9692 9693 /** 9694 * Returns true if application is not found or there was an error. Otherwise it returns 9695 * the hidden state of the package for the given user. 9696 */ 9697 @Override 9698 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9699 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9700 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9701 false, "getApplicationHidden for user " + userId); 9702 PackageSetting pkgSetting; 9703 long callingId = Binder.clearCallingIdentity(); 9704 try { 9705 // writer 9706 synchronized (mPackages) { 9707 pkgSetting = mSettings.mPackages.get(packageName); 9708 if (pkgSetting == null) { 9709 return true; 9710 } 9711 return pkgSetting.getHidden(userId); 9712 } 9713 } finally { 9714 Binder.restoreCallingIdentity(callingId); 9715 } 9716 } 9717 9718 /** 9719 * @hide 9720 */ 9721 @Override 9722 public int installExistingPackageAsUser(String packageName, int userId) { 9723 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9724 null); 9725 PackageSetting pkgSetting; 9726 final int uid = Binder.getCallingUid(); 9727 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9728 + userId); 9729 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9730 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9731 } 9732 9733 long callingId = Binder.clearCallingIdentity(); 9734 try { 9735 boolean sendAdded = false; 9736 9737 // writer 9738 synchronized (mPackages) { 9739 pkgSetting = mSettings.mPackages.get(packageName); 9740 if (pkgSetting == null) { 9741 return PackageManager.INSTALL_FAILED_INVALID_URI; 9742 } 9743 if (!pkgSetting.getInstalled(userId)) { 9744 pkgSetting.setInstalled(true, userId); 9745 pkgSetting.setHidden(false, userId); 9746 mSettings.writePackageRestrictionsLPr(userId); 9747 sendAdded = true; 9748 } 9749 } 9750 9751 if (sendAdded) { 9752 sendPackageAddedForUser(packageName, pkgSetting, userId); 9753 } 9754 } finally { 9755 Binder.restoreCallingIdentity(callingId); 9756 } 9757 9758 return PackageManager.INSTALL_SUCCEEDED; 9759 } 9760 9761 boolean isUserRestricted(int userId, String restrictionKey) { 9762 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9763 if (restrictions.getBoolean(restrictionKey, false)) { 9764 Log.w(TAG, "User is restricted: " + restrictionKey); 9765 return true; 9766 } 9767 return false; 9768 } 9769 9770 @Override 9771 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9772 mContext.enforceCallingOrSelfPermission( 9773 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9774 "Only package verification agents can verify applications"); 9775 9776 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9777 final PackageVerificationResponse response = new PackageVerificationResponse( 9778 verificationCode, Binder.getCallingUid()); 9779 msg.arg1 = id; 9780 msg.obj = response; 9781 mHandler.sendMessage(msg); 9782 } 9783 9784 @Override 9785 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9786 long millisecondsToDelay) { 9787 mContext.enforceCallingOrSelfPermission( 9788 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9789 "Only package verification agents can extend verification timeouts"); 9790 9791 final PackageVerificationState state = mPendingVerification.get(id); 9792 final PackageVerificationResponse response = new PackageVerificationResponse( 9793 verificationCodeAtTimeout, Binder.getCallingUid()); 9794 9795 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9796 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9797 } 9798 if (millisecondsToDelay < 0) { 9799 millisecondsToDelay = 0; 9800 } 9801 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9802 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9803 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9804 } 9805 9806 if ((state != null) && !state.timeoutExtended()) { 9807 state.extendTimeout(); 9808 9809 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9810 msg.arg1 = id; 9811 msg.obj = response; 9812 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9813 } 9814 } 9815 9816 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9817 int verificationCode, UserHandle user) { 9818 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9819 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9820 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9821 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9822 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9823 9824 mContext.sendBroadcastAsUser(intent, user, 9825 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9826 } 9827 9828 private ComponentName matchComponentForVerifier(String packageName, 9829 List<ResolveInfo> receivers) { 9830 ActivityInfo targetReceiver = null; 9831 9832 final int NR = receivers.size(); 9833 for (int i = 0; i < NR; i++) { 9834 final ResolveInfo info = receivers.get(i); 9835 if (info.activityInfo == null) { 9836 continue; 9837 } 9838 9839 if (packageName.equals(info.activityInfo.packageName)) { 9840 targetReceiver = info.activityInfo; 9841 break; 9842 } 9843 } 9844 9845 if (targetReceiver == null) { 9846 return null; 9847 } 9848 9849 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9850 } 9851 9852 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9853 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9854 if (pkgInfo.verifiers.length == 0) { 9855 return null; 9856 } 9857 9858 final int N = pkgInfo.verifiers.length; 9859 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9860 for (int i = 0; i < N; i++) { 9861 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9862 9863 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9864 receivers); 9865 if (comp == null) { 9866 continue; 9867 } 9868 9869 final int verifierUid = getUidForVerifier(verifierInfo); 9870 if (verifierUid == -1) { 9871 continue; 9872 } 9873 9874 if (DEBUG_VERIFY) { 9875 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9876 + " with the correct signature"); 9877 } 9878 sufficientVerifiers.add(comp); 9879 verificationState.addSufficientVerifier(verifierUid); 9880 } 9881 9882 return sufficientVerifiers; 9883 } 9884 9885 private int getUidForVerifier(VerifierInfo verifierInfo) { 9886 synchronized (mPackages) { 9887 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9888 if (pkg == null) { 9889 return -1; 9890 } else if (pkg.mSignatures.length != 1) { 9891 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9892 + " has more than one signature; ignoring"); 9893 return -1; 9894 } 9895 9896 /* 9897 * If the public key of the package's signature does not match 9898 * our expected public key, then this is a different package and 9899 * we should skip. 9900 */ 9901 9902 final byte[] expectedPublicKey; 9903 try { 9904 final Signature verifierSig = pkg.mSignatures[0]; 9905 final PublicKey publicKey = verifierSig.getPublicKey(); 9906 expectedPublicKey = publicKey.getEncoded(); 9907 } catch (CertificateException e) { 9908 return -1; 9909 } 9910 9911 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9912 9913 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9914 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9915 + " does not have the expected public key; ignoring"); 9916 return -1; 9917 } 9918 9919 return pkg.applicationInfo.uid; 9920 } 9921 } 9922 9923 @Override 9924 public void finishPackageInstall(int token) { 9925 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9926 9927 if (DEBUG_INSTALL) { 9928 Slog.v(TAG, "BM finishing package install for " + token); 9929 } 9930 9931 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9932 mHandler.sendMessage(msg); 9933 } 9934 9935 /** 9936 * Get the verification agent timeout. 9937 * 9938 * @return verification timeout in milliseconds 9939 */ 9940 private long getVerificationTimeout() { 9941 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9942 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9943 DEFAULT_VERIFICATION_TIMEOUT); 9944 } 9945 9946 /** 9947 * Get the default verification agent response code. 9948 * 9949 * @return default verification response code 9950 */ 9951 private int getDefaultVerificationResponse() { 9952 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9953 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9954 DEFAULT_VERIFICATION_RESPONSE); 9955 } 9956 9957 /** 9958 * Check whether or not package verification has been enabled. 9959 * 9960 * @return true if verification should be performed 9961 */ 9962 private boolean isVerificationEnabled(int userId, int installFlags) { 9963 if (!DEFAULT_VERIFY_ENABLE) { 9964 return false; 9965 } 9966 9967 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9968 9969 // Check if installing from ADB 9970 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9971 // Do not run verification in a test harness environment 9972 if (ActivityManager.isRunningInTestHarness()) { 9973 return false; 9974 } 9975 if (ensureVerifyAppsEnabled) { 9976 return true; 9977 } 9978 // Check if the developer does not want package verification for ADB installs 9979 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9980 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9981 return false; 9982 } 9983 } 9984 9985 if (ensureVerifyAppsEnabled) { 9986 return true; 9987 } 9988 9989 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9990 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9991 } 9992 9993 @Override 9994 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9995 throws RemoteException { 9996 mContext.enforceCallingOrSelfPermission( 9997 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9998 "Only intentfilter verification agents can verify applications"); 9999 10000 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10001 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10002 Binder.getCallingUid(), verificationCode, failedDomains); 10003 msg.arg1 = id; 10004 msg.obj = response; 10005 mHandler.sendMessage(msg); 10006 } 10007 10008 @Override 10009 public int getIntentVerificationStatus(String packageName, int userId) { 10010 synchronized (mPackages) { 10011 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10012 } 10013 } 10014 10015 @Override 10016 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10017 mContext.enforceCallingOrSelfPermission( 10018 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10019 10020 boolean result = false; 10021 synchronized (mPackages) { 10022 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10023 } 10024 if (result) { 10025 scheduleWritePackageRestrictionsLocked(userId); 10026 } 10027 return result; 10028 } 10029 10030 @Override 10031 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10032 synchronized (mPackages) { 10033 return mSettings.getIntentFilterVerificationsLPr(packageName); 10034 } 10035 } 10036 10037 @Override 10038 public List<IntentFilter> getAllIntentFilters(String packageName) { 10039 if (TextUtils.isEmpty(packageName)) { 10040 return Collections.<IntentFilter>emptyList(); 10041 } 10042 synchronized (mPackages) { 10043 PackageParser.Package pkg = mPackages.get(packageName); 10044 if (pkg == null || pkg.activities == null) { 10045 return Collections.<IntentFilter>emptyList(); 10046 } 10047 final int count = pkg.activities.size(); 10048 ArrayList<IntentFilter> result = new ArrayList<>(); 10049 for (int n=0; n<count; n++) { 10050 PackageParser.Activity activity = pkg.activities.get(n); 10051 if (activity.intents != null || activity.intents.size() > 0) { 10052 result.addAll(activity.intents); 10053 } 10054 } 10055 return result; 10056 } 10057 } 10058 10059 @Override 10060 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10061 mContext.enforceCallingOrSelfPermission( 10062 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10063 10064 synchronized (mPackages) { 10065 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10066 if (packageName != null) { 10067 result |= updateIntentVerificationStatus(packageName, 10068 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10069 userId); 10070 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10071 packageName, userId); 10072 } 10073 return result; 10074 } 10075 } 10076 10077 @Override 10078 public String getDefaultBrowserPackageName(int userId) { 10079 synchronized (mPackages) { 10080 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10081 } 10082 } 10083 10084 /** 10085 * Get the "allow unknown sources" setting. 10086 * 10087 * @return the current "allow unknown sources" setting 10088 */ 10089 private int getUnknownSourcesSettings() { 10090 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10091 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10092 -1); 10093 } 10094 10095 @Override 10096 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10097 final int uid = Binder.getCallingUid(); 10098 // writer 10099 synchronized (mPackages) { 10100 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10101 if (targetPackageSetting == null) { 10102 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10103 } 10104 10105 PackageSetting installerPackageSetting; 10106 if (installerPackageName != null) { 10107 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10108 if (installerPackageSetting == null) { 10109 throw new IllegalArgumentException("Unknown installer package: " 10110 + installerPackageName); 10111 } 10112 } else { 10113 installerPackageSetting = null; 10114 } 10115 10116 Signature[] callerSignature; 10117 Object obj = mSettings.getUserIdLPr(uid); 10118 if (obj != null) { 10119 if (obj instanceof SharedUserSetting) { 10120 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10121 } else if (obj instanceof PackageSetting) { 10122 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10123 } else { 10124 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10125 } 10126 } else { 10127 throw new SecurityException("Unknown calling uid " + uid); 10128 } 10129 10130 // Verify: can't set installerPackageName to a package that is 10131 // not signed with the same cert as the caller. 10132 if (installerPackageSetting != null) { 10133 if (compareSignatures(callerSignature, 10134 installerPackageSetting.signatures.mSignatures) 10135 != PackageManager.SIGNATURE_MATCH) { 10136 throw new SecurityException( 10137 "Caller does not have same cert as new installer package " 10138 + installerPackageName); 10139 } 10140 } 10141 10142 // Verify: if target already has an installer package, it must 10143 // be signed with the same cert as the caller. 10144 if (targetPackageSetting.installerPackageName != null) { 10145 PackageSetting setting = mSettings.mPackages.get( 10146 targetPackageSetting.installerPackageName); 10147 // If the currently set package isn't valid, then it's always 10148 // okay to change it. 10149 if (setting != null) { 10150 if (compareSignatures(callerSignature, 10151 setting.signatures.mSignatures) 10152 != PackageManager.SIGNATURE_MATCH) { 10153 throw new SecurityException( 10154 "Caller does not have same cert as old installer package " 10155 + targetPackageSetting.installerPackageName); 10156 } 10157 } 10158 } 10159 10160 // Okay! 10161 targetPackageSetting.installerPackageName = installerPackageName; 10162 scheduleWriteSettingsLocked(); 10163 } 10164 } 10165 10166 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10167 // Queue up an async operation since the package installation may take a little while. 10168 mHandler.post(new Runnable() { 10169 public void run() { 10170 mHandler.removeCallbacks(this); 10171 // Result object to be returned 10172 PackageInstalledInfo res = new PackageInstalledInfo(); 10173 res.returnCode = currentStatus; 10174 res.uid = -1; 10175 res.pkg = null; 10176 res.removedInfo = new PackageRemovedInfo(); 10177 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10178 args.doPreInstall(res.returnCode); 10179 synchronized (mInstallLock) { 10180 installPackageTracedLI(args, res); 10181 } 10182 args.doPostInstall(res.returnCode, res.uid); 10183 } 10184 10185 // A restore should be performed at this point if (a) the install 10186 // succeeded, (b) the operation is not an update, and (c) the new 10187 // package has not opted out of backup participation. 10188 final boolean update = res.removedInfo.removedPackage != null; 10189 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10190 boolean doRestore = !update 10191 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10192 10193 // Set up the post-install work request bookkeeping. This will be used 10194 // and cleaned up by the post-install event handling regardless of whether 10195 // there's a restore pass performed. Token values are >= 1. 10196 int token; 10197 if (mNextInstallToken < 0) mNextInstallToken = 1; 10198 token = mNextInstallToken++; 10199 10200 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10201 10202 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10203 // Pass responsibility to the Backup Manager. It will perform a 10204 // restore if appropriate, then pass responsibility back to the 10205 // Package Manager to run the post-install observer callbacks 10206 // and broadcasts. 10207 IBackupManager bm = IBackupManager.Stub.asInterface( 10208 ServiceManager.getService(Context.BACKUP_SERVICE)); 10209 if (bm != null) { 10210 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10211 + " to BM for possible restore"); 10212 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10213 try { 10214 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10215 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10216 } else { 10217 doRestore = false; 10218 } 10219 } catch (RemoteException e) { 10220 // can't happen; the backup manager is local 10221 } catch (Exception e) { 10222 Slog.e(TAG, "Exception trying to enqueue restore", e); 10223 doRestore = false; 10224 } finally { 10225 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10226 } 10227 } else { 10228 Slog.e(TAG, "Backup Manager not found!"); 10229 doRestore = false; 10230 } 10231 } 10232 10233 if (!doRestore) { 10234 // No restore possible, or the Backup Manager was mysteriously not 10235 // available -- just fire the post-install work request directly. 10236 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10237 10238 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10239 10240 PostInstallData data = new PostInstallData(args, res); 10241 mRunningInstalls.put(token, data); 10242 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10243 mHandler.sendMessage(msg); 10244 } 10245 } 10246 }); 10247 } 10248 10249 private abstract class HandlerParams { 10250 private static final int MAX_RETRIES = 4; 10251 10252 /** 10253 * Number of times startCopy() has been attempted and had a non-fatal 10254 * error. 10255 */ 10256 private int mRetries = 0; 10257 10258 /** User handle for the user requesting the information or installation. */ 10259 private final UserHandle mUser; 10260 10261 HandlerParams(UserHandle user) { 10262 mUser = user; 10263 } 10264 10265 UserHandle getUser() { 10266 return mUser; 10267 } 10268 10269 final boolean startCopy() { 10270 boolean res; 10271 try { 10272 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10273 10274 if (++mRetries > MAX_RETRIES) { 10275 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10276 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10277 handleServiceError(); 10278 return false; 10279 } else { 10280 handleStartCopy(); 10281 res = true; 10282 } 10283 } catch (RemoteException e) { 10284 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10285 mHandler.sendEmptyMessage(MCS_RECONNECT); 10286 res = false; 10287 } 10288 handleReturnCode(); 10289 return res; 10290 } 10291 10292 final void serviceError() { 10293 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10294 handleServiceError(); 10295 handleReturnCode(); 10296 } 10297 10298 abstract void handleStartCopy() throws RemoteException; 10299 abstract void handleServiceError(); 10300 abstract void handleReturnCode(); 10301 } 10302 10303 class MeasureParams extends HandlerParams { 10304 private final PackageStats mStats; 10305 private boolean mSuccess; 10306 10307 private final IPackageStatsObserver mObserver; 10308 10309 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10310 super(new UserHandle(stats.userHandle)); 10311 mObserver = observer; 10312 mStats = stats; 10313 } 10314 10315 @Override 10316 public String toString() { 10317 return "MeasureParams{" 10318 + Integer.toHexString(System.identityHashCode(this)) 10319 + " " + mStats.packageName + "}"; 10320 } 10321 10322 @Override 10323 void handleStartCopy() throws RemoteException { 10324 synchronized (mInstallLock) { 10325 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10326 } 10327 10328 if (mSuccess) { 10329 final boolean mounted; 10330 if (Environment.isExternalStorageEmulated()) { 10331 mounted = true; 10332 } else { 10333 final String status = Environment.getExternalStorageState(); 10334 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10335 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10336 } 10337 10338 if (mounted) { 10339 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10340 10341 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10342 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10343 10344 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10345 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10346 10347 // Always subtract cache size, since it's a subdirectory 10348 mStats.externalDataSize -= mStats.externalCacheSize; 10349 10350 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10351 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10352 10353 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10354 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10355 } 10356 } 10357 } 10358 10359 @Override 10360 void handleReturnCode() { 10361 if (mObserver != null) { 10362 try { 10363 mObserver.onGetStatsCompleted(mStats, mSuccess); 10364 } catch (RemoteException e) { 10365 Slog.i(TAG, "Observer no longer exists."); 10366 } 10367 } 10368 } 10369 10370 @Override 10371 void handleServiceError() { 10372 Slog.e(TAG, "Could not measure application " + mStats.packageName 10373 + " external storage"); 10374 } 10375 } 10376 10377 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10378 throws RemoteException { 10379 long result = 0; 10380 for (File path : paths) { 10381 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10382 } 10383 return result; 10384 } 10385 10386 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10387 for (File path : paths) { 10388 try { 10389 mcs.clearDirectory(path.getAbsolutePath()); 10390 } catch (RemoteException e) { 10391 } 10392 } 10393 } 10394 10395 static class OriginInfo { 10396 /** 10397 * Location where install is coming from, before it has been 10398 * copied/renamed into place. This could be a single monolithic APK 10399 * file, or a cluster directory. This location may be untrusted. 10400 */ 10401 final File file; 10402 final String cid; 10403 10404 /** 10405 * Flag indicating that {@link #file} or {@link #cid} has already been 10406 * staged, meaning downstream users don't need to defensively copy the 10407 * contents. 10408 */ 10409 final boolean staged; 10410 10411 /** 10412 * Flag indicating that {@link #file} or {@link #cid} is an already 10413 * installed app that is being moved. 10414 */ 10415 final boolean existing; 10416 10417 final String resolvedPath; 10418 final File resolvedFile; 10419 10420 static OriginInfo fromNothing() { 10421 return new OriginInfo(null, null, false, false); 10422 } 10423 10424 static OriginInfo fromUntrustedFile(File file) { 10425 return new OriginInfo(file, null, false, false); 10426 } 10427 10428 static OriginInfo fromExistingFile(File file) { 10429 return new OriginInfo(file, null, false, true); 10430 } 10431 10432 static OriginInfo fromStagedFile(File file) { 10433 return new OriginInfo(file, null, true, false); 10434 } 10435 10436 static OriginInfo fromStagedContainer(String cid) { 10437 return new OriginInfo(null, cid, true, false); 10438 } 10439 10440 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10441 this.file = file; 10442 this.cid = cid; 10443 this.staged = staged; 10444 this.existing = existing; 10445 10446 if (cid != null) { 10447 resolvedPath = PackageHelper.getSdDir(cid); 10448 resolvedFile = new File(resolvedPath); 10449 } else if (file != null) { 10450 resolvedPath = file.getAbsolutePath(); 10451 resolvedFile = file; 10452 } else { 10453 resolvedPath = null; 10454 resolvedFile = null; 10455 } 10456 } 10457 } 10458 10459 class MoveInfo { 10460 final int moveId; 10461 final String fromUuid; 10462 final String toUuid; 10463 final String packageName; 10464 final String dataAppName; 10465 final int appId; 10466 final String seinfo; 10467 10468 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10469 String dataAppName, int appId, String seinfo) { 10470 this.moveId = moveId; 10471 this.fromUuid = fromUuid; 10472 this.toUuid = toUuid; 10473 this.packageName = packageName; 10474 this.dataAppName = dataAppName; 10475 this.appId = appId; 10476 this.seinfo = seinfo; 10477 } 10478 } 10479 10480 class InstallParams extends HandlerParams { 10481 final OriginInfo origin; 10482 final MoveInfo move; 10483 final IPackageInstallObserver2 observer; 10484 int installFlags; 10485 final String installerPackageName; 10486 final String volumeUuid; 10487 final VerificationParams verificationParams; 10488 private InstallArgs mArgs; 10489 private int mRet; 10490 final String packageAbiOverride; 10491 final String[] grantedRuntimePermissions; 10492 10493 10494 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10495 int installFlags, String installerPackageName, String volumeUuid, 10496 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10497 String[] grantedPermissions) { 10498 super(user); 10499 this.origin = origin; 10500 this.move = move; 10501 this.observer = observer; 10502 this.installFlags = installFlags; 10503 this.installerPackageName = installerPackageName; 10504 this.volumeUuid = volumeUuid; 10505 this.verificationParams = verificationParams; 10506 this.packageAbiOverride = packageAbiOverride; 10507 this.grantedRuntimePermissions = grantedPermissions; 10508 } 10509 10510 @Override 10511 public String toString() { 10512 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10513 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10514 } 10515 10516 public ManifestDigest getManifestDigest() { 10517 if (verificationParams == null) { 10518 return null; 10519 } 10520 return verificationParams.getManifestDigest(); 10521 } 10522 10523 private int installLocationPolicy(PackageInfoLite pkgLite) { 10524 String packageName = pkgLite.packageName; 10525 int installLocation = pkgLite.installLocation; 10526 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10527 // reader 10528 synchronized (mPackages) { 10529 PackageParser.Package pkg = mPackages.get(packageName); 10530 if (pkg != null) { 10531 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10532 // Check for downgrading. 10533 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10534 try { 10535 checkDowngrade(pkg, pkgLite); 10536 } catch (PackageManagerException e) { 10537 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10538 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10539 } 10540 } 10541 // Check for updated system application. 10542 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10543 if (onSd) { 10544 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10545 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10546 } 10547 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10548 } else { 10549 if (onSd) { 10550 // Install flag overrides everything. 10551 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10552 } 10553 // If current upgrade specifies particular preference 10554 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10555 // Application explicitly specified internal. 10556 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10557 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10558 // App explictly prefers external. Let policy decide 10559 } else { 10560 // Prefer previous location 10561 if (isExternal(pkg)) { 10562 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10563 } 10564 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10565 } 10566 } 10567 } else { 10568 // Invalid install. Return error code 10569 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10570 } 10571 } 10572 } 10573 // All the special cases have been taken care of. 10574 // Return result based on recommended install location. 10575 if (onSd) { 10576 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10577 } 10578 return pkgLite.recommendedInstallLocation; 10579 } 10580 10581 /* 10582 * Invoke remote method to get package information and install 10583 * location values. Override install location based on default 10584 * policy if needed and then create install arguments based 10585 * on the install location. 10586 */ 10587 public void handleStartCopy() throws RemoteException { 10588 int ret = PackageManager.INSTALL_SUCCEEDED; 10589 10590 // If we're already staged, we've firmly committed to an install location 10591 if (origin.staged) { 10592 if (origin.file != null) { 10593 installFlags |= PackageManager.INSTALL_INTERNAL; 10594 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10595 } else if (origin.cid != null) { 10596 installFlags |= PackageManager.INSTALL_EXTERNAL; 10597 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10598 } else { 10599 throw new IllegalStateException("Invalid stage location"); 10600 } 10601 } 10602 10603 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10604 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10605 PackageInfoLite pkgLite = null; 10606 10607 if (onInt && onSd) { 10608 // Check if both bits are set. 10609 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10610 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10611 } else { 10612 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10613 packageAbiOverride); 10614 10615 /* 10616 * If we have too little free space, try to free cache 10617 * before giving up. 10618 */ 10619 if (!origin.staged && pkgLite.recommendedInstallLocation 10620 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10621 // TODO: focus freeing disk space on the target device 10622 final StorageManager storage = StorageManager.from(mContext); 10623 final long lowThreshold = storage.getStorageLowBytes( 10624 Environment.getDataDirectory()); 10625 10626 final long sizeBytes = mContainerService.calculateInstalledSize( 10627 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10628 10629 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10630 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10631 installFlags, packageAbiOverride); 10632 } 10633 10634 /* 10635 * The cache free must have deleted the file we 10636 * downloaded to install. 10637 * 10638 * TODO: fix the "freeCache" call to not delete 10639 * the file we care about. 10640 */ 10641 if (pkgLite.recommendedInstallLocation 10642 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10643 pkgLite.recommendedInstallLocation 10644 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10645 } 10646 } 10647 } 10648 10649 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10650 int loc = pkgLite.recommendedInstallLocation; 10651 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10652 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10653 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10654 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10655 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10656 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10657 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10658 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10659 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10660 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10661 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10662 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10663 } else { 10664 // Override with defaults if needed. 10665 loc = installLocationPolicy(pkgLite); 10666 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10667 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10668 } else if (!onSd && !onInt) { 10669 // Override install location with flags 10670 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10671 // Set the flag to install on external media. 10672 installFlags |= PackageManager.INSTALL_EXTERNAL; 10673 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10674 } else { 10675 // Make sure the flag for installing on external 10676 // media is unset 10677 installFlags |= PackageManager.INSTALL_INTERNAL; 10678 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10679 } 10680 } 10681 } 10682 } 10683 10684 final InstallArgs args = createInstallArgs(this); 10685 mArgs = args; 10686 10687 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10688 /* 10689 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10690 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10691 */ 10692 int userIdentifier = getUser().getIdentifier(); 10693 if (userIdentifier == UserHandle.USER_ALL 10694 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10695 userIdentifier = UserHandle.USER_OWNER; 10696 } 10697 10698 /* 10699 * Determine if we have any installed package verifiers. If we 10700 * do, then we'll defer to them to verify the packages. 10701 */ 10702 final int requiredUid = mRequiredVerifierPackage == null ? -1 10703 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10704 if (!origin.existing && requiredUid != -1 10705 && isVerificationEnabled(userIdentifier, installFlags)) { 10706 final Intent verification = new Intent( 10707 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10708 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10709 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10710 PACKAGE_MIME_TYPE); 10711 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10712 10713 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10714 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10715 0 /* TODO: Which userId? */); 10716 10717 if (DEBUG_VERIFY) { 10718 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10719 + verification.toString() + " with " + pkgLite.verifiers.length 10720 + " optional verifiers"); 10721 } 10722 10723 final int verificationId = mPendingVerificationToken++; 10724 10725 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10726 10727 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10728 installerPackageName); 10729 10730 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10731 installFlags); 10732 10733 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10734 pkgLite.packageName); 10735 10736 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10737 pkgLite.versionCode); 10738 10739 if (verificationParams != null) { 10740 if (verificationParams.getVerificationURI() != null) { 10741 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10742 verificationParams.getVerificationURI()); 10743 } 10744 if (verificationParams.getOriginatingURI() != null) { 10745 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10746 verificationParams.getOriginatingURI()); 10747 } 10748 if (verificationParams.getReferrer() != null) { 10749 verification.putExtra(Intent.EXTRA_REFERRER, 10750 verificationParams.getReferrer()); 10751 } 10752 if (verificationParams.getOriginatingUid() >= 0) { 10753 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10754 verificationParams.getOriginatingUid()); 10755 } 10756 if (verificationParams.getInstallerUid() >= 0) { 10757 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10758 verificationParams.getInstallerUid()); 10759 } 10760 } 10761 10762 final PackageVerificationState verificationState = new PackageVerificationState( 10763 requiredUid, args); 10764 10765 mPendingVerification.append(verificationId, verificationState); 10766 10767 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10768 receivers, verificationState); 10769 10770 // Apps installed for "all" users use the device owner to verify the app 10771 UserHandle verifierUser = getUser(); 10772 if (verifierUser == UserHandle.ALL) { 10773 verifierUser = UserHandle.OWNER; 10774 } 10775 10776 /* 10777 * If any sufficient verifiers were listed in the package 10778 * manifest, attempt to ask them. 10779 */ 10780 if (sufficientVerifiers != null) { 10781 final int N = sufficientVerifiers.size(); 10782 if (N == 0) { 10783 Slog.i(TAG, "Additional verifiers required, but none installed."); 10784 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10785 } else { 10786 for (int i = 0; i < N; i++) { 10787 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10788 10789 final Intent sufficientIntent = new Intent(verification); 10790 sufficientIntent.setComponent(verifierComponent); 10791 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10792 } 10793 } 10794 } 10795 10796 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10797 mRequiredVerifierPackage, receivers); 10798 if (ret == PackageManager.INSTALL_SUCCEEDED 10799 && mRequiredVerifierPackage != null) { 10800 Trace.asyncTraceBegin( 10801 TRACE_TAG_PACKAGE_MANAGER, "pendingVerification", verificationId); 10802 /* 10803 * Send the intent to the required verification agent, 10804 * but only start the verification timeout after the 10805 * target BroadcastReceivers have run. 10806 */ 10807 verification.setComponent(requiredVerifierComponent); 10808 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10809 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10810 new BroadcastReceiver() { 10811 @Override 10812 public void onReceive(Context context, Intent intent) { 10813 final Message msg = mHandler 10814 .obtainMessage(CHECK_PENDING_VERIFICATION); 10815 msg.arg1 = verificationId; 10816 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10817 } 10818 }, null, 0, null, null); 10819 10820 /* 10821 * We don't want the copy to proceed until verification 10822 * succeeds, so null out this field. 10823 */ 10824 mArgs = null; 10825 } 10826 } else { 10827 /* 10828 * No package verification is enabled, so immediately start 10829 * the remote call to initiate copy using temporary file. 10830 */ 10831 ret = args.copyApk(mContainerService, true); 10832 } 10833 } 10834 10835 mRet = ret; 10836 } 10837 10838 @Override 10839 void handleReturnCode() { 10840 // If mArgs is null, then MCS couldn't be reached. When it 10841 // reconnects, it will try again to install. At that point, this 10842 // will succeed. 10843 if (mArgs != null) { 10844 processPendingInstall(mArgs, mRet); 10845 } 10846 } 10847 10848 @Override 10849 void handleServiceError() { 10850 mArgs = createInstallArgs(this); 10851 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10852 } 10853 10854 public boolean isForwardLocked() { 10855 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10856 } 10857 } 10858 10859 /** 10860 * Used during creation of InstallArgs 10861 * 10862 * @param installFlags package installation flags 10863 * @return true if should be installed on external storage 10864 */ 10865 private static boolean installOnExternalAsec(int installFlags) { 10866 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10867 return false; 10868 } 10869 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10870 return true; 10871 } 10872 return false; 10873 } 10874 10875 /** 10876 * Used during creation of InstallArgs 10877 * 10878 * @param installFlags package installation flags 10879 * @return true if should be installed as forward locked 10880 */ 10881 private static boolean installForwardLocked(int installFlags) { 10882 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10883 } 10884 10885 private InstallArgs createInstallArgs(InstallParams params) { 10886 if (params.move != null) { 10887 return new MoveInstallArgs(params); 10888 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10889 return new AsecInstallArgs(params); 10890 } else { 10891 return new FileInstallArgs(params); 10892 } 10893 } 10894 10895 /** 10896 * Create args that describe an existing installed package. Typically used 10897 * when cleaning up old installs, or used as a move source. 10898 */ 10899 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10900 String resourcePath, String[] instructionSets) { 10901 final boolean isInAsec; 10902 if (installOnExternalAsec(installFlags)) { 10903 /* Apps on SD card are always in ASEC containers. */ 10904 isInAsec = true; 10905 } else if (installForwardLocked(installFlags) 10906 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10907 /* 10908 * Forward-locked apps are only in ASEC containers if they're the 10909 * new style 10910 */ 10911 isInAsec = true; 10912 } else { 10913 isInAsec = false; 10914 } 10915 10916 if (isInAsec) { 10917 return new AsecInstallArgs(codePath, instructionSets, 10918 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10919 } else { 10920 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10921 } 10922 } 10923 10924 static abstract class InstallArgs { 10925 /** @see InstallParams#origin */ 10926 final OriginInfo origin; 10927 /** @see InstallParams#move */ 10928 final MoveInfo move; 10929 10930 final IPackageInstallObserver2 observer; 10931 // Always refers to PackageManager flags only 10932 final int installFlags; 10933 final String installerPackageName; 10934 final String volumeUuid; 10935 final ManifestDigest manifestDigest; 10936 final UserHandle user; 10937 final String abiOverride; 10938 final String[] installGrantPermissions; 10939 10940 // The list of instruction sets supported by this app. This is currently 10941 // only used during the rmdex() phase to clean up resources. We can get rid of this 10942 // if we move dex files under the common app path. 10943 /* nullable */ String[] instructionSets; 10944 10945 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10946 int installFlags, String installerPackageName, String volumeUuid, 10947 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10948 String abiOverride, String[] installGrantPermissions) { 10949 this.origin = origin; 10950 this.move = move; 10951 this.installFlags = installFlags; 10952 this.observer = observer; 10953 this.installerPackageName = installerPackageName; 10954 this.volumeUuid = volumeUuid; 10955 this.manifestDigest = manifestDigest; 10956 this.user = user; 10957 this.instructionSets = instructionSets; 10958 this.abiOverride = abiOverride; 10959 this.installGrantPermissions = installGrantPermissions; 10960 } 10961 10962 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10963 abstract int doPreInstall(int status); 10964 10965 /** 10966 * Rename package into final resting place. All paths on the given 10967 * scanned package should be updated to reflect the rename. 10968 */ 10969 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10970 abstract int doPostInstall(int status, int uid); 10971 10972 /** @see PackageSettingBase#codePathString */ 10973 abstract String getCodePath(); 10974 /** @see PackageSettingBase#resourcePathString */ 10975 abstract String getResourcePath(); 10976 10977 // Need installer lock especially for dex file removal. 10978 abstract void cleanUpResourcesLI(); 10979 abstract boolean doPostDeleteLI(boolean delete); 10980 10981 /** 10982 * Called before the source arguments are copied. This is used mostly 10983 * for MoveParams when it needs to read the source file to put it in the 10984 * destination. 10985 */ 10986 int doPreCopy() { 10987 return PackageManager.INSTALL_SUCCEEDED; 10988 } 10989 10990 /** 10991 * Called after the source arguments are copied. This is used mostly for 10992 * MoveParams when it needs to read the source file to put it in the 10993 * destination. 10994 * 10995 * @return 10996 */ 10997 int doPostCopy(int uid) { 10998 return PackageManager.INSTALL_SUCCEEDED; 10999 } 11000 11001 protected boolean isFwdLocked() { 11002 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11003 } 11004 11005 protected boolean isExternalAsec() { 11006 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11007 } 11008 11009 UserHandle getUser() { 11010 return user; 11011 } 11012 } 11013 11014 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11015 if (!allCodePaths.isEmpty()) { 11016 if (instructionSets == null) { 11017 throw new IllegalStateException("instructionSet == null"); 11018 } 11019 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11020 for (String codePath : allCodePaths) { 11021 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11022 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11023 if (retCode < 0) { 11024 Slog.w(TAG, "Couldn't remove dex file for package: " 11025 + " at location " + codePath + ", retcode=" + retCode); 11026 // we don't consider this to be a failure of the core package deletion 11027 } 11028 } 11029 } 11030 } 11031 } 11032 11033 /** 11034 * Logic to handle installation of non-ASEC applications, including copying 11035 * and renaming logic. 11036 */ 11037 class FileInstallArgs extends InstallArgs { 11038 private File codeFile; 11039 private File resourceFile; 11040 11041 // Example topology: 11042 // /data/app/com.example/base.apk 11043 // /data/app/com.example/split_foo.apk 11044 // /data/app/com.example/lib/arm/libfoo.so 11045 // /data/app/com.example/lib/arm64/libfoo.so 11046 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11047 11048 /** New install */ 11049 FileInstallArgs(InstallParams params) { 11050 super(params.origin, params.move, params.observer, params.installFlags, 11051 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11052 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11053 params.grantedRuntimePermissions); 11054 if (isFwdLocked()) { 11055 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11056 } 11057 } 11058 11059 /** Existing install */ 11060 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11061 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11062 null, null); 11063 this.codeFile = (codePath != null) ? new File(codePath) : null; 11064 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11065 } 11066 11067 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11068 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11069 try { 11070 return doCopyApk(imcs, temp); 11071 } finally { 11072 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11073 } 11074 } 11075 11076 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11077 if (origin.staged) { 11078 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11079 codeFile = origin.file; 11080 resourceFile = origin.file; 11081 return PackageManager.INSTALL_SUCCEEDED; 11082 } 11083 11084 try { 11085 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11086 codeFile = tempDir; 11087 resourceFile = tempDir; 11088 } catch (IOException e) { 11089 Slog.w(TAG, "Failed to create copy file: " + e); 11090 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11091 } 11092 11093 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11094 @Override 11095 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11096 if (!FileUtils.isValidExtFilename(name)) { 11097 throw new IllegalArgumentException("Invalid filename: " + name); 11098 } 11099 try { 11100 final File file = new File(codeFile, name); 11101 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11102 O_RDWR | O_CREAT, 0644); 11103 Os.chmod(file.getAbsolutePath(), 0644); 11104 return new ParcelFileDescriptor(fd); 11105 } catch (ErrnoException e) { 11106 throw new RemoteException("Failed to open: " + e.getMessage()); 11107 } 11108 } 11109 }; 11110 11111 int ret = PackageManager.INSTALL_SUCCEEDED; 11112 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11113 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11114 Slog.e(TAG, "Failed to copy package"); 11115 return ret; 11116 } 11117 11118 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11119 NativeLibraryHelper.Handle handle = null; 11120 try { 11121 handle = NativeLibraryHelper.Handle.create(codeFile); 11122 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11123 abiOverride); 11124 } catch (IOException e) { 11125 Slog.e(TAG, "Copying native libraries failed", e); 11126 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11127 } finally { 11128 IoUtils.closeQuietly(handle); 11129 } 11130 11131 return ret; 11132 } 11133 11134 int doPreInstall(int status) { 11135 if (status != PackageManager.INSTALL_SUCCEEDED) { 11136 cleanUp(); 11137 } 11138 return status; 11139 } 11140 11141 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11142 if (status != PackageManager.INSTALL_SUCCEEDED) { 11143 cleanUp(); 11144 return false; 11145 } 11146 11147 final File targetDir = codeFile.getParentFile(); 11148 final File beforeCodeFile = codeFile; 11149 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11150 11151 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11152 try { 11153 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11154 } catch (ErrnoException e) { 11155 Slog.w(TAG, "Failed to rename", e); 11156 return false; 11157 } 11158 11159 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11160 Slog.w(TAG, "Failed to restorecon"); 11161 return false; 11162 } 11163 11164 // Reflect the rename internally 11165 codeFile = afterCodeFile; 11166 resourceFile = afterCodeFile; 11167 11168 // Reflect the rename in scanned details 11169 pkg.codePath = afterCodeFile.getAbsolutePath(); 11170 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11171 pkg.baseCodePath); 11172 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11173 pkg.splitCodePaths); 11174 11175 // Reflect the rename in app info 11176 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11177 pkg.applicationInfo.setCodePath(pkg.codePath); 11178 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11179 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11180 pkg.applicationInfo.setResourcePath(pkg.codePath); 11181 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11182 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11183 11184 return true; 11185 } 11186 11187 int doPostInstall(int status, int uid) { 11188 if (status != PackageManager.INSTALL_SUCCEEDED) { 11189 cleanUp(); 11190 } 11191 return status; 11192 } 11193 11194 @Override 11195 String getCodePath() { 11196 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11197 } 11198 11199 @Override 11200 String getResourcePath() { 11201 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11202 } 11203 11204 private boolean cleanUp() { 11205 if (codeFile == null || !codeFile.exists()) { 11206 return false; 11207 } 11208 11209 if (codeFile.isDirectory()) { 11210 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11211 } else { 11212 codeFile.delete(); 11213 } 11214 11215 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11216 resourceFile.delete(); 11217 } 11218 11219 return true; 11220 } 11221 11222 void cleanUpResourcesLI() { 11223 // Try enumerating all code paths before deleting 11224 List<String> allCodePaths = Collections.EMPTY_LIST; 11225 if (codeFile != null && codeFile.exists()) { 11226 try { 11227 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11228 allCodePaths = pkg.getAllCodePaths(); 11229 } catch (PackageParserException e) { 11230 // Ignored; we tried our best 11231 } 11232 } 11233 11234 cleanUp(); 11235 removeDexFiles(allCodePaths, instructionSets); 11236 } 11237 11238 boolean doPostDeleteLI(boolean delete) { 11239 // XXX err, shouldn't we respect the delete flag? 11240 cleanUpResourcesLI(); 11241 return true; 11242 } 11243 } 11244 11245 private boolean isAsecExternal(String cid) { 11246 final String asecPath = PackageHelper.getSdFilesystem(cid); 11247 return !asecPath.startsWith(mAsecInternalPath); 11248 } 11249 11250 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11251 PackageManagerException { 11252 if (copyRet < 0) { 11253 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11254 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11255 throw new PackageManagerException(copyRet, message); 11256 } 11257 } 11258 } 11259 11260 /** 11261 * Extract the MountService "container ID" from the full code path of an 11262 * .apk. 11263 */ 11264 static String cidFromCodePath(String fullCodePath) { 11265 int eidx = fullCodePath.lastIndexOf("/"); 11266 String subStr1 = fullCodePath.substring(0, eidx); 11267 int sidx = subStr1.lastIndexOf("/"); 11268 return subStr1.substring(sidx+1, eidx); 11269 } 11270 11271 /** 11272 * Logic to handle installation of ASEC applications, including copying and 11273 * renaming logic. 11274 */ 11275 class AsecInstallArgs extends InstallArgs { 11276 static final String RES_FILE_NAME = "pkg.apk"; 11277 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11278 11279 String cid; 11280 String packagePath; 11281 String resourcePath; 11282 11283 /** New install */ 11284 AsecInstallArgs(InstallParams params) { 11285 super(params.origin, params.move, params.observer, params.installFlags, 11286 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11287 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11288 params.grantedRuntimePermissions); 11289 } 11290 11291 /** Existing install */ 11292 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11293 boolean isExternal, boolean isForwardLocked) { 11294 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11295 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11296 instructionSets, null, null); 11297 // Hackily pretend we're still looking at a full code path 11298 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11299 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11300 } 11301 11302 // Extract cid from fullCodePath 11303 int eidx = fullCodePath.lastIndexOf("/"); 11304 String subStr1 = fullCodePath.substring(0, eidx); 11305 int sidx = subStr1.lastIndexOf("/"); 11306 cid = subStr1.substring(sidx+1, eidx); 11307 setMountPath(subStr1); 11308 } 11309 11310 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11311 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11312 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11313 instructionSets, null, null); 11314 this.cid = cid; 11315 setMountPath(PackageHelper.getSdDir(cid)); 11316 } 11317 11318 void createCopyFile() { 11319 cid = mInstallerService.allocateExternalStageCidLegacy(); 11320 } 11321 11322 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11323 if (origin.staged) { 11324 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11325 cid = origin.cid; 11326 setMountPath(PackageHelper.getSdDir(cid)); 11327 return PackageManager.INSTALL_SUCCEEDED; 11328 } 11329 11330 if (temp) { 11331 createCopyFile(); 11332 } else { 11333 /* 11334 * Pre-emptively destroy the container since it's destroyed if 11335 * copying fails due to it existing anyway. 11336 */ 11337 PackageHelper.destroySdDir(cid); 11338 } 11339 11340 final String newMountPath = imcs.copyPackageToContainer( 11341 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11342 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11343 11344 if (newMountPath != null) { 11345 setMountPath(newMountPath); 11346 return PackageManager.INSTALL_SUCCEEDED; 11347 } else { 11348 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11349 } 11350 } 11351 11352 @Override 11353 String getCodePath() { 11354 return packagePath; 11355 } 11356 11357 @Override 11358 String getResourcePath() { 11359 return resourcePath; 11360 } 11361 11362 int doPreInstall(int status) { 11363 if (status != PackageManager.INSTALL_SUCCEEDED) { 11364 // Destroy container 11365 PackageHelper.destroySdDir(cid); 11366 } else { 11367 boolean mounted = PackageHelper.isContainerMounted(cid); 11368 if (!mounted) { 11369 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11370 Process.SYSTEM_UID); 11371 if (newMountPath != null) { 11372 setMountPath(newMountPath); 11373 } else { 11374 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11375 } 11376 } 11377 } 11378 return status; 11379 } 11380 11381 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11382 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11383 String newMountPath = null; 11384 if (PackageHelper.isContainerMounted(cid)) { 11385 // Unmount the container 11386 if (!PackageHelper.unMountSdDir(cid)) { 11387 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11388 return false; 11389 } 11390 } 11391 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11392 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11393 " which might be stale. Will try to clean up."); 11394 // Clean up the stale container and proceed to recreate. 11395 if (!PackageHelper.destroySdDir(newCacheId)) { 11396 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11397 return false; 11398 } 11399 // Successfully cleaned up stale container. Try to rename again. 11400 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11401 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11402 + " inspite of cleaning it up."); 11403 return false; 11404 } 11405 } 11406 if (!PackageHelper.isContainerMounted(newCacheId)) { 11407 Slog.w(TAG, "Mounting container " + newCacheId); 11408 newMountPath = PackageHelper.mountSdDir(newCacheId, 11409 getEncryptKey(), Process.SYSTEM_UID); 11410 } else { 11411 newMountPath = PackageHelper.getSdDir(newCacheId); 11412 } 11413 if (newMountPath == null) { 11414 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11415 return false; 11416 } 11417 Log.i(TAG, "Succesfully renamed " + cid + 11418 " to " + newCacheId + 11419 " at new path: " + newMountPath); 11420 cid = newCacheId; 11421 11422 final File beforeCodeFile = new File(packagePath); 11423 setMountPath(newMountPath); 11424 final File afterCodeFile = new File(packagePath); 11425 11426 // Reflect the rename in scanned details 11427 pkg.codePath = afterCodeFile.getAbsolutePath(); 11428 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11429 pkg.baseCodePath); 11430 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11431 pkg.splitCodePaths); 11432 11433 // Reflect the rename in app info 11434 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11435 pkg.applicationInfo.setCodePath(pkg.codePath); 11436 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11437 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11438 pkg.applicationInfo.setResourcePath(pkg.codePath); 11439 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11440 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11441 11442 return true; 11443 } 11444 11445 private void setMountPath(String mountPath) { 11446 final File mountFile = new File(mountPath); 11447 11448 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11449 if (monolithicFile.exists()) { 11450 packagePath = monolithicFile.getAbsolutePath(); 11451 if (isFwdLocked()) { 11452 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11453 } else { 11454 resourcePath = packagePath; 11455 } 11456 } else { 11457 packagePath = mountFile.getAbsolutePath(); 11458 resourcePath = packagePath; 11459 } 11460 } 11461 11462 int doPostInstall(int status, int uid) { 11463 if (status != PackageManager.INSTALL_SUCCEEDED) { 11464 cleanUp(); 11465 } else { 11466 final int groupOwner; 11467 final String protectedFile; 11468 if (isFwdLocked()) { 11469 groupOwner = UserHandle.getSharedAppGid(uid); 11470 protectedFile = RES_FILE_NAME; 11471 } else { 11472 groupOwner = -1; 11473 protectedFile = null; 11474 } 11475 11476 if (uid < Process.FIRST_APPLICATION_UID 11477 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11478 Slog.e(TAG, "Failed to finalize " + cid); 11479 PackageHelper.destroySdDir(cid); 11480 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11481 } 11482 11483 boolean mounted = PackageHelper.isContainerMounted(cid); 11484 if (!mounted) { 11485 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11486 } 11487 } 11488 return status; 11489 } 11490 11491 private void cleanUp() { 11492 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11493 11494 // Destroy secure container 11495 PackageHelper.destroySdDir(cid); 11496 } 11497 11498 private List<String> getAllCodePaths() { 11499 final File codeFile = new File(getCodePath()); 11500 if (codeFile != null && codeFile.exists()) { 11501 try { 11502 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11503 return pkg.getAllCodePaths(); 11504 } catch (PackageParserException e) { 11505 // Ignored; we tried our best 11506 } 11507 } 11508 return Collections.EMPTY_LIST; 11509 } 11510 11511 void cleanUpResourcesLI() { 11512 // Enumerate all code paths before deleting 11513 cleanUpResourcesLI(getAllCodePaths()); 11514 } 11515 11516 private void cleanUpResourcesLI(List<String> allCodePaths) { 11517 cleanUp(); 11518 removeDexFiles(allCodePaths, instructionSets); 11519 } 11520 11521 String getPackageName() { 11522 return getAsecPackageName(cid); 11523 } 11524 11525 boolean doPostDeleteLI(boolean delete) { 11526 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11527 final List<String> allCodePaths = getAllCodePaths(); 11528 boolean mounted = PackageHelper.isContainerMounted(cid); 11529 if (mounted) { 11530 // Unmount first 11531 if (PackageHelper.unMountSdDir(cid)) { 11532 mounted = false; 11533 } 11534 } 11535 if (!mounted && delete) { 11536 cleanUpResourcesLI(allCodePaths); 11537 } 11538 return !mounted; 11539 } 11540 11541 @Override 11542 int doPreCopy() { 11543 if (isFwdLocked()) { 11544 if (!PackageHelper.fixSdPermissions(cid, 11545 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11546 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11547 } 11548 } 11549 11550 return PackageManager.INSTALL_SUCCEEDED; 11551 } 11552 11553 @Override 11554 int doPostCopy(int uid) { 11555 if (isFwdLocked()) { 11556 if (uid < Process.FIRST_APPLICATION_UID 11557 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11558 RES_FILE_NAME)) { 11559 Slog.e(TAG, "Failed to finalize " + cid); 11560 PackageHelper.destroySdDir(cid); 11561 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11562 } 11563 } 11564 11565 return PackageManager.INSTALL_SUCCEEDED; 11566 } 11567 } 11568 11569 /** 11570 * Logic to handle movement of existing installed applications. 11571 */ 11572 class MoveInstallArgs extends InstallArgs { 11573 private File codeFile; 11574 private File resourceFile; 11575 11576 /** New install */ 11577 MoveInstallArgs(InstallParams params) { 11578 super(params.origin, params.move, params.observer, params.installFlags, 11579 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11580 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11581 params.grantedRuntimePermissions); 11582 } 11583 11584 int copyApk(IMediaContainerService imcs, boolean temp) { 11585 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11586 + move.fromUuid + " to " + move.toUuid); 11587 synchronized (mInstaller) { 11588 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11589 move.dataAppName, move.appId, move.seinfo) != 0) { 11590 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11591 } 11592 } 11593 11594 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11595 resourceFile = codeFile; 11596 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11597 11598 return PackageManager.INSTALL_SUCCEEDED; 11599 } 11600 11601 int doPreInstall(int status) { 11602 if (status != PackageManager.INSTALL_SUCCEEDED) { 11603 cleanUp(move.toUuid); 11604 } 11605 return status; 11606 } 11607 11608 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11609 if (status != PackageManager.INSTALL_SUCCEEDED) { 11610 cleanUp(move.toUuid); 11611 return false; 11612 } 11613 11614 // Reflect the move in app info 11615 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11616 pkg.applicationInfo.setCodePath(pkg.codePath); 11617 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11618 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11619 pkg.applicationInfo.setResourcePath(pkg.codePath); 11620 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11621 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11622 11623 return true; 11624 } 11625 11626 int doPostInstall(int status, int uid) { 11627 if (status == PackageManager.INSTALL_SUCCEEDED) { 11628 cleanUp(move.fromUuid); 11629 } else { 11630 cleanUp(move.toUuid); 11631 } 11632 return status; 11633 } 11634 11635 @Override 11636 String getCodePath() { 11637 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11638 } 11639 11640 @Override 11641 String getResourcePath() { 11642 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11643 } 11644 11645 private boolean cleanUp(String volumeUuid) { 11646 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11647 move.dataAppName); 11648 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11649 synchronized (mInstallLock) { 11650 // Clean up both app data and code 11651 removeDataDirsLI(volumeUuid, move.packageName); 11652 if (codeFile.isDirectory()) { 11653 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11654 } else { 11655 codeFile.delete(); 11656 } 11657 } 11658 return true; 11659 } 11660 11661 void cleanUpResourcesLI() { 11662 throw new UnsupportedOperationException(); 11663 } 11664 11665 boolean doPostDeleteLI(boolean delete) { 11666 throw new UnsupportedOperationException(); 11667 } 11668 } 11669 11670 static String getAsecPackageName(String packageCid) { 11671 int idx = packageCid.lastIndexOf("-"); 11672 if (idx == -1) { 11673 return packageCid; 11674 } 11675 return packageCid.substring(0, idx); 11676 } 11677 11678 // Utility method used to create code paths based on package name and available index. 11679 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11680 String idxStr = ""; 11681 int idx = 1; 11682 // Fall back to default value of idx=1 if prefix is not 11683 // part of oldCodePath 11684 if (oldCodePath != null) { 11685 String subStr = oldCodePath; 11686 // Drop the suffix right away 11687 if (suffix != null && subStr.endsWith(suffix)) { 11688 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11689 } 11690 // If oldCodePath already contains prefix find out the 11691 // ending index to either increment or decrement. 11692 int sidx = subStr.lastIndexOf(prefix); 11693 if (sidx != -1) { 11694 subStr = subStr.substring(sidx + prefix.length()); 11695 if (subStr != null) { 11696 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11697 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11698 } 11699 try { 11700 idx = Integer.parseInt(subStr); 11701 if (idx <= 1) { 11702 idx++; 11703 } else { 11704 idx--; 11705 } 11706 } catch(NumberFormatException e) { 11707 } 11708 } 11709 } 11710 } 11711 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11712 return prefix + idxStr; 11713 } 11714 11715 private File getNextCodePath(File targetDir, String packageName) { 11716 int suffix = 1; 11717 File result; 11718 do { 11719 result = new File(targetDir, packageName + "-" + suffix); 11720 suffix++; 11721 } while (result.exists()); 11722 return result; 11723 } 11724 11725 // Utility method that returns the relative package path with respect 11726 // to the installation directory. Like say for /data/data/com.test-1.apk 11727 // string com.test-1 is returned. 11728 static String deriveCodePathName(String codePath) { 11729 if (codePath == null) { 11730 return null; 11731 } 11732 final File codeFile = new File(codePath); 11733 final String name = codeFile.getName(); 11734 if (codeFile.isDirectory()) { 11735 return name; 11736 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11737 final int lastDot = name.lastIndexOf('.'); 11738 return name.substring(0, lastDot); 11739 } else { 11740 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11741 return null; 11742 } 11743 } 11744 11745 class PackageInstalledInfo { 11746 String name; 11747 int uid; 11748 // The set of users that originally had this package installed. 11749 int[] origUsers; 11750 // The set of users that now have this package installed. 11751 int[] newUsers; 11752 PackageParser.Package pkg; 11753 int returnCode; 11754 String returnMsg; 11755 PackageRemovedInfo removedInfo; 11756 11757 public void setError(int code, String msg) { 11758 returnCode = code; 11759 returnMsg = msg; 11760 Slog.w(TAG, msg); 11761 } 11762 11763 public void setError(String msg, PackageParserException e) { 11764 returnCode = e.error; 11765 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11766 Slog.w(TAG, msg, e); 11767 } 11768 11769 public void setError(String msg, PackageManagerException e) { 11770 returnCode = e.error; 11771 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11772 Slog.w(TAG, msg, e); 11773 } 11774 11775 // In some error cases we want to convey more info back to the observer 11776 String origPackage; 11777 String origPermission; 11778 } 11779 11780 /* 11781 * Install a non-existing package. 11782 */ 11783 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11784 UserHandle user, String installerPackageName, String volumeUuid, 11785 PackageInstalledInfo res) { 11786 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 11787 11788 // Remember this for later, in case we need to rollback this install 11789 String pkgName = pkg.packageName; 11790 11791 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11792 final boolean dataDirExists = Environment 11793 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11794 11795 synchronized(mPackages) { 11796 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11797 // A package with the same name is already installed, though 11798 // it has been renamed to an older name. The package we 11799 // are trying to install should be installed as an update to 11800 // the existing one, but that has not been requested, so bail. 11801 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11802 + " without first uninstalling package running as " 11803 + mSettings.mRenamedPackages.get(pkgName)); 11804 return; 11805 } 11806 if (mPackages.containsKey(pkgName)) { 11807 // Don't allow installation over an existing package with the same name. 11808 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11809 + " without first uninstalling."); 11810 return; 11811 } 11812 } 11813 11814 try { 11815 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 11816 System.currentTimeMillis(), user); 11817 11818 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11819 // delete the partially installed application. the data directory will have to be 11820 // restored if it was already existing 11821 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11822 // remove package from internal structures. Note that we want deletePackageX to 11823 // delete the package data and cache directories that it created in 11824 // scanPackageLocked, unless those directories existed before we even tried to 11825 // install. 11826 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11827 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11828 res.removedInfo, true); 11829 } 11830 11831 } catch (PackageManagerException e) { 11832 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11833 } 11834 11835 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11836 } 11837 11838 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11839 // Can't rotate keys during boot or if sharedUser. 11840 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11841 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11842 return false; 11843 } 11844 // app is using upgradeKeySets; make sure all are valid 11845 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11846 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11847 for (int i = 0; i < upgradeKeySets.length; i++) { 11848 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11849 Slog.wtf(TAG, "Package " 11850 + (oldPs.name != null ? oldPs.name : "<null>") 11851 + " contains upgrade-key-set reference to unknown key-set: " 11852 + upgradeKeySets[i] 11853 + " reverting to signatures check."); 11854 return false; 11855 } 11856 } 11857 return true; 11858 } 11859 11860 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11861 // Upgrade keysets are being used. Determine if new package has a superset of the 11862 // required keys. 11863 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11864 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11865 for (int i = 0; i < upgradeKeySets.length; i++) { 11866 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11867 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11868 return true; 11869 } 11870 } 11871 return false; 11872 } 11873 11874 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11875 UserHandle user, String installerPackageName, String volumeUuid, 11876 PackageInstalledInfo res) { 11877 final PackageParser.Package oldPackage; 11878 final String pkgName = pkg.packageName; 11879 final int[] allUsers; 11880 final boolean[] perUserInstalled; 11881 11882 // First find the old package info and check signatures 11883 synchronized(mPackages) { 11884 oldPackage = mPackages.get(pkgName); 11885 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11886 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11887 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11888 if(!checkUpgradeKeySetLP(ps, pkg)) { 11889 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11890 "New package not signed by keys specified by upgrade-keysets: " 11891 + pkgName); 11892 return; 11893 } 11894 } else { 11895 // default to original signature matching 11896 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11897 != PackageManager.SIGNATURE_MATCH) { 11898 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11899 "New package has a different signature: " + pkgName); 11900 return; 11901 } 11902 } 11903 11904 // In case of rollback, remember per-user/profile install state 11905 allUsers = sUserManager.getUserIds(); 11906 perUserInstalled = new boolean[allUsers.length]; 11907 for (int i = 0; i < allUsers.length; i++) { 11908 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11909 } 11910 } 11911 11912 boolean sysPkg = (isSystemApp(oldPackage)); 11913 if (sysPkg) { 11914 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11915 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11916 } else { 11917 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11918 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11919 } 11920 } 11921 11922 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11923 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11924 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11925 String volumeUuid, PackageInstalledInfo res) { 11926 String pkgName = deletedPackage.packageName; 11927 boolean deletedPkg = true; 11928 boolean updatedSettings = false; 11929 11930 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11931 + deletedPackage); 11932 long origUpdateTime; 11933 if (pkg.mExtras != null) { 11934 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11935 } else { 11936 origUpdateTime = 0; 11937 } 11938 11939 // First delete the existing package while retaining the data directory 11940 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11941 res.removedInfo, true)) { 11942 // If the existing package wasn't successfully deleted 11943 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11944 deletedPkg = false; 11945 } else { 11946 // Successfully deleted the old package; proceed with replace. 11947 11948 // If deleted package lived in a container, give users a chance to 11949 // relinquish resources before killing. 11950 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11951 if (DEBUG_INSTALL) { 11952 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11953 } 11954 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11955 final ArrayList<String> pkgList = new ArrayList<String>(1); 11956 pkgList.add(deletedPackage.applicationInfo.packageName); 11957 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11958 } 11959 11960 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11961 try { 11962 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 11963 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11964 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11965 perUserInstalled, res, user); 11966 updatedSettings = true; 11967 } catch (PackageManagerException e) { 11968 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11969 } 11970 } 11971 11972 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11973 // remove package from internal structures. Note that we want deletePackageX to 11974 // delete the package data and cache directories that it created in 11975 // scanPackageLocked, unless those directories existed before we even tried to 11976 // install. 11977 if(updatedSettings) { 11978 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11979 deletePackageLI( 11980 pkgName, null, true, allUsers, perUserInstalled, 11981 PackageManager.DELETE_KEEP_DATA, 11982 res.removedInfo, true); 11983 } 11984 // Since we failed to install the new package we need to restore the old 11985 // package that we deleted. 11986 if (deletedPkg) { 11987 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11988 File restoreFile = new File(deletedPackage.codePath); 11989 // Parse old package 11990 boolean oldExternal = isExternal(deletedPackage); 11991 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11992 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11993 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11994 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11995 try { 11996 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11997 } catch (PackageManagerException e) { 11998 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11999 + e.getMessage()); 12000 return; 12001 } 12002 // Restore of old package succeeded. Update permissions. 12003 // writer 12004 synchronized (mPackages) { 12005 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12006 UPDATE_PERMISSIONS_ALL); 12007 // can downgrade to reader 12008 mSettings.writeLPr(); 12009 } 12010 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12011 } 12012 } 12013 } 12014 12015 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12016 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12017 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12018 String volumeUuid, PackageInstalledInfo res) { 12019 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12020 + ", old=" + deletedPackage); 12021 boolean disabledSystem = false; 12022 boolean updatedSettings = false; 12023 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12024 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12025 != 0) { 12026 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12027 } 12028 String packageName = deletedPackage.packageName; 12029 if (packageName == null) { 12030 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12031 "Attempt to delete null packageName."); 12032 return; 12033 } 12034 PackageParser.Package oldPkg; 12035 PackageSetting oldPkgSetting; 12036 // reader 12037 synchronized (mPackages) { 12038 oldPkg = mPackages.get(packageName); 12039 oldPkgSetting = mSettings.mPackages.get(packageName); 12040 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12041 (oldPkgSetting == null)) { 12042 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12043 "Couldn't find package:" + packageName + " information"); 12044 return; 12045 } 12046 } 12047 12048 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12049 12050 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12051 res.removedInfo.removedPackage = packageName; 12052 // Remove existing system package 12053 removePackageLI(oldPkgSetting, true); 12054 // writer 12055 synchronized (mPackages) { 12056 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12057 if (!disabledSystem && deletedPackage != null) { 12058 // We didn't need to disable the .apk as a current system package, 12059 // which means we are replacing another update that is already 12060 // installed. We need to make sure to delete the older one's .apk. 12061 res.removedInfo.args = createInstallArgsForExisting(0, 12062 deletedPackage.applicationInfo.getCodePath(), 12063 deletedPackage.applicationInfo.getResourcePath(), 12064 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12065 } else { 12066 res.removedInfo.args = null; 12067 } 12068 } 12069 12070 // Successfully disabled the old package. Now proceed with re-installation 12071 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12072 12073 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12074 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12075 12076 PackageParser.Package newPackage = null; 12077 try { 12078 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12079 if (newPackage.mExtras != null) { 12080 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12081 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12082 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12083 12084 // is the update attempting to change shared user? that isn't going to work... 12085 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12086 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12087 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12088 + " to " + newPkgSetting.sharedUser); 12089 updatedSettings = true; 12090 } 12091 } 12092 12093 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12094 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12095 perUserInstalled, res, user); 12096 updatedSettings = true; 12097 } 12098 12099 } catch (PackageManagerException e) { 12100 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12101 } 12102 12103 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12104 // Re installation failed. Restore old information 12105 // Remove new pkg information 12106 if (newPackage != null) { 12107 removeInstalledPackageLI(newPackage, true); 12108 } 12109 // Add back the old system package 12110 try { 12111 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12112 } catch (PackageManagerException e) { 12113 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12114 } 12115 // Restore the old system information in Settings 12116 synchronized (mPackages) { 12117 if (disabledSystem) { 12118 mSettings.enableSystemPackageLPw(packageName); 12119 } 12120 if (updatedSettings) { 12121 mSettings.setInstallerPackageName(packageName, 12122 oldPkgSetting.installerPackageName); 12123 } 12124 mSettings.writeLPr(); 12125 } 12126 } 12127 } 12128 12129 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12130 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12131 UserHandle user) { 12132 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12133 12134 String pkgName = newPackage.packageName; 12135 synchronized (mPackages) { 12136 //write settings. the installStatus will be incomplete at this stage. 12137 //note that the new package setting would have already been 12138 //added to mPackages. It hasn't been persisted yet. 12139 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12140 mSettings.writeLPr(); 12141 } 12142 12143 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12144 synchronized (mPackages) { 12145 updatePermissionsLPw(newPackage.packageName, newPackage, 12146 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12147 ? UPDATE_PERMISSIONS_ALL : 0)); 12148 // For system-bundled packages, we assume that installing an upgraded version 12149 // of the package implies that the user actually wants to run that new code, 12150 // so we enable the package. 12151 PackageSetting ps = mSettings.mPackages.get(pkgName); 12152 if (ps != null) { 12153 if (isSystemApp(newPackage)) { 12154 // NB: implicit assumption that system package upgrades apply to all users 12155 if (DEBUG_INSTALL) { 12156 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12157 } 12158 if (res.origUsers != null) { 12159 for (int userHandle : res.origUsers) { 12160 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12161 userHandle, installerPackageName); 12162 } 12163 } 12164 // Also convey the prior install/uninstall state 12165 if (allUsers != null && perUserInstalled != null) { 12166 for (int i = 0; i < allUsers.length; i++) { 12167 if (DEBUG_INSTALL) { 12168 Slog.d(TAG, " user " + allUsers[i] 12169 + " => " + perUserInstalled[i]); 12170 } 12171 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12172 } 12173 // these install state changes will be persisted in the 12174 // upcoming call to mSettings.writeLPr(). 12175 } 12176 } 12177 // It's implied that when a user requests installation, they want the app to be 12178 // installed and enabled. 12179 int userId = user.getIdentifier(); 12180 if (userId != UserHandle.USER_ALL) { 12181 ps.setInstalled(true, userId); 12182 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12183 } 12184 } 12185 res.name = pkgName; 12186 res.uid = newPackage.applicationInfo.uid; 12187 res.pkg = newPackage; 12188 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12189 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12190 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12191 //to update install status 12192 mSettings.writeLPr(); 12193 } 12194 12195 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12196 } 12197 12198 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12199 try { 12200 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12201 installPackageLI(args, res); 12202 } finally { 12203 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12204 } 12205 } 12206 12207 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12208 final int installFlags = args.installFlags; 12209 final String installerPackageName = args.installerPackageName; 12210 final String volumeUuid = args.volumeUuid; 12211 final File tmpPackageFile = new File(args.getCodePath()); 12212 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12213 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12214 || (args.volumeUuid != null)); 12215 boolean replace = false; 12216 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12217 if (args.move != null) { 12218 // moving a complete application; perfom an initial scan on the new install location 12219 scanFlags |= SCAN_INITIAL; 12220 } 12221 // Result object to be returned 12222 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12223 12224 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12225 12226 // Retrieve PackageSettings and parse package 12227 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12228 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12229 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12230 PackageParser pp = new PackageParser(); 12231 pp.setSeparateProcesses(mSeparateProcesses); 12232 pp.setDisplayMetrics(mMetrics); 12233 12234 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12235 final PackageParser.Package pkg; 12236 try { 12237 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12238 } catch (PackageParserException e) { 12239 res.setError("Failed parse during installPackageLI", e); 12240 return; 12241 } finally { 12242 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12243 } 12244 12245 // Mark that we have an install time CPU ABI override. 12246 pkg.cpuAbiOverride = args.abiOverride; 12247 12248 String pkgName = res.name = pkg.packageName; 12249 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12250 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12251 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12252 return; 12253 } 12254 } 12255 12256 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12257 try { 12258 pp.collectCertificates(pkg, parseFlags); 12259 pp.collectManifestDigest(pkg); 12260 } catch (PackageParserException e) { 12261 res.setError("Failed collect during installPackageLI", e); 12262 return; 12263 } finally { 12264 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12265 } 12266 12267 /* If the installer passed in a manifest digest, compare it now. */ 12268 if (args.manifestDigest != null) { 12269 if (DEBUG_INSTALL) { 12270 final String parsedManifest = pkg.manifestDigest == null ? "null" 12271 : pkg.manifestDigest.toString(); 12272 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12273 + parsedManifest); 12274 } 12275 12276 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12277 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12278 return; 12279 } 12280 } else if (DEBUG_INSTALL) { 12281 final String parsedManifest = pkg.manifestDigest == null 12282 ? "null" : pkg.manifestDigest.toString(); 12283 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12284 } 12285 12286 // Get rid of all references to package scan path via parser. 12287 pp = null; 12288 String oldCodePath = null; 12289 boolean systemApp = false; 12290 synchronized (mPackages) { 12291 // Check if installing already existing package 12292 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12293 String oldName = mSettings.mRenamedPackages.get(pkgName); 12294 if (pkg.mOriginalPackages != null 12295 && pkg.mOriginalPackages.contains(oldName) 12296 && mPackages.containsKey(oldName)) { 12297 // This package is derived from an original package, 12298 // and this device has been updating from that original 12299 // name. We must continue using the original name, so 12300 // rename the new package here. 12301 pkg.setPackageName(oldName); 12302 pkgName = pkg.packageName; 12303 replace = true; 12304 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12305 + oldName + " pkgName=" + pkgName); 12306 } else if (mPackages.containsKey(pkgName)) { 12307 // This package, under its official name, already exists 12308 // on the device; we should replace it. 12309 replace = true; 12310 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12311 } 12312 12313 // Prevent apps opting out from runtime permissions 12314 if (replace) { 12315 PackageParser.Package oldPackage = mPackages.get(pkgName); 12316 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12317 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12318 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12319 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12320 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12321 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12322 + " doesn't support runtime permissions but the old" 12323 + " target SDK " + oldTargetSdk + " does."); 12324 return; 12325 } 12326 } 12327 } 12328 12329 PackageSetting ps = mSettings.mPackages.get(pkgName); 12330 if (ps != null) { 12331 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12332 12333 // Quick sanity check that we're signed correctly if updating; 12334 // we'll check this again later when scanning, but we want to 12335 // bail early here before tripping over redefined permissions. 12336 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12337 if (!checkUpgradeKeySetLP(ps, pkg)) { 12338 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12339 + pkg.packageName + " upgrade keys do not match the " 12340 + "previously installed version"); 12341 return; 12342 } 12343 } else { 12344 try { 12345 verifySignaturesLP(ps, pkg); 12346 } catch (PackageManagerException e) { 12347 res.setError(e.error, e.getMessage()); 12348 return; 12349 } 12350 } 12351 12352 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12353 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12354 systemApp = (ps.pkg.applicationInfo.flags & 12355 ApplicationInfo.FLAG_SYSTEM) != 0; 12356 } 12357 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12358 } 12359 12360 // Check whether the newly-scanned package wants to define an already-defined perm 12361 int N = pkg.permissions.size(); 12362 for (int i = N-1; i >= 0; i--) { 12363 PackageParser.Permission perm = pkg.permissions.get(i); 12364 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12365 if (bp != null) { 12366 // If the defining package is signed with our cert, it's okay. This 12367 // also includes the "updating the same package" case, of course. 12368 // "updating same package" could also involve key-rotation. 12369 final boolean sigsOk; 12370 if (bp.sourcePackage.equals(pkg.packageName) 12371 && (bp.packageSetting instanceof PackageSetting) 12372 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12373 scanFlags))) { 12374 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12375 } else { 12376 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12377 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12378 } 12379 if (!sigsOk) { 12380 // If the owning package is the system itself, we log but allow 12381 // install to proceed; we fail the install on all other permission 12382 // redefinitions. 12383 if (!bp.sourcePackage.equals("android")) { 12384 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12385 + pkg.packageName + " attempting to redeclare permission " 12386 + perm.info.name + " already owned by " + bp.sourcePackage); 12387 res.origPermission = perm.info.name; 12388 res.origPackage = bp.sourcePackage; 12389 return; 12390 } else { 12391 Slog.w(TAG, "Package " + pkg.packageName 12392 + " attempting to redeclare system permission " 12393 + perm.info.name + "; ignoring new declaration"); 12394 pkg.permissions.remove(i); 12395 } 12396 } 12397 } 12398 } 12399 12400 } 12401 12402 if (systemApp && onExternal) { 12403 // Disable updates to system apps on sdcard 12404 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12405 "Cannot install updates to system apps on sdcard"); 12406 return; 12407 } 12408 12409 if (args.move != null) { 12410 // We did an in-place move, so dex is ready to roll 12411 scanFlags |= SCAN_NO_DEX; 12412 scanFlags |= SCAN_MOVE; 12413 12414 synchronized (mPackages) { 12415 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12416 if (ps == null) { 12417 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12418 "Missing settings for moved package " + pkgName); 12419 } 12420 12421 // We moved the entire application as-is, so bring over the 12422 // previously derived ABI information. 12423 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12424 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12425 } 12426 12427 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12428 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12429 scanFlags |= SCAN_NO_DEX; 12430 12431 try { 12432 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12433 true /* extract libs */); 12434 } catch (PackageManagerException pme) { 12435 Slog.e(TAG, "Error deriving application ABI", pme); 12436 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12437 return; 12438 } 12439 12440 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12441 int result = mPackageDexOptimizer 12442 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12443 false /* defer */, false /* inclDependencies */); 12444 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12445 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12446 return; 12447 } 12448 } 12449 12450 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12451 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12452 return; 12453 } 12454 12455 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12456 12457 if (replace) { 12458 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12459 installerPackageName, volumeUuid, res); 12460 } else { 12461 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12462 args.user, installerPackageName, volumeUuid, res); 12463 } 12464 synchronized (mPackages) { 12465 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12466 if (ps != null) { 12467 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12468 } 12469 } 12470 } 12471 12472 private void startIntentFilterVerifications(int userId, boolean replacing, 12473 PackageParser.Package pkg) { 12474 if (mIntentFilterVerifierComponent == null) { 12475 Slog.w(TAG, "No IntentFilter verification will not be done as " 12476 + "there is no IntentFilterVerifier available!"); 12477 return; 12478 } 12479 12480 final int verifierUid = getPackageUid( 12481 mIntentFilterVerifierComponent.getPackageName(), 12482 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12483 12484 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12485 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12486 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12487 mHandler.sendMessage(msg); 12488 } 12489 12490 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12491 PackageParser.Package pkg) { 12492 int size = pkg.activities.size(); 12493 if (size == 0) { 12494 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12495 "No activity, so no need to verify any IntentFilter!"); 12496 return; 12497 } 12498 12499 final boolean hasDomainURLs = hasDomainURLs(pkg); 12500 if (!hasDomainURLs) { 12501 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12502 "No domain URLs, so no need to verify any IntentFilter!"); 12503 return; 12504 } 12505 12506 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12507 + " if any IntentFilter from the " + size 12508 + " Activities needs verification ..."); 12509 12510 int count = 0; 12511 final String packageName = pkg.packageName; 12512 12513 synchronized (mPackages) { 12514 // If this is a new install and we see that we've already run verification for this 12515 // package, we have nothing to do: it means the state was restored from backup. 12516 if (!replacing) { 12517 IntentFilterVerificationInfo ivi = 12518 mSettings.getIntentFilterVerificationLPr(packageName); 12519 if (ivi != null) { 12520 if (DEBUG_DOMAIN_VERIFICATION) { 12521 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12522 + ivi.getStatusString()); 12523 } 12524 return; 12525 } 12526 } 12527 12528 // If any filters need to be verified, then all need to be. 12529 boolean needToVerify = false; 12530 for (PackageParser.Activity a : pkg.activities) { 12531 for (ActivityIntentInfo filter : a.intents) { 12532 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12533 if (DEBUG_DOMAIN_VERIFICATION) { 12534 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12535 } 12536 needToVerify = true; 12537 break; 12538 } 12539 } 12540 } 12541 12542 if (needToVerify) { 12543 final int verificationId = mIntentFilterVerificationToken++; 12544 for (PackageParser.Activity a : pkg.activities) { 12545 for (ActivityIntentInfo filter : a.intents) { 12546 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12547 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12548 "Verification needed for IntentFilter:" + filter.toString()); 12549 mIntentFilterVerifier.addOneIntentFilterVerification( 12550 verifierUid, userId, verificationId, filter, packageName); 12551 count++; 12552 } 12553 } 12554 } 12555 } 12556 } 12557 12558 if (count > 0) { 12559 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12560 + " IntentFilter verification" + (count > 1 ? "s" : "") 12561 + " for userId:" + userId); 12562 mIntentFilterVerifier.startVerifications(userId); 12563 } else { 12564 if (DEBUG_DOMAIN_VERIFICATION) { 12565 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12566 } 12567 } 12568 } 12569 12570 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12571 final ComponentName cn = filter.activity.getComponentName(); 12572 final String packageName = cn.getPackageName(); 12573 12574 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12575 packageName); 12576 if (ivi == null) { 12577 return true; 12578 } 12579 int status = ivi.getStatus(); 12580 switch (status) { 12581 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12582 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12583 return true; 12584 12585 default: 12586 // Nothing to do 12587 return false; 12588 } 12589 } 12590 12591 private static boolean isMultiArch(PackageSetting ps) { 12592 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12593 } 12594 12595 private static boolean isMultiArch(ApplicationInfo info) { 12596 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12597 } 12598 12599 private static boolean isExternal(PackageParser.Package pkg) { 12600 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12601 } 12602 12603 private static boolean isExternal(PackageSetting ps) { 12604 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12605 } 12606 12607 private static boolean isExternal(ApplicationInfo info) { 12608 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12609 } 12610 12611 private static boolean isSystemApp(PackageParser.Package pkg) { 12612 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12613 } 12614 12615 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12616 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12617 } 12618 12619 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12620 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12621 } 12622 12623 private static boolean isSystemApp(PackageSetting ps) { 12624 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12625 } 12626 12627 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12628 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12629 } 12630 12631 private int packageFlagsToInstallFlags(PackageSetting ps) { 12632 int installFlags = 0; 12633 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12634 // This existing package was an external ASEC install when we have 12635 // the external flag without a UUID 12636 installFlags |= PackageManager.INSTALL_EXTERNAL; 12637 } 12638 if (ps.isForwardLocked()) { 12639 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12640 } 12641 return installFlags; 12642 } 12643 12644 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12645 if (isExternal(pkg)) { 12646 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12647 return mSettings.getExternalVersion(); 12648 } else { 12649 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12650 } 12651 } else { 12652 return mSettings.getInternalVersion(); 12653 } 12654 } 12655 12656 private void deleteTempPackageFiles() { 12657 final FilenameFilter filter = new FilenameFilter() { 12658 public boolean accept(File dir, String name) { 12659 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12660 } 12661 }; 12662 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12663 file.delete(); 12664 } 12665 } 12666 12667 @Override 12668 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12669 int flags) { 12670 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12671 flags); 12672 } 12673 12674 @Override 12675 public void deletePackage(final String packageName, 12676 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12677 mContext.enforceCallingOrSelfPermission( 12678 android.Manifest.permission.DELETE_PACKAGES, null); 12679 Preconditions.checkNotNull(packageName); 12680 Preconditions.checkNotNull(observer); 12681 final int uid = Binder.getCallingUid(); 12682 if (UserHandle.getUserId(uid) != userId) { 12683 mContext.enforceCallingPermission( 12684 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12685 "deletePackage for user " + userId); 12686 } 12687 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12688 try { 12689 observer.onPackageDeleted(packageName, 12690 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12691 } catch (RemoteException re) { 12692 } 12693 return; 12694 } 12695 12696 boolean uninstallBlocked = false; 12697 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12698 int[] users = sUserManager.getUserIds(); 12699 for (int i = 0; i < users.length; ++i) { 12700 if (getBlockUninstallForUser(packageName, users[i])) { 12701 uninstallBlocked = true; 12702 break; 12703 } 12704 } 12705 } else { 12706 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12707 } 12708 if (uninstallBlocked) { 12709 try { 12710 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12711 null); 12712 } catch (RemoteException re) { 12713 } 12714 return; 12715 } 12716 12717 if (DEBUG_REMOVE) { 12718 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12719 } 12720 // Queue up an async operation since the package deletion may take a little while. 12721 mHandler.post(new Runnable() { 12722 public void run() { 12723 mHandler.removeCallbacks(this); 12724 final int returnCode = deletePackageX(packageName, userId, flags); 12725 if (observer != null) { 12726 try { 12727 observer.onPackageDeleted(packageName, returnCode, null); 12728 } catch (RemoteException e) { 12729 Log.i(TAG, "Observer no longer exists."); 12730 } //end catch 12731 } //end if 12732 } //end run 12733 }); 12734 } 12735 12736 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12737 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12738 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12739 try { 12740 if (dpm != null) { 12741 if (dpm.isDeviceOwner(packageName)) { 12742 return true; 12743 } 12744 int[] users; 12745 if (userId == UserHandle.USER_ALL) { 12746 users = sUserManager.getUserIds(); 12747 } else { 12748 users = new int[]{userId}; 12749 } 12750 for (int i = 0; i < users.length; ++i) { 12751 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12752 return true; 12753 } 12754 } 12755 } 12756 } catch (RemoteException e) { 12757 } 12758 return false; 12759 } 12760 12761 /** 12762 * This method is an internal method that could be get invoked either 12763 * to delete an installed package or to clean up a failed installation. 12764 * After deleting an installed package, a broadcast is sent to notify any 12765 * listeners that the package has been installed. For cleaning up a failed 12766 * installation, the broadcast is not necessary since the package's 12767 * installation wouldn't have sent the initial broadcast either 12768 * The key steps in deleting a package are 12769 * deleting the package information in internal structures like mPackages, 12770 * deleting the packages base directories through installd 12771 * updating mSettings to reflect current status 12772 * persisting settings for later use 12773 * sending a broadcast if necessary 12774 */ 12775 private int deletePackageX(String packageName, int userId, int flags) { 12776 final PackageRemovedInfo info = new PackageRemovedInfo(); 12777 final boolean res; 12778 12779 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12780 ? UserHandle.ALL : new UserHandle(userId); 12781 12782 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12783 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12784 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12785 } 12786 12787 boolean removedForAllUsers = false; 12788 boolean systemUpdate = false; 12789 12790 // for the uninstall-updates case and restricted profiles, remember the per- 12791 // userhandle installed state 12792 int[] allUsers; 12793 boolean[] perUserInstalled; 12794 synchronized (mPackages) { 12795 PackageSetting ps = mSettings.mPackages.get(packageName); 12796 allUsers = sUserManager.getUserIds(); 12797 perUserInstalled = new boolean[allUsers.length]; 12798 for (int i = 0; i < allUsers.length; i++) { 12799 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12800 } 12801 } 12802 12803 synchronized (mInstallLock) { 12804 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12805 res = deletePackageLI(packageName, removeForUser, 12806 true, allUsers, perUserInstalled, 12807 flags | REMOVE_CHATTY, info, true); 12808 systemUpdate = info.isRemovedPackageSystemUpdate; 12809 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12810 removedForAllUsers = true; 12811 } 12812 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12813 + " removedForAllUsers=" + removedForAllUsers); 12814 } 12815 12816 if (res) { 12817 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12818 12819 // If the removed package was a system update, the old system package 12820 // was re-enabled; we need to broadcast this information 12821 if (systemUpdate) { 12822 Bundle extras = new Bundle(1); 12823 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12824 ? info.removedAppId : info.uid); 12825 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12826 12827 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12828 extras, null, null, null); 12829 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12830 extras, null, null, null); 12831 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12832 null, packageName, null, null); 12833 } 12834 } 12835 // Force a gc here. 12836 Runtime.getRuntime().gc(); 12837 // Delete the resources here after sending the broadcast to let 12838 // other processes clean up before deleting resources. 12839 if (info.args != null) { 12840 synchronized (mInstallLock) { 12841 info.args.doPostDeleteLI(true); 12842 } 12843 } 12844 12845 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12846 } 12847 12848 class PackageRemovedInfo { 12849 String removedPackage; 12850 int uid = -1; 12851 int removedAppId = -1; 12852 int[] removedUsers = null; 12853 boolean isRemovedPackageSystemUpdate = false; 12854 // Clean up resources deleted packages. 12855 InstallArgs args = null; 12856 12857 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12858 Bundle extras = new Bundle(1); 12859 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12860 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12861 if (replacing) { 12862 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12863 } 12864 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12865 if (removedPackage != null) { 12866 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12867 extras, null, null, removedUsers); 12868 if (fullRemove && !replacing) { 12869 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12870 extras, null, null, removedUsers); 12871 } 12872 } 12873 if (removedAppId >= 0) { 12874 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12875 removedUsers); 12876 } 12877 } 12878 } 12879 12880 /* 12881 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12882 * flag is not set, the data directory is removed as well. 12883 * make sure this flag is set for partially installed apps. If not its meaningless to 12884 * delete a partially installed application. 12885 */ 12886 private void removePackageDataLI(PackageSetting ps, 12887 int[] allUserHandles, boolean[] perUserInstalled, 12888 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12889 String packageName = ps.name; 12890 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12891 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12892 // Retrieve object to delete permissions for shared user later on 12893 final PackageSetting deletedPs; 12894 // reader 12895 synchronized (mPackages) { 12896 deletedPs = mSettings.mPackages.get(packageName); 12897 if (outInfo != null) { 12898 outInfo.removedPackage = packageName; 12899 outInfo.removedUsers = deletedPs != null 12900 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12901 : null; 12902 } 12903 } 12904 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12905 removeDataDirsLI(ps.volumeUuid, packageName); 12906 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12907 } 12908 // writer 12909 synchronized (mPackages) { 12910 if (deletedPs != null) { 12911 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12912 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12913 clearDefaultBrowserIfNeeded(packageName); 12914 if (outInfo != null) { 12915 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12916 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12917 } 12918 updatePermissionsLPw(deletedPs.name, null, 0); 12919 if (deletedPs.sharedUser != null) { 12920 // Remove permissions associated with package. Since runtime 12921 // permissions are per user we have to kill the removed package 12922 // or packages running under the shared user of the removed 12923 // package if revoking the permissions requested only by the removed 12924 // package is successful and this causes a change in gids. 12925 for (int userId : UserManagerService.getInstance().getUserIds()) { 12926 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12927 userId); 12928 if (userIdToKill == UserHandle.USER_ALL 12929 || userIdToKill >= UserHandle.USER_OWNER) { 12930 // If gids changed for this user, kill all affected packages. 12931 mHandler.post(new Runnable() { 12932 @Override 12933 public void run() { 12934 // This has to happen with no lock held. 12935 killSettingPackagesForUser(deletedPs, userIdToKill, 12936 KILL_APP_REASON_GIDS_CHANGED); 12937 } 12938 }); 12939 break; 12940 } 12941 } 12942 } 12943 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12944 } 12945 // make sure to preserve per-user disabled state if this removal was just 12946 // a downgrade of a system app to the factory package 12947 if (allUserHandles != null && perUserInstalled != null) { 12948 if (DEBUG_REMOVE) { 12949 Slog.d(TAG, "Propagating install state across downgrade"); 12950 } 12951 for (int i = 0; i < allUserHandles.length; i++) { 12952 if (DEBUG_REMOVE) { 12953 Slog.d(TAG, " user " + allUserHandles[i] 12954 + " => " + perUserInstalled[i]); 12955 } 12956 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12957 } 12958 } 12959 } 12960 // can downgrade to reader 12961 if (writeSettings) { 12962 // Save settings now 12963 mSettings.writeLPr(); 12964 } 12965 } 12966 if (outInfo != null) { 12967 // A user ID was deleted here. Go through all users and remove it 12968 // from KeyStore. 12969 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12970 } 12971 } 12972 12973 static boolean locationIsPrivileged(File path) { 12974 try { 12975 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12976 .getCanonicalPath(); 12977 return path.getCanonicalPath().startsWith(privilegedAppDir); 12978 } catch (IOException e) { 12979 Slog.e(TAG, "Unable to access code path " + path); 12980 } 12981 return false; 12982 } 12983 12984 /* 12985 * Tries to delete system package. 12986 */ 12987 private boolean deleteSystemPackageLI(PackageSetting newPs, 12988 int[] allUserHandles, boolean[] perUserInstalled, 12989 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12990 final boolean applyUserRestrictions 12991 = (allUserHandles != null) && (perUserInstalled != null); 12992 PackageSetting disabledPs = null; 12993 // Confirm if the system package has been updated 12994 // An updated system app can be deleted. This will also have to restore 12995 // the system pkg from system partition 12996 // reader 12997 synchronized (mPackages) { 12998 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12999 } 13000 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13001 + " disabledPs=" + disabledPs); 13002 if (disabledPs == null) { 13003 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13004 return false; 13005 } else if (DEBUG_REMOVE) { 13006 Slog.d(TAG, "Deleting system pkg from data partition"); 13007 } 13008 if (DEBUG_REMOVE) { 13009 if (applyUserRestrictions) { 13010 Slog.d(TAG, "Remembering install states:"); 13011 for (int i = 0; i < allUserHandles.length; i++) { 13012 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13013 } 13014 } 13015 } 13016 // Delete the updated package 13017 outInfo.isRemovedPackageSystemUpdate = true; 13018 if (disabledPs.versionCode < newPs.versionCode) { 13019 // Delete data for downgrades 13020 flags &= ~PackageManager.DELETE_KEEP_DATA; 13021 } else { 13022 // Preserve data by setting flag 13023 flags |= PackageManager.DELETE_KEEP_DATA; 13024 } 13025 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13026 allUserHandles, perUserInstalled, outInfo, writeSettings); 13027 if (!ret) { 13028 return false; 13029 } 13030 // writer 13031 synchronized (mPackages) { 13032 // Reinstate the old system package 13033 mSettings.enableSystemPackageLPw(newPs.name); 13034 // Remove any native libraries from the upgraded package. 13035 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13036 } 13037 // Install the system package 13038 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13039 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13040 if (locationIsPrivileged(disabledPs.codePath)) { 13041 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13042 } 13043 13044 final PackageParser.Package newPkg; 13045 try { 13046 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13047 } catch (PackageManagerException e) { 13048 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13049 return false; 13050 } 13051 13052 // writer 13053 synchronized (mPackages) { 13054 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13055 13056 updatePermissionsLPw(newPkg.packageName, newPkg, 13057 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13058 13059 if (applyUserRestrictions) { 13060 if (DEBUG_REMOVE) { 13061 Slog.d(TAG, "Propagating install state across reinstall"); 13062 } 13063 for (int i = 0; i < allUserHandles.length; i++) { 13064 if (DEBUG_REMOVE) { 13065 Slog.d(TAG, " user " + allUserHandles[i] 13066 + " => " + perUserInstalled[i]); 13067 } 13068 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13069 13070 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13071 } 13072 // Regardless of writeSettings we need to ensure that this restriction 13073 // state propagation is persisted 13074 mSettings.writeAllUsersPackageRestrictionsLPr(); 13075 } 13076 // can downgrade to reader here 13077 if (writeSettings) { 13078 mSettings.writeLPr(); 13079 } 13080 } 13081 return true; 13082 } 13083 13084 private boolean deleteInstalledPackageLI(PackageSetting ps, 13085 boolean deleteCodeAndResources, int flags, 13086 int[] allUserHandles, boolean[] perUserInstalled, 13087 PackageRemovedInfo outInfo, boolean writeSettings) { 13088 if (outInfo != null) { 13089 outInfo.uid = ps.appId; 13090 } 13091 13092 // Delete package data from internal structures and also remove data if flag is set 13093 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13094 13095 // Delete application code and resources 13096 if (deleteCodeAndResources && (outInfo != null)) { 13097 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13098 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13099 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13100 } 13101 return true; 13102 } 13103 13104 @Override 13105 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13106 int userId) { 13107 mContext.enforceCallingOrSelfPermission( 13108 android.Manifest.permission.DELETE_PACKAGES, null); 13109 synchronized (mPackages) { 13110 PackageSetting ps = mSettings.mPackages.get(packageName); 13111 if (ps == null) { 13112 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13113 return false; 13114 } 13115 if (!ps.getInstalled(userId)) { 13116 // Can't block uninstall for an app that is not installed or enabled. 13117 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13118 return false; 13119 } 13120 ps.setBlockUninstall(blockUninstall, userId); 13121 mSettings.writePackageRestrictionsLPr(userId); 13122 } 13123 return true; 13124 } 13125 13126 @Override 13127 public boolean getBlockUninstallForUser(String packageName, int userId) { 13128 synchronized (mPackages) { 13129 PackageSetting ps = mSettings.mPackages.get(packageName); 13130 if (ps == null) { 13131 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13132 return false; 13133 } 13134 return ps.getBlockUninstall(userId); 13135 } 13136 } 13137 13138 /* 13139 * This method handles package deletion in general 13140 */ 13141 private boolean deletePackageLI(String packageName, UserHandle user, 13142 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13143 int flags, PackageRemovedInfo outInfo, 13144 boolean writeSettings) { 13145 if (packageName == null) { 13146 Slog.w(TAG, "Attempt to delete null packageName."); 13147 return false; 13148 } 13149 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13150 PackageSetting ps; 13151 boolean dataOnly = false; 13152 int removeUser = -1; 13153 int appId = -1; 13154 synchronized (mPackages) { 13155 ps = mSettings.mPackages.get(packageName); 13156 if (ps == null) { 13157 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13158 return false; 13159 } 13160 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13161 && user.getIdentifier() != UserHandle.USER_ALL) { 13162 // The caller is asking that the package only be deleted for a single 13163 // user. To do this, we just mark its uninstalled state and delete 13164 // its data. If this is a system app, we only allow this to happen if 13165 // they have set the special DELETE_SYSTEM_APP which requests different 13166 // semantics than normal for uninstalling system apps. 13167 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13168 ps.setUserState(user.getIdentifier(), 13169 COMPONENT_ENABLED_STATE_DEFAULT, 13170 false, //installed 13171 true, //stopped 13172 true, //notLaunched 13173 false, //hidden 13174 null, null, null, 13175 false, // blockUninstall 13176 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0); 13177 if (!isSystemApp(ps)) { 13178 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13179 // Other user still have this package installed, so all 13180 // we need to do is clear this user's data and save that 13181 // it is uninstalled. 13182 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13183 removeUser = user.getIdentifier(); 13184 appId = ps.appId; 13185 scheduleWritePackageRestrictionsLocked(removeUser); 13186 } else { 13187 // We need to set it back to 'installed' so the uninstall 13188 // broadcasts will be sent correctly. 13189 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13190 ps.setInstalled(true, user.getIdentifier()); 13191 } 13192 } else { 13193 // This is a system app, so we assume that the 13194 // other users still have this package installed, so all 13195 // we need to do is clear this user's data and save that 13196 // it is uninstalled. 13197 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13198 removeUser = user.getIdentifier(); 13199 appId = ps.appId; 13200 scheduleWritePackageRestrictionsLocked(removeUser); 13201 } 13202 } 13203 } 13204 13205 if (removeUser >= 0) { 13206 // From above, we determined that we are deleting this only 13207 // for a single user. Continue the work here. 13208 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13209 if (outInfo != null) { 13210 outInfo.removedPackage = packageName; 13211 outInfo.removedAppId = appId; 13212 outInfo.removedUsers = new int[] {removeUser}; 13213 } 13214 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13215 removeKeystoreDataIfNeeded(removeUser, appId); 13216 schedulePackageCleaning(packageName, removeUser, false); 13217 synchronized (mPackages) { 13218 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13219 scheduleWritePackageRestrictionsLocked(removeUser); 13220 } 13221 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13222 } 13223 return true; 13224 } 13225 13226 if (dataOnly) { 13227 // Delete application data first 13228 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13229 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13230 return true; 13231 } 13232 13233 boolean ret = false; 13234 if (isSystemApp(ps)) { 13235 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13236 // When an updated system application is deleted we delete the existing resources as well and 13237 // fall back to existing code in system partition 13238 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13239 flags, outInfo, writeSettings); 13240 } else { 13241 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13242 // Kill application pre-emptively especially for apps on sd. 13243 killApplication(packageName, ps.appId, "uninstall pkg"); 13244 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13245 allUserHandles, perUserInstalled, 13246 outInfo, writeSettings); 13247 } 13248 13249 return ret; 13250 } 13251 13252 private final class ClearStorageConnection implements ServiceConnection { 13253 IMediaContainerService mContainerService; 13254 13255 @Override 13256 public void onServiceConnected(ComponentName name, IBinder service) { 13257 synchronized (this) { 13258 mContainerService = IMediaContainerService.Stub.asInterface(service); 13259 notifyAll(); 13260 } 13261 } 13262 13263 @Override 13264 public void onServiceDisconnected(ComponentName name) { 13265 } 13266 } 13267 13268 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13269 final boolean mounted; 13270 if (Environment.isExternalStorageEmulated()) { 13271 mounted = true; 13272 } else { 13273 final String status = Environment.getExternalStorageState(); 13274 13275 mounted = status.equals(Environment.MEDIA_MOUNTED) 13276 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13277 } 13278 13279 if (!mounted) { 13280 return; 13281 } 13282 13283 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13284 int[] users; 13285 if (userId == UserHandle.USER_ALL) { 13286 users = sUserManager.getUserIds(); 13287 } else { 13288 users = new int[] { userId }; 13289 } 13290 final ClearStorageConnection conn = new ClearStorageConnection(); 13291 if (mContext.bindServiceAsUser( 13292 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13293 try { 13294 for (int curUser : users) { 13295 long timeout = SystemClock.uptimeMillis() + 5000; 13296 synchronized (conn) { 13297 long now = SystemClock.uptimeMillis(); 13298 while (conn.mContainerService == null && now < timeout) { 13299 try { 13300 conn.wait(timeout - now); 13301 } catch (InterruptedException e) { 13302 } 13303 } 13304 } 13305 if (conn.mContainerService == null) { 13306 return; 13307 } 13308 13309 final UserEnvironment userEnv = new UserEnvironment(curUser); 13310 clearDirectory(conn.mContainerService, 13311 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13312 if (allData) { 13313 clearDirectory(conn.mContainerService, 13314 userEnv.buildExternalStorageAppDataDirs(packageName)); 13315 clearDirectory(conn.mContainerService, 13316 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13317 } 13318 } 13319 } finally { 13320 mContext.unbindService(conn); 13321 } 13322 } 13323 } 13324 13325 @Override 13326 public void clearApplicationUserData(final String packageName, 13327 final IPackageDataObserver observer, final int userId) { 13328 mContext.enforceCallingOrSelfPermission( 13329 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13330 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13331 // Queue up an async operation since the package deletion may take a little while. 13332 mHandler.post(new Runnable() { 13333 public void run() { 13334 mHandler.removeCallbacks(this); 13335 final boolean succeeded; 13336 synchronized (mInstallLock) { 13337 succeeded = clearApplicationUserDataLI(packageName, userId); 13338 } 13339 clearExternalStorageDataSync(packageName, userId, true); 13340 if (succeeded) { 13341 // invoke DeviceStorageMonitor's update method to clear any notifications 13342 DeviceStorageMonitorInternal 13343 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13344 if (dsm != null) { 13345 dsm.checkMemory(); 13346 } 13347 } 13348 if(observer != null) { 13349 try { 13350 observer.onRemoveCompleted(packageName, succeeded); 13351 } catch (RemoteException e) { 13352 Log.i(TAG, "Observer no longer exists."); 13353 } 13354 } //end if observer 13355 } //end run 13356 }); 13357 } 13358 13359 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13360 if (packageName == null) { 13361 Slog.w(TAG, "Attempt to delete null packageName."); 13362 return false; 13363 } 13364 13365 // Try finding details about the requested package 13366 PackageParser.Package pkg; 13367 synchronized (mPackages) { 13368 pkg = mPackages.get(packageName); 13369 if (pkg == null) { 13370 final PackageSetting ps = mSettings.mPackages.get(packageName); 13371 if (ps != null) { 13372 pkg = ps.pkg; 13373 } 13374 } 13375 13376 if (pkg == null) { 13377 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13378 return false; 13379 } 13380 13381 PackageSetting ps = (PackageSetting) pkg.mExtras; 13382 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13383 } 13384 13385 // Always delete data directories for package, even if we found no other 13386 // record of app. This helps users recover from UID mismatches without 13387 // resorting to a full data wipe. 13388 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13389 if (retCode < 0) { 13390 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13391 return false; 13392 } 13393 13394 final int appId = pkg.applicationInfo.uid; 13395 removeKeystoreDataIfNeeded(userId, appId); 13396 13397 // Create a native library symlink only if we have native libraries 13398 // and if the native libraries are 32 bit libraries. We do not provide 13399 // this symlink for 64 bit libraries. 13400 if (pkg.applicationInfo.primaryCpuAbi != null && 13401 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13402 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13403 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13404 nativeLibPath, userId) < 0) { 13405 Slog.w(TAG, "Failed linking native library dir"); 13406 return false; 13407 } 13408 } 13409 13410 return true; 13411 } 13412 13413 /** 13414 * Reverts user permission state changes (permissions and flags) in 13415 * all packages for a given user. 13416 * 13417 * @param userId The device user for which to do a reset. 13418 */ 13419 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13420 final int packageCount = mPackages.size(); 13421 for (int i = 0; i < packageCount; i++) { 13422 PackageParser.Package pkg = mPackages.valueAt(i); 13423 PackageSetting ps = (PackageSetting) pkg.mExtras; 13424 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13425 } 13426 } 13427 13428 /** 13429 * Reverts user permission state changes (permissions and flags). 13430 * 13431 * @param ps The package for which to reset. 13432 * @param userId The device user for which to do a reset. 13433 */ 13434 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13435 final PackageSetting ps, final int userId) { 13436 if (ps.pkg == null) { 13437 return; 13438 } 13439 13440 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13441 | FLAG_PERMISSION_USER_FIXED 13442 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13443 13444 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13445 | FLAG_PERMISSION_POLICY_FIXED; 13446 13447 boolean writeInstallPermissions = false; 13448 boolean writeRuntimePermissions = false; 13449 13450 final int permissionCount = ps.pkg.requestedPermissions.size(); 13451 for (int i = 0; i < permissionCount; i++) { 13452 String permission = ps.pkg.requestedPermissions.get(i); 13453 13454 BasePermission bp = mSettings.mPermissions.get(permission); 13455 if (bp == null) { 13456 continue; 13457 } 13458 13459 // If shared user we just reset the state to which only this app contributed. 13460 if (ps.sharedUser != null) { 13461 boolean used = false; 13462 final int packageCount = ps.sharedUser.packages.size(); 13463 for (int j = 0; j < packageCount; j++) { 13464 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13465 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13466 && pkg.pkg.requestedPermissions.contains(permission)) { 13467 used = true; 13468 break; 13469 } 13470 } 13471 if (used) { 13472 continue; 13473 } 13474 } 13475 13476 PermissionsState permissionsState = ps.getPermissionsState(); 13477 13478 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13479 13480 // Always clear the user settable flags. 13481 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13482 bp.name) != null; 13483 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13484 if (hasInstallState) { 13485 writeInstallPermissions = true; 13486 } else { 13487 writeRuntimePermissions = true; 13488 } 13489 } 13490 13491 // Below is only runtime permission handling. 13492 if (!bp.isRuntime()) { 13493 continue; 13494 } 13495 13496 // Never clobber system or policy. 13497 if ((oldFlags & policyOrSystemFlags) != 0) { 13498 continue; 13499 } 13500 13501 // If this permission was granted by default, make sure it is. 13502 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13503 if (permissionsState.grantRuntimePermission(bp, userId) 13504 != PERMISSION_OPERATION_FAILURE) { 13505 writeRuntimePermissions = true; 13506 } 13507 } else { 13508 // Otherwise, reset the permission. 13509 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13510 switch (revokeResult) { 13511 case PERMISSION_OPERATION_SUCCESS: { 13512 writeRuntimePermissions = true; 13513 } break; 13514 13515 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13516 writeRuntimePermissions = true; 13517 // If gids changed for this user, kill all affected packages. 13518 mHandler.post(new Runnable() { 13519 @Override 13520 public void run() { 13521 // This has to happen with no lock held. 13522 killSettingPackagesForUser(ps, userId, 13523 KILL_APP_REASON_GIDS_CHANGED); 13524 } 13525 }); 13526 } break; 13527 } 13528 } 13529 } 13530 13531 // Synchronously write as we are taking permissions away. 13532 if (writeRuntimePermissions) { 13533 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13534 } 13535 13536 // Synchronously write as we are taking permissions away. 13537 if (writeInstallPermissions) { 13538 mSettings.writeLPr(); 13539 } 13540 } 13541 13542 /** 13543 * Remove entries from the keystore daemon. Will only remove it if the 13544 * {@code appId} is valid. 13545 */ 13546 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13547 if (appId < 0) { 13548 return; 13549 } 13550 13551 final KeyStore keyStore = KeyStore.getInstance(); 13552 if (keyStore != null) { 13553 if (userId == UserHandle.USER_ALL) { 13554 for (final int individual : sUserManager.getUserIds()) { 13555 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13556 } 13557 } else { 13558 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13559 } 13560 } else { 13561 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13562 } 13563 } 13564 13565 @Override 13566 public void deleteApplicationCacheFiles(final String packageName, 13567 final IPackageDataObserver observer) { 13568 mContext.enforceCallingOrSelfPermission( 13569 android.Manifest.permission.DELETE_CACHE_FILES, null); 13570 // Queue up an async operation since the package deletion may take a little while. 13571 final int userId = UserHandle.getCallingUserId(); 13572 mHandler.post(new Runnable() { 13573 public void run() { 13574 mHandler.removeCallbacks(this); 13575 final boolean succeded; 13576 synchronized (mInstallLock) { 13577 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13578 } 13579 clearExternalStorageDataSync(packageName, userId, false); 13580 if (observer != null) { 13581 try { 13582 observer.onRemoveCompleted(packageName, succeded); 13583 } catch (RemoteException e) { 13584 Log.i(TAG, "Observer no longer exists."); 13585 } 13586 } //end if observer 13587 } //end run 13588 }); 13589 } 13590 13591 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13592 if (packageName == null) { 13593 Slog.w(TAG, "Attempt to delete null packageName."); 13594 return false; 13595 } 13596 PackageParser.Package p; 13597 synchronized (mPackages) { 13598 p = mPackages.get(packageName); 13599 } 13600 if (p == null) { 13601 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13602 return false; 13603 } 13604 final ApplicationInfo applicationInfo = p.applicationInfo; 13605 if (applicationInfo == null) { 13606 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13607 return false; 13608 } 13609 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13610 if (retCode < 0) { 13611 Slog.w(TAG, "Couldn't remove cache files for package: " 13612 + packageName + " u" + userId); 13613 return false; 13614 } 13615 return true; 13616 } 13617 13618 @Override 13619 public void getPackageSizeInfo(final String packageName, int userHandle, 13620 final IPackageStatsObserver observer) { 13621 mContext.enforceCallingOrSelfPermission( 13622 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13623 if (packageName == null) { 13624 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13625 } 13626 13627 PackageStats stats = new PackageStats(packageName, userHandle); 13628 13629 /* 13630 * Queue up an async operation since the package measurement may take a 13631 * little while. 13632 */ 13633 Message msg = mHandler.obtainMessage(INIT_COPY); 13634 msg.obj = new MeasureParams(stats, observer); 13635 mHandler.sendMessage(msg); 13636 } 13637 13638 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13639 PackageStats pStats) { 13640 if (packageName == null) { 13641 Slog.w(TAG, "Attempt to get size of null packageName."); 13642 return false; 13643 } 13644 PackageParser.Package p; 13645 boolean dataOnly = false; 13646 String libDirRoot = null; 13647 String asecPath = null; 13648 PackageSetting ps = null; 13649 synchronized (mPackages) { 13650 p = mPackages.get(packageName); 13651 ps = mSettings.mPackages.get(packageName); 13652 if(p == null) { 13653 dataOnly = true; 13654 if((ps == null) || (ps.pkg == null)) { 13655 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13656 return false; 13657 } 13658 p = ps.pkg; 13659 } 13660 if (ps != null) { 13661 libDirRoot = ps.legacyNativeLibraryPathString; 13662 } 13663 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13664 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13665 if (secureContainerId != null) { 13666 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13667 } 13668 } 13669 } 13670 String publicSrcDir = null; 13671 if(!dataOnly) { 13672 final ApplicationInfo applicationInfo = p.applicationInfo; 13673 if (applicationInfo == null) { 13674 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13675 return false; 13676 } 13677 if (p.isForwardLocked()) { 13678 publicSrcDir = applicationInfo.getBaseResourcePath(); 13679 } 13680 } 13681 // TODO: extend to measure size of split APKs 13682 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13683 // not just the first level. 13684 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13685 // just the primary. 13686 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13687 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13688 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13689 if (res < 0) { 13690 return false; 13691 } 13692 13693 // Fix-up for forward-locked applications in ASEC containers. 13694 if (!isExternal(p)) { 13695 pStats.codeSize += pStats.externalCodeSize; 13696 pStats.externalCodeSize = 0L; 13697 } 13698 13699 return true; 13700 } 13701 13702 13703 @Override 13704 public void addPackageToPreferred(String packageName) { 13705 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13706 } 13707 13708 @Override 13709 public void removePackageFromPreferred(String packageName) { 13710 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13711 } 13712 13713 @Override 13714 public List<PackageInfo> getPreferredPackages(int flags) { 13715 return new ArrayList<PackageInfo>(); 13716 } 13717 13718 private int getUidTargetSdkVersionLockedLPr(int uid) { 13719 Object obj = mSettings.getUserIdLPr(uid); 13720 if (obj instanceof SharedUserSetting) { 13721 final SharedUserSetting sus = (SharedUserSetting) obj; 13722 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13723 final Iterator<PackageSetting> it = sus.packages.iterator(); 13724 while (it.hasNext()) { 13725 final PackageSetting ps = it.next(); 13726 if (ps.pkg != null) { 13727 int v = ps.pkg.applicationInfo.targetSdkVersion; 13728 if (v < vers) vers = v; 13729 } 13730 } 13731 return vers; 13732 } else if (obj instanceof PackageSetting) { 13733 final PackageSetting ps = (PackageSetting) obj; 13734 if (ps.pkg != null) { 13735 return ps.pkg.applicationInfo.targetSdkVersion; 13736 } 13737 } 13738 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13739 } 13740 13741 @Override 13742 public void addPreferredActivity(IntentFilter filter, int match, 13743 ComponentName[] set, ComponentName activity, int userId) { 13744 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13745 "Adding preferred"); 13746 } 13747 13748 private void addPreferredActivityInternal(IntentFilter filter, int match, 13749 ComponentName[] set, ComponentName activity, boolean always, int userId, 13750 String opname) { 13751 // writer 13752 int callingUid = Binder.getCallingUid(); 13753 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13754 if (filter.countActions() == 0) { 13755 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13756 return; 13757 } 13758 synchronized (mPackages) { 13759 if (mContext.checkCallingOrSelfPermission( 13760 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13761 != PackageManager.PERMISSION_GRANTED) { 13762 if (getUidTargetSdkVersionLockedLPr(callingUid) 13763 < Build.VERSION_CODES.FROYO) { 13764 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13765 + callingUid); 13766 return; 13767 } 13768 mContext.enforceCallingOrSelfPermission( 13769 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13770 } 13771 13772 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13773 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13774 + userId + ":"); 13775 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13776 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13777 scheduleWritePackageRestrictionsLocked(userId); 13778 } 13779 } 13780 13781 @Override 13782 public void replacePreferredActivity(IntentFilter filter, int match, 13783 ComponentName[] set, ComponentName activity, int userId) { 13784 if (filter.countActions() != 1) { 13785 throw new IllegalArgumentException( 13786 "replacePreferredActivity expects filter to have only 1 action."); 13787 } 13788 if (filter.countDataAuthorities() != 0 13789 || filter.countDataPaths() != 0 13790 || filter.countDataSchemes() > 1 13791 || filter.countDataTypes() != 0) { 13792 throw new IllegalArgumentException( 13793 "replacePreferredActivity expects filter to have no data authorities, " + 13794 "paths, or types; and at most one scheme."); 13795 } 13796 13797 final int callingUid = Binder.getCallingUid(); 13798 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13799 synchronized (mPackages) { 13800 if (mContext.checkCallingOrSelfPermission( 13801 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13802 != PackageManager.PERMISSION_GRANTED) { 13803 if (getUidTargetSdkVersionLockedLPr(callingUid) 13804 < Build.VERSION_CODES.FROYO) { 13805 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13806 + Binder.getCallingUid()); 13807 return; 13808 } 13809 mContext.enforceCallingOrSelfPermission( 13810 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13811 } 13812 13813 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13814 if (pir != null) { 13815 // Get all of the existing entries that exactly match this filter. 13816 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13817 if (existing != null && existing.size() == 1) { 13818 PreferredActivity cur = existing.get(0); 13819 if (DEBUG_PREFERRED) { 13820 Slog.i(TAG, "Checking replace of preferred:"); 13821 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13822 if (!cur.mPref.mAlways) { 13823 Slog.i(TAG, " -- CUR; not mAlways!"); 13824 } else { 13825 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13826 Slog.i(TAG, " -- CUR: mSet=" 13827 + Arrays.toString(cur.mPref.mSetComponents)); 13828 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13829 Slog.i(TAG, " -- NEW: mMatch=" 13830 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13831 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13832 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13833 } 13834 } 13835 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13836 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13837 && cur.mPref.sameSet(set)) { 13838 // Setting the preferred activity to what it happens to be already 13839 if (DEBUG_PREFERRED) { 13840 Slog.i(TAG, "Replacing with same preferred activity " 13841 + cur.mPref.mShortComponent + " for user " 13842 + userId + ":"); 13843 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13844 } 13845 return; 13846 } 13847 } 13848 13849 if (existing != null) { 13850 if (DEBUG_PREFERRED) { 13851 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13852 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13853 } 13854 for (int i = 0; i < existing.size(); i++) { 13855 PreferredActivity pa = existing.get(i); 13856 if (DEBUG_PREFERRED) { 13857 Slog.i(TAG, "Removing existing preferred activity " 13858 + pa.mPref.mComponent + ":"); 13859 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13860 } 13861 pir.removeFilter(pa); 13862 } 13863 } 13864 } 13865 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13866 "Replacing preferred"); 13867 } 13868 } 13869 13870 @Override 13871 public void clearPackagePreferredActivities(String packageName) { 13872 final int uid = Binder.getCallingUid(); 13873 // writer 13874 synchronized (mPackages) { 13875 PackageParser.Package pkg = mPackages.get(packageName); 13876 if (pkg == null || pkg.applicationInfo.uid != uid) { 13877 if (mContext.checkCallingOrSelfPermission( 13878 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13879 != PackageManager.PERMISSION_GRANTED) { 13880 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13881 < Build.VERSION_CODES.FROYO) { 13882 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13883 + Binder.getCallingUid()); 13884 return; 13885 } 13886 mContext.enforceCallingOrSelfPermission( 13887 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13888 } 13889 } 13890 13891 int user = UserHandle.getCallingUserId(); 13892 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13893 scheduleWritePackageRestrictionsLocked(user); 13894 } 13895 } 13896 } 13897 13898 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13899 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13900 ArrayList<PreferredActivity> removed = null; 13901 boolean changed = false; 13902 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13903 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13904 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13905 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13906 continue; 13907 } 13908 Iterator<PreferredActivity> it = pir.filterIterator(); 13909 while (it.hasNext()) { 13910 PreferredActivity pa = it.next(); 13911 // Mark entry for removal only if it matches the package name 13912 // and the entry is of type "always". 13913 if (packageName == null || 13914 (pa.mPref.mComponent.getPackageName().equals(packageName) 13915 && pa.mPref.mAlways)) { 13916 if (removed == null) { 13917 removed = new ArrayList<PreferredActivity>(); 13918 } 13919 removed.add(pa); 13920 } 13921 } 13922 if (removed != null) { 13923 for (int j=0; j<removed.size(); j++) { 13924 PreferredActivity pa = removed.get(j); 13925 pir.removeFilter(pa); 13926 } 13927 changed = true; 13928 } 13929 } 13930 return changed; 13931 } 13932 13933 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13934 private void clearIntentFilterVerificationsLPw(int userId) { 13935 final int packageCount = mPackages.size(); 13936 for (int i = 0; i < packageCount; i++) { 13937 PackageParser.Package pkg = mPackages.valueAt(i); 13938 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 13939 } 13940 } 13941 13942 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13943 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13944 if (userId == UserHandle.USER_ALL) { 13945 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13946 sUserManager.getUserIds())) { 13947 for (int oneUserId : sUserManager.getUserIds()) { 13948 scheduleWritePackageRestrictionsLocked(oneUserId); 13949 } 13950 } 13951 } else { 13952 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13953 scheduleWritePackageRestrictionsLocked(userId); 13954 } 13955 } 13956 } 13957 13958 void clearDefaultBrowserIfNeeded(String packageName) { 13959 for (int oneUserId : sUserManager.getUserIds()) { 13960 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13961 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13962 if (packageName.equals(defaultBrowserPackageName)) { 13963 setDefaultBrowserPackageName(null, oneUserId); 13964 } 13965 } 13966 } 13967 13968 @Override 13969 public void resetApplicationPreferences(int userId) { 13970 mContext.enforceCallingOrSelfPermission( 13971 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13972 // writer 13973 synchronized (mPackages) { 13974 final long identity = Binder.clearCallingIdentity(); 13975 try { 13976 clearPackagePreferredActivitiesLPw(null, userId); 13977 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13978 // TODO: We have to reset the default SMS and Phone. This requires 13979 // significant refactoring to keep all default apps in the package 13980 // manager (cleaner but more work) or have the services provide 13981 // callbacks to the package manager to request a default app reset. 13982 applyFactoryDefaultBrowserLPw(userId); 13983 clearIntentFilterVerificationsLPw(userId); 13984 primeDomainVerificationsLPw(userId); 13985 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 13986 scheduleWritePackageRestrictionsLocked(userId); 13987 } finally { 13988 Binder.restoreCallingIdentity(identity); 13989 } 13990 } 13991 } 13992 13993 @Override 13994 public int getPreferredActivities(List<IntentFilter> outFilters, 13995 List<ComponentName> outActivities, String packageName) { 13996 13997 int num = 0; 13998 final int userId = UserHandle.getCallingUserId(); 13999 // reader 14000 synchronized (mPackages) { 14001 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14002 if (pir != null) { 14003 final Iterator<PreferredActivity> it = pir.filterIterator(); 14004 while (it.hasNext()) { 14005 final PreferredActivity pa = it.next(); 14006 if (packageName == null 14007 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14008 && pa.mPref.mAlways)) { 14009 if (outFilters != null) { 14010 outFilters.add(new IntentFilter(pa)); 14011 } 14012 if (outActivities != null) { 14013 outActivities.add(pa.mPref.mComponent); 14014 } 14015 } 14016 } 14017 } 14018 } 14019 14020 return num; 14021 } 14022 14023 @Override 14024 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14025 int userId) { 14026 int callingUid = Binder.getCallingUid(); 14027 if (callingUid != Process.SYSTEM_UID) { 14028 throw new SecurityException( 14029 "addPersistentPreferredActivity can only be run by the system"); 14030 } 14031 if (filter.countActions() == 0) { 14032 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14033 return; 14034 } 14035 synchronized (mPackages) { 14036 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14037 " :"); 14038 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14039 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14040 new PersistentPreferredActivity(filter, activity)); 14041 scheduleWritePackageRestrictionsLocked(userId); 14042 } 14043 } 14044 14045 @Override 14046 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14047 int callingUid = Binder.getCallingUid(); 14048 if (callingUid != Process.SYSTEM_UID) { 14049 throw new SecurityException( 14050 "clearPackagePersistentPreferredActivities can only be run by the system"); 14051 } 14052 ArrayList<PersistentPreferredActivity> removed = null; 14053 boolean changed = false; 14054 synchronized (mPackages) { 14055 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14056 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14057 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14058 .valueAt(i); 14059 if (userId != thisUserId) { 14060 continue; 14061 } 14062 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14063 while (it.hasNext()) { 14064 PersistentPreferredActivity ppa = it.next(); 14065 // Mark entry for removal only if it matches the package name. 14066 if (ppa.mComponent.getPackageName().equals(packageName)) { 14067 if (removed == null) { 14068 removed = new ArrayList<PersistentPreferredActivity>(); 14069 } 14070 removed.add(ppa); 14071 } 14072 } 14073 if (removed != null) { 14074 for (int j=0; j<removed.size(); j++) { 14075 PersistentPreferredActivity ppa = removed.get(j); 14076 ppir.removeFilter(ppa); 14077 } 14078 changed = true; 14079 } 14080 } 14081 14082 if (changed) { 14083 scheduleWritePackageRestrictionsLocked(userId); 14084 } 14085 } 14086 } 14087 14088 /** 14089 * Common machinery for picking apart a restored XML blob and passing 14090 * it to a caller-supplied functor to be applied to the running system. 14091 */ 14092 private void restoreFromXml(XmlPullParser parser, int userId, 14093 String expectedStartTag, BlobXmlRestorer functor) 14094 throws IOException, XmlPullParserException { 14095 int type; 14096 while ((type = parser.next()) != XmlPullParser.START_TAG 14097 && type != XmlPullParser.END_DOCUMENT) { 14098 } 14099 if (type != XmlPullParser.START_TAG) { 14100 // oops didn't find a start tag?! 14101 if (DEBUG_BACKUP) { 14102 Slog.e(TAG, "Didn't find start tag during restore"); 14103 } 14104 return; 14105 } 14106 14107 // this is supposed to be TAG_PREFERRED_BACKUP 14108 if (!expectedStartTag.equals(parser.getName())) { 14109 if (DEBUG_BACKUP) { 14110 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14111 } 14112 return; 14113 } 14114 14115 // skip interfering stuff, then we're aligned with the backing implementation 14116 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14117 functor.apply(parser, userId); 14118 } 14119 14120 private interface BlobXmlRestorer { 14121 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14122 } 14123 14124 /** 14125 * Non-Binder method, support for the backup/restore mechanism: write the 14126 * full set of preferred activities in its canonical XML format. Returns the 14127 * XML output as a byte array, or null if there is none. 14128 */ 14129 @Override 14130 public byte[] getPreferredActivityBackup(int userId) { 14131 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14132 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14133 } 14134 14135 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14136 try { 14137 final XmlSerializer serializer = new FastXmlSerializer(); 14138 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14139 serializer.startDocument(null, true); 14140 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14141 14142 synchronized (mPackages) { 14143 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14144 } 14145 14146 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14147 serializer.endDocument(); 14148 serializer.flush(); 14149 } catch (Exception e) { 14150 if (DEBUG_BACKUP) { 14151 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14152 } 14153 return null; 14154 } 14155 14156 return dataStream.toByteArray(); 14157 } 14158 14159 @Override 14160 public void restorePreferredActivities(byte[] backup, int userId) { 14161 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14162 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14163 } 14164 14165 try { 14166 final XmlPullParser parser = Xml.newPullParser(); 14167 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14168 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14169 new BlobXmlRestorer() { 14170 @Override 14171 public void apply(XmlPullParser parser, int userId) 14172 throws XmlPullParserException, IOException { 14173 synchronized (mPackages) { 14174 mSettings.readPreferredActivitiesLPw(parser, userId); 14175 } 14176 } 14177 } ); 14178 } catch (Exception e) { 14179 if (DEBUG_BACKUP) { 14180 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14181 } 14182 } 14183 } 14184 14185 /** 14186 * Non-Binder method, support for the backup/restore mechanism: write the 14187 * default browser (etc) settings in its canonical XML format. Returns the default 14188 * browser XML representation as a byte array, or null if there is none. 14189 */ 14190 @Override 14191 public byte[] getDefaultAppsBackup(int userId) { 14192 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14193 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14194 } 14195 14196 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14197 try { 14198 final XmlSerializer serializer = new FastXmlSerializer(); 14199 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14200 serializer.startDocument(null, true); 14201 serializer.startTag(null, TAG_DEFAULT_APPS); 14202 14203 synchronized (mPackages) { 14204 mSettings.writeDefaultAppsLPr(serializer, userId); 14205 } 14206 14207 serializer.endTag(null, TAG_DEFAULT_APPS); 14208 serializer.endDocument(); 14209 serializer.flush(); 14210 } catch (Exception e) { 14211 if (DEBUG_BACKUP) { 14212 Slog.e(TAG, "Unable to write default apps for backup", e); 14213 } 14214 return null; 14215 } 14216 14217 return dataStream.toByteArray(); 14218 } 14219 14220 @Override 14221 public void restoreDefaultApps(byte[] backup, int userId) { 14222 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14223 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14224 } 14225 14226 try { 14227 final XmlPullParser parser = Xml.newPullParser(); 14228 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14229 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14230 new BlobXmlRestorer() { 14231 @Override 14232 public void apply(XmlPullParser parser, int userId) 14233 throws XmlPullParserException, IOException { 14234 synchronized (mPackages) { 14235 mSettings.readDefaultAppsLPw(parser, userId); 14236 } 14237 } 14238 } ); 14239 } catch (Exception e) { 14240 if (DEBUG_BACKUP) { 14241 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14242 } 14243 } 14244 } 14245 14246 @Override 14247 public byte[] getIntentFilterVerificationBackup(int userId) { 14248 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14249 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14250 } 14251 14252 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14253 try { 14254 final XmlSerializer serializer = new FastXmlSerializer(); 14255 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14256 serializer.startDocument(null, true); 14257 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14258 14259 synchronized (mPackages) { 14260 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14261 } 14262 14263 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14264 serializer.endDocument(); 14265 serializer.flush(); 14266 } catch (Exception e) { 14267 if (DEBUG_BACKUP) { 14268 Slog.e(TAG, "Unable to write default apps for backup", e); 14269 } 14270 return null; 14271 } 14272 14273 return dataStream.toByteArray(); 14274 } 14275 14276 @Override 14277 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14278 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14279 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14280 } 14281 14282 try { 14283 final XmlPullParser parser = Xml.newPullParser(); 14284 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14285 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14286 new BlobXmlRestorer() { 14287 @Override 14288 public void apply(XmlPullParser parser, int userId) 14289 throws XmlPullParserException, IOException { 14290 synchronized (mPackages) { 14291 mSettings.readAllDomainVerificationsLPr(parser, userId); 14292 mSettings.writeLPr(); 14293 } 14294 } 14295 } ); 14296 } catch (Exception e) { 14297 if (DEBUG_BACKUP) { 14298 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14299 } 14300 } 14301 } 14302 14303 @Override 14304 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14305 int sourceUserId, int targetUserId, int flags) { 14306 mContext.enforceCallingOrSelfPermission( 14307 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14308 int callingUid = Binder.getCallingUid(); 14309 enforceOwnerRights(ownerPackage, callingUid); 14310 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14311 if (intentFilter.countActions() == 0) { 14312 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14313 return; 14314 } 14315 synchronized (mPackages) { 14316 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14317 ownerPackage, targetUserId, flags); 14318 CrossProfileIntentResolver resolver = 14319 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14320 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14321 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14322 if (existing != null) { 14323 int size = existing.size(); 14324 for (int i = 0; i < size; i++) { 14325 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14326 return; 14327 } 14328 } 14329 } 14330 resolver.addFilter(newFilter); 14331 scheduleWritePackageRestrictionsLocked(sourceUserId); 14332 } 14333 } 14334 14335 @Override 14336 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14337 mContext.enforceCallingOrSelfPermission( 14338 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14339 int callingUid = Binder.getCallingUid(); 14340 enforceOwnerRights(ownerPackage, callingUid); 14341 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14342 synchronized (mPackages) { 14343 CrossProfileIntentResolver resolver = 14344 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14345 ArraySet<CrossProfileIntentFilter> set = 14346 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14347 for (CrossProfileIntentFilter filter : set) { 14348 if (filter.getOwnerPackage().equals(ownerPackage)) { 14349 resolver.removeFilter(filter); 14350 } 14351 } 14352 scheduleWritePackageRestrictionsLocked(sourceUserId); 14353 } 14354 } 14355 14356 // Enforcing that callingUid is owning pkg on userId 14357 private void enforceOwnerRights(String pkg, int callingUid) { 14358 // The system owns everything. 14359 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14360 return; 14361 } 14362 int callingUserId = UserHandle.getUserId(callingUid); 14363 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14364 if (pi == null) { 14365 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14366 + callingUserId); 14367 } 14368 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14369 throw new SecurityException("Calling uid " + callingUid 14370 + " does not own package " + pkg); 14371 } 14372 } 14373 14374 @Override 14375 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14376 Intent intent = new Intent(Intent.ACTION_MAIN); 14377 intent.addCategory(Intent.CATEGORY_HOME); 14378 14379 final int callingUserId = UserHandle.getCallingUserId(); 14380 List<ResolveInfo> list = queryIntentActivities(intent, null, 14381 PackageManager.GET_META_DATA, callingUserId); 14382 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14383 true, false, false, callingUserId); 14384 14385 allHomeCandidates.clear(); 14386 if (list != null) { 14387 for (ResolveInfo ri : list) { 14388 allHomeCandidates.add(ri); 14389 } 14390 } 14391 return (preferred == null || preferred.activityInfo == null) 14392 ? null 14393 : new ComponentName(preferred.activityInfo.packageName, 14394 preferred.activityInfo.name); 14395 } 14396 14397 @Override 14398 public void setApplicationEnabledSetting(String appPackageName, 14399 int newState, int flags, int userId, String callingPackage) { 14400 if (!sUserManager.exists(userId)) return; 14401 if (callingPackage == null) { 14402 callingPackage = Integer.toString(Binder.getCallingUid()); 14403 } 14404 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14405 } 14406 14407 @Override 14408 public void setComponentEnabledSetting(ComponentName componentName, 14409 int newState, int flags, int userId) { 14410 if (!sUserManager.exists(userId)) return; 14411 setEnabledSetting(componentName.getPackageName(), 14412 componentName.getClassName(), newState, flags, userId, null); 14413 } 14414 14415 private void setEnabledSetting(final String packageName, String className, int newState, 14416 final int flags, int userId, String callingPackage) { 14417 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14418 || newState == COMPONENT_ENABLED_STATE_ENABLED 14419 || newState == COMPONENT_ENABLED_STATE_DISABLED 14420 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14421 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14422 throw new IllegalArgumentException("Invalid new component state: " 14423 + newState); 14424 } 14425 PackageSetting pkgSetting; 14426 final int uid = Binder.getCallingUid(); 14427 final int permission = mContext.checkCallingOrSelfPermission( 14428 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14429 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14430 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14431 boolean sendNow = false; 14432 boolean isApp = (className == null); 14433 String componentName = isApp ? packageName : className; 14434 int packageUid = -1; 14435 ArrayList<String> components; 14436 14437 // writer 14438 synchronized (mPackages) { 14439 pkgSetting = mSettings.mPackages.get(packageName); 14440 if (pkgSetting == null) { 14441 if (className == null) { 14442 throw new IllegalArgumentException( 14443 "Unknown package: " + packageName); 14444 } 14445 throw new IllegalArgumentException( 14446 "Unknown component: " + packageName 14447 + "/" + className); 14448 } 14449 // Allow root and verify that userId is not being specified by a different user 14450 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14451 throw new SecurityException( 14452 "Permission Denial: attempt to change component state from pid=" 14453 + Binder.getCallingPid() 14454 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14455 } 14456 if (className == null) { 14457 // We're dealing with an application/package level state change 14458 if (pkgSetting.getEnabled(userId) == newState) { 14459 // Nothing to do 14460 return; 14461 } 14462 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14463 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14464 // Don't care about who enables an app. 14465 callingPackage = null; 14466 } 14467 pkgSetting.setEnabled(newState, userId, callingPackage); 14468 // pkgSetting.pkg.mSetEnabled = newState; 14469 } else { 14470 // We're dealing with a component level state change 14471 // First, verify that this is a valid class name. 14472 PackageParser.Package pkg = pkgSetting.pkg; 14473 if (pkg == null || !pkg.hasComponentClassName(className)) { 14474 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14475 throw new IllegalArgumentException("Component class " + className 14476 + " does not exist in " + packageName); 14477 } else { 14478 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14479 + className + " does not exist in " + packageName); 14480 } 14481 } 14482 switch (newState) { 14483 case COMPONENT_ENABLED_STATE_ENABLED: 14484 if (!pkgSetting.enableComponentLPw(className, userId)) { 14485 return; 14486 } 14487 break; 14488 case COMPONENT_ENABLED_STATE_DISABLED: 14489 if (!pkgSetting.disableComponentLPw(className, userId)) { 14490 return; 14491 } 14492 break; 14493 case COMPONENT_ENABLED_STATE_DEFAULT: 14494 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14495 return; 14496 } 14497 break; 14498 default: 14499 Slog.e(TAG, "Invalid new component state: " + newState); 14500 return; 14501 } 14502 } 14503 scheduleWritePackageRestrictionsLocked(userId); 14504 components = mPendingBroadcasts.get(userId, packageName); 14505 final boolean newPackage = components == null; 14506 if (newPackage) { 14507 components = new ArrayList<String>(); 14508 } 14509 if (!components.contains(componentName)) { 14510 components.add(componentName); 14511 } 14512 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14513 sendNow = true; 14514 // Purge entry from pending broadcast list if another one exists already 14515 // since we are sending one right away. 14516 mPendingBroadcasts.remove(userId, packageName); 14517 } else { 14518 if (newPackage) { 14519 mPendingBroadcasts.put(userId, packageName, components); 14520 } 14521 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14522 // Schedule a message 14523 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14524 } 14525 } 14526 } 14527 14528 long callingId = Binder.clearCallingIdentity(); 14529 try { 14530 if (sendNow) { 14531 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14532 sendPackageChangedBroadcast(packageName, 14533 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14534 } 14535 } finally { 14536 Binder.restoreCallingIdentity(callingId); 14537 } 14538 } 14539 14540 private void sendPackageChangedBroadcast(String packageName, 14541 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14542 if (DEBUG_INSTALL) 14543 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14544 + componentNames); 14545 Bundle extras = new Bundle(4); 14546 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14547 String nameList[] = new String[componentNames.size()]; 14548 componentNames.toArray(nameList); 14549 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14550 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14551 extras.putInt(Intent.EXTRA_UID, packageUid); 14552 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14553 new int[] {UserHandle.getUserId(packageUid)}); 14554 } 14555 14556 @Override 14557 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14558 if (!sUserManager.exists(userId)) return; 14559 final int uid = Binder.getCallingUid(); 14560 final int permission = mContext.checkCallingOrSelfPermission( 14561 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14562 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14563 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14564 // writer 14565 synchronized (mPackages) { 14566 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14567 allowedByPermission, uid, userId)) { 14568 scheduleWritePackageRestrictionsLocked(userId); 14569 } 14570 } 14571 } 14572 14573 @Override 14574 public String getInstallerPackageName(String packageName) { 14575 // reader 14576 synchronized (mPackages) { 14577 return mSettings.getInstallerPackageNameLPr(packageName); 14578 } 14579 } 14580 14581 @Override 14582 public int getApplicationEnabledSetting(String packageName, int userId) { 14583 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14584 int uid = Binder.getCallingUid(); 14585 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14586 // reader 14587 synchronized (mPackages) { 14588 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14589 } 14590 } 14591 14592 @Override 14593 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14594 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14595 int uid = Binder.getCallingUid(); 14596 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14597 // reader 14598 synchronized (mPackages) { 14599 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14600 } 14601 } 14602 14603 @Override 14604 public void enterSafeMode() { 14605 enforceSystemOrRoot("Only the system can request entering safe mode"); 14606 14607 if (!mSystemReady) { 14608 mSafeMode = true; 14609 } 14610 } 14611 14612 @Override 14613 public void systemReady() { 14614 mSystemReady = true; 14615 14616 // Read the compatibilty setting when the system is ready. 14617 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14618 mContext.getContentResolver(), 14619 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14620 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14621 if (DEBUG_SETTINGS) { 14622 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14623 } 14624 14625 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14626 14627 synchronized (mPackages) { 14628 // Verify that all of the preferred activity components actually 14629 // exist. It is possible for applications to be updated and at 14630 // that point remove a previously declared activity component that 14631 // had been set as a preferred activity. We try to clean this up 14632 // the next time we encounter that preferred activity, but it is 14633 // possible for the user flow to never be able to return to that 14634 // situation so here we do a sanity check to make sure we haven't 14635 // left any junk around. 14636 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14637 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14638 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14639 removed.clear(); 14640 for (PreferredActivity pa : pir.filterSet()) { 14641 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14642 removed.add(pa); 14643 } 14644 } 14645 if (removed.size() > 0) { 14646 for (int r=0; r<removed.size(); r++) { 14647 PreferredActivity pa = removed.get(r); 14648 Slog.w(TAG, "Removing dangling preferred activity: " 14649 + pa.mPref.mComponent); 14650 pir.removeFilter(pa); 14651 } 14652 mSettings.writePackageRestrictionsLPr( 14653 mSettings.mPreferredActivities.keyAt(i)); 14654 } 14655 } 14656 14657 for (int userId : UserManagerService.getInstance().getUserIds()) { 14658 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14659 grantPermissionsUserIds = ArrayUtils.appendInt( 14660 grantPermissionsUserIds, userId); 14661 } 14662 } 14663 } 14664 sUserManager.systemReady(); 14665 14666 // If we upgraded grant all default permissions before kicking off. 14667 for (int userId : grantPermissionsUserIds) { 14668 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14669 } 14670 14671 // Kick off any messages waiting for system ready 14672 if (mPostSystemReadyMessages != null) { 14673 for (Message msg : mPostSystemReadyMessages) { 14674 msg.sendToTarget(); 14675 } 14676 mPostSystemReadyMessages = null; 14677 } 14678 14679 // Watch for external volumes that come and go over time 14680 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14681 storage.registerListener(mStorageListener); 14682 14683 mInstallerService.systemReady(); 14684 mPackageDexOptimizer.systemReady(); 14685 14686 MountServiceInternal mountServiceInternal = LocalServices.getService( 14687 MountServiceInternal.class); 14688 mountServiceInternal.addExternalStoragePolicy( 14689 new MountServiceInternal.ExternalStorageMountPolicy() { 14690 @Override 14691 public int getMountMode(int uid, String packageName) { 14692 if (Process.isIsolated(uid)) { 14693 return Zygote.MOUNT_EXTERNAL_NONE; 14694 } 14695 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14696 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14697 } 14698 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14699 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14700 } 14701 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14702 return Zygote.MOUNT_EXTERNAL_READ; 14703 } 14704 return Zygote.MOUNT_EXTERNAL_WRITE; 14705 } 14706 14707 @Override 14708 public boolean hasExternalStorage(int uid, String packageName) { 14709 return true; 14710 } 14711 }); 14712 } 14713 14714 @Override 14715 public boolean isSafeMode() { 14716 return mSafeMode; 14717 } 14718 14719 @Override 14720 public boolean hasSystemUidErrors() { 14721 return mHasSystemUidErrors; 14722 } 14723 14724 static String arrayToString(int[] array) { 14725 StringBuffer buf = new StringBuffer(128); 14726 buf.append('['); 14727 if (array != null) { 14728 for (int i=0; i<array.length; i++) { 14729 if (i > 0) buf.append(", "); 14730 buf.append(array[i]); 14731 } 14732 } 14733 buf.append(']'); 14734 return buf.toString(); 14735 } 14736 14737 static class DumpState { 14738 public static final int DUMP_LIBS = 1 << 0; 14739 public static final int DUMP_FEATURES = 1 << 1; 14740 public static final int DUMP_RESOLVERS = 1 << 2; 14741 public static final int DUMP_PERMISSIONS = 1 << 3; 14742 public static final int DUMP_PACKAGES = 1 << 4; 14743 public static final int DUMP_SHARED_USERS = 1 << 5; 14744 public static final int DUMP_MESSAGES = 1 << 6; 14745 public static final int DUMP_PROVIDERS = 1 << 7; 14746 public static final int DUMP_VERIFIERS = 1 << 8; 14747 public static final int DUMP_PREFERRED = 1 << 9; 14748 public static final int DUMP_PREFERRED_XML = 1 << 10; 14749 public static final int DUMP_KEYSETS = 1 << 11; 14750 public static final int DUMP_VERSION = 1 << 12; 14751 public static final int DUMP_INSTALLS = 1 << 13; 14752 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14753 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14754 14755 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14756 14757 private int mTypes; 14758 14759 private int mOptions; 14760 14761 private boolean mTitlePrinted; 14762 14763 private SharedUserSetting mSharedUser; 14764 14765 public boolean isDumping(int type) { 14766 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14767 return true; 14768 } 14769 14770 return (mTypes & type) != 0; 14771 } 14772 14773 public void setDump(int type) { 14774 mTypes |= type; 14775 } 14776 14777 public boolean isOptionEnabled(int option) { 14778 return (mOptions & option) != 0; 14779 } 14780 14781 public void setOptionEnabled(int option) { 14782 mOptions |= option; 14783 } 14784 14785 public boolean onTitlePrinted() { 14786 final boolean printed = mTitlePrinted; 14787 mTitlePrinted = true; 14788 return printed; 14789 } 14790 14791 public boolean getTitlePrinted() { 14792 return mTitlePrinted; 14793 } 14794 14795 public void setTitlePrinted(boolean enabled) { 14796 mTitlePrinted = enabled; 14797 } 14798 14799 public SharedUserSetting getSharedUser() { 14800 return mSharedUser; 14801 } 14802 14803 public void setSharedUser(SharedUserSetting user) { 14804 mSharedUser = user; 14805 } 14806 } 14807 14808 @Override 14809 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14810 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14811 != PackageManager.PERMISSION_GRANTED) { 14812 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14813 + Binder.getCallingPid() 14814 + ", uid=" + Binder.getCallingUid() 14815 + " without permission " 14816 + android.Manifest.permission.DUMP); 14817 return; 14818 } 14819 14820 DumpState dumpState = new DumpState(); 14821 boolean fullPreferred = false; 14822 boolean checkin = false; 14823 14824 String packageName = null; 14825 ArraySet<String> permissionNames = null; 14826 14827 int opti = 0; 14828 while (opti < args.length) { 14829 String opt = args[opti]; 14830 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14831 break; 14832 } 14833 opti++; 14834 14835 if ("-a".equals(opt)) { 14836 // Right now we only know how to print all. 14837 } else if ("-h".equals(opt)) { 14838 pw.println("Package manager dump options:"); 14839 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14840 pw.println(" --checkin: dump for a checkin"); 14841 pw.println(" -f: print details of intent filters"); 14842 pw.println(" -h: print this help"); 14843 pw.println(" cmd may be one of:"); 14844 pw.println(" l[ibraries]: list known shared libraries"); 14845 pw.println(" f[ibraries]: list device features"); 14846 pw.println(" k[eysets]: print known keysets"); 14847 pw.println(" r[esolvers]: dump intent resolvers"); 14848 pw.println(" perm[issions]: dump permissions"); 14849 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14850 pw.println(" pref[erred]: print preferred package settings"); 14851 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14852 pw.println(" prov[iders]: dump content providers"); 14853 pw.println(" p[ackages]: dump installed packages"); 14854 pw.println(" s[hared-users]: dump shared user IDs"); 14855 pw.println(" m[essages]: print collected runtime messages"); 14856 pw.println(" v[erifiers]: print package verifier info"); 14857 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14858 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14859 pw.println(" version: print database version info"); 14860 pw.println(" write: write current settings now"); 14861 pw.println(" installs: details about install sessions"); 14862 pw.println(" <package.name>: info about given package"); 14863 return; 14864 } else if ("--checkin".equals(opt)) { 14865 checkin = true; 14866 } else if ("-f".equals(opt)) { 14867 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14868 } else { 14869 pw.println("Unknown argument: " + opt + "; use -h for help"); 14870 } 14871 } 14872 14873 // Is the caller requesting to dump a particular piece of data? 14874 if (opti < args.length) { 14875 String cmd = args[opti]; 14876 opti++; 14877 // Is this a package name? 14878 if ("android".equals(cmd) || cmd.contains(".")) { 14879 packageName = cmd; 14880 // When dumping a single package, we always dump all of its 14881 // filter information since the amount of data will be reasonable. 14882 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14883 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14884 dumpState.setDump(DumpState.DUMP_LIBS); 14885 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14886 dumpState.setDump(DumpState.DUMP_FEATURES); 14887 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14888 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14889 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14890 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14891 } else if ("permission".equals(cmd)) { 14892 if (opti >= args.length) { 14893 pw.println("Error: permission requires permission name"); 14894 return; 14895 } 14896 permissionNames = new ArraySet<>(); 14897 while (opti < args.length) { 14898 permissionNames.add(args[opti]); 14899 opti++; 14900 } 14901 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14902 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14903 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14904 dumpState.setDump(DumpState.DUMP_PREFERRED); 14905 } else if ("preferred-xml".equals(cmd)) { 14906 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14907 if (opti < args.length && "--full".equals(args[opti])) { 14908 fullPreferred = true; 14909 opti++; 14910 } 14911 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14912 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14913 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14914 dumpState.setDump(DumpState.DUMP_PACKAGES); 14915 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14916 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14917 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14918 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14919 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14920 dumpState.setDump(DumpState.DUMP_MESSAGES); 14921 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14922 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14923 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14924 || "intent-filter-verifiers".equals(cmd)) { 14925 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14926 } else if ("version".equals(cmd)) { 14927 dumpState.setDump(DumpState.DUMP_VERSION); 14928 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14929 dumpState.setDump(DumpState.DUMP_KEYSETS); 14930 } else if ("installs".equals(cmd)) { 14931 dumpState.setDump(DumpState.DUMP_INSTALLS); 14932 } else if ("write".equals(cmd)) { 14933 synchronized (mPackages) { 14934 mSettings.writeLPr(); 14935 pw.println("Settings written."); 14936 return; 14937 } 14938 } 14939 } 14940 14941 if (checkin) { 14942 pw.println("vers,1"); 14943 } 14944 14945 // reader 14946 synchronized (mPackages) { 14947 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14948 if (!checkin) { 14949 if (dumpState.onTitlePrinted()) 14950 pw.println(); 14951 pw.println("Database versions:"); 14952 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 14953 } 14954 } 14955 14956 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14957 if (!checkin) { 14958 if (dumpState.onTitlePrinted()) 14959 pw.println(); 14960 pw.println("Verifiers:"); 14961 pw.print(" Required: "); 14962 pw.print(mRequiredVerifierPackage); 14963 pw.print(" (uid="); 14964 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14965 pw.println(")"); 14966 } else if (mRequiredVerifierPackage != null) { 14967 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14968 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14969 } 14970 } 14971 14972 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14973 packageName == null) { 14974 if (mIntentFilterVerifierComponent != null) { 14975 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14976 if (!checkin) { 14977 if (dumpState.onTitlePrinted()) 14978 pw.println(); 14979 pw.println("Intent Filter Verifier:"); 14980 pw.print(" Using: "); 14981 pw.print(verifierPackageName); 14982 pw.print(" (uid="); 14983 pw.print(getPackageUid(verifierPackageName, 0)); 14984 pw.println(")"); 14985 } else if (verifierPackageName != null) { 14986 pw.print("ifv,"); pw.print(verifierPackageName); 14987 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14988 } 14989 } else { 14990 pw.println(); 14991 pw.println("No Intent Filter Verifier available!"); 14992 } 14993 } 14994 14995 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14996 boolean printedHeader = false; 14997 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14998 while (it.hasNext()) { 14999 String name = it.next(); 15000 SharedLibraryEntry ent = mSharedLibraries.get(name); 15001 if (!checkin) { 15002 if (!printedHeader) { 15003 if (dumpState.onTitlePrinted()) 15004 pw.println(); 15005 pw.println("Libraries:"); 15006 printedHeader = true; 15007 } 15008 pw.print(" "); 15009 } else { 15010 pw.print("lib,"); 15011 } 15012 pw.print(name); 15013 if (!checkin) { 15014 pw.print(" -> "); 15015 } 15016 if (ent.path != null) { 15017 if (!checkin) { 15018 pw.print("(jar) "); 15019 pw.print(ent.path); 15020 } else { 15021 pw.print(",jar,"); 15022 pw.print(ent.path); 15023 } 15024 } else { 15025 if (!checkin) { 15026 pw.print("(apk) "); 15027 pw.print(ent.apk); 15028 } else { 15029 pw.print(",apk,"); 15030 pw.print(ent.apk); 15031 } 15032 } 15033 pw.println(); 15034 } 15035 } 15036 15037 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15038 if (dumpState.onTitlePrinted()) 15039 pw.println(); 15040 if (!checkin) { 15041 pw.println("Features:"); 15042 } 15043 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15044 while (it.hasNext()) { 15045 String name = it.next(); 15046 if (!checkin) { 15047 pw.print(" "); 15048 } else { 15049 pw.print("feat,"); 15050 } 15051 pw.println(name); 15052 } 15053 } 15054 15055 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15056 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15057 : "Activity Resolver Table:", " ", packageName, 15058 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15059 dumpState.setTitlePrinted(true); 15060 } 15061 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15062 : "Receiver Resolver Table:", " ", packageName, 15063 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15064 dumpState.setTitlePrinted(true); 15065 } 15066 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15067 : "Service Resolver Table:", " ", packageName, 15068 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15069 dumpState.setTitlePrinted(true); 15070 } 15071 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15072 : "Provider Resolver Table:", " ", packageName, 15073 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15074 dumpState.setTitlePrinted(true); 15075 } 15076 } 15077 15078 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15079 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15080 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15081 int user = mSettings.mPreferredActivities.keyAt(i); 15082 if (pir.dump(pw, 15083 dumpState.getTitlePrinted() 15084 ? "\nPreferred Activities User " + user + ":" 15085 : "Preferred Activities User " + user + ":", " ", 15086 packageName, true, false)) { 15087 dumpState.setTitlePrinted(true); 15088 } 15089 } 15090 } 15091 15092 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15093 pw.flush(); 15094 FileOutputStream fout = new FileOutputStream(fd); 15095 BufferedOutputStream str = new BufferedOutputStream(fout); 15096 XmlSerializer serializer = new FastXmlSerializer(); 15097 try { 15098 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15099 serializer.startDocument(null, true); 15100 serializer.setFeature( 15101 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15102 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15103 serializer.endDocument(); 15104 serializer.flush(); 15105 } catch (IllegalArgumentException e) { 15106 pw.println("Failed writing: " + e); 15107 } catch (IllegalStateException e) { 15108 pw.println("Failed writing: " + e); 15109 } catch (IOException e) { 15110 pw.println("Failed writing: " + e); 15111 } 15112 } 15113 15114 if (!checkin 15115 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15116 && packageName == null) { 15117 pw.println(); 15118 int count = mSettings.mPackages.size(); 15119 if (count == 0) { 15120 pw.println("No applications!"); 15121 pw.println(); 15122 } else { 15123 final String prefix = " "; 15124 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15125 if (allPackageSettings.size() == 0) { 15126 pw.println("No domain preferred apps!"); 15127 pw.println(); 15128 } else { 15129 pw.println("App verification status:"); 15130 pw.println(); 15131 count = 0; 15132 for (PackageSetting ps : allPackageSettings) { 15133 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15134 if (ivi == null || ivi.getPackageName() == null) continue; 15135 pw.println(prefix + "Package: " + ivi.getPackageName()); 15136 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15137 pw.println(prefix + "Status: " + ivi.getStatusString()); 15138 pw.println(); 15139 count++; 15140 } 15141 if (count == 0) { 15142 pw.println(prefix + "No app verification established."); 15143 pw.println(); 15144 } 15145 for (int userId : sUserManager.getUserIds()) { 15146 pw.println("App linkages for user " + userId + ":"); 15147 pw.println(); 15148 count = 0; 15149 for (PackageSetting ps : allPackageSettings) { 15150 final long status = ps.getDomainVerificationStatusForUser(userId); 15151 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15152 continue; 15153 } 15154 pw.println(prefix + "Package: " + ps.name); 15155 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15156 String statusStr = IntentFilterVerificationInfo. 15157 getStatusStringFromValue(status); 15158 pw.println(prefix + "Status: " + statusStr); 15159 pw.println(); 15160 count++; 15161 } 15162 if (count == 0) { 15163 pw.println(prefix + "No configured app linkages."); 15164 pw.println(); 15165 } 15166 } 15167 } 15168 } 15169 } 15170 15171 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15172 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15173 if (packageName == null && permissionNames == null) { 15174 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15175 if (iperm == 0) { 15176 if (dumpState.onTitlePrinted()) 15177 pw.println(); 15178 pw.println("AppOp Permissions:"); 15179 } 15180 pw.print(" AppOp Permission "); 15181 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15182 pw.println(":"); 15183 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15184 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15185 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15186 } 15187 } 15188 } 15189 } 15190 15191 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15192 boolean printedSomething = false; 15193 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15194 if (packageName != null && !packageName.equals(p.info.packageName)) { 15195 continue; 15196 } 15197 if (!printedSomething) { 15198 if (dumpState.onTitlePrinted()) 15199 pw.println(); 15200 pw.println("Registered ContentProviders:"); 15201 printedSomething = true; 15202 } 15203 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15204 pw.print(" "); pw.println(p.toString()); 15205 } 15206 printedSomething = false; 15207 for (Map.Entry<String, PackageParser.Provider> entry : 15208 mProvidersByAuthority.entrySet()) { 15209 PackageParser.Provider p = entry.getValue(); 15210 if (packageName != null && !packageName.equals(p.info.packageName)) { 15211 continue; 15212 } 15213 if (!printedSomething) { 15214 if (dumpState.onTitlePrinted()) 15215 pw.println(); 15216 pw.println("ContentProvider Authorities:"); 15217 printedSomething = true; 15218 } 15219 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15220 pw.print(" "); pw.println(p.toString()); 15221 if (p.info != null && p.info.applicationInfo != null) { 15222 final String appInfo = p.info.applicationInfo.toString(); 15223 pw.print(" applicationInfo="); pw.println(appInfo); 15224 } 15225 } 15226 } 15227 15228 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15229 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15230 } 15231 15232 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15233 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15234 } 15235 15236 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15237 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15238 } 15239 15240 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15241 // XXX should handle packageName != null by dumping only install data that 15242 // the given package is involved with. 15243 if (dumpState.onTitlePrinted()) pw.println(); 15244 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15245 } 15246 15247 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15248 if (dumpState.onTitlePrinted()) pw.println(); 15249 mSettings.dumpReadMessagesLPr(pw, dumpState); 15250 15251 pw.println(); 15252 pw.println("Package warning messages:"); 15253 BufferedReader in = null; 15254 String line = null; 15255 try { 15256 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15257 while ((line = in.readLine()) != null) { 15258 if (line.contains("ignored: updated version")) continue; 15259 pw.println(line); 15260 } 15261 } catch (IOException ignored) { 15262 } finally { 15263 IoUtils.closeQuietly(in); 15264 } 15265 } 15266 15267 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15268 BufferedReader in = null; 15269 String line = null; 15270 try { 15271 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15272 while ((line = in.readLine()) != null) { 15273 if (line.contains("ignored: updated version")) continue; 15274 pw.print("msg,"); 15275 pw.println(line); 15276 } 15277 } catch (IOException ignored) { 15278 } finally { 15279 IoUtils.closeQuietly(in); 15280 } 15281 } 15282 } 15283 } 15284 15285 private String dumpDomainString(String packageName) { 15286 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15287 List<IntentFilter> filters = getAllIntentFilters(packageName); 15288 15289 ArraySet<String> result = new ArraySet<>(); 15290 if (iviList.size() > 0) { 15291 for (IntentFilterVerificationInfo ivi : iviList) { 15292 for (String host : ivi.getDomains()) { 15293 result.add(host); 15294 } 15295 } 15296 } 15297 if (filters != null && filters.size() > 0) { 15298 for (IntentFilter filter : filters) { 15299 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15300 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15301 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15302 result.addAll(filter.getHostsList()); 15303 } 15304 } 15305 } 15306 15307 StringBuilder sb = new StringBuilder(result.size() * 16); 15308 for (String domain : result) { 15309 if (sb.length() > 0) sb.append(" "); 15310 sb.append(domain); 15311 } 15312 return sb.toString(); 15313 } 15314 15315 // ------- apps on sdcard specific code ------- 15316 static final boolean DEBUG_SD_INSTALL = false; 15317 15318 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15319 15320 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15321 15322 private boolean mMediaMounted = false; 15323 15324 static String getEncryptKey() { 15325 try { 15326 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15327 SD_ENCRYPTION_KEYSTORE_NAME); 15328 if (sdEncKey == null) { 15329 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15330 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15331 if (sdEncKey == null) { 15332 Slog.e(TAG, "Failed to create encryption keys"); 15333 return null; 15334 } 15335 } 15336 return sdEncKey; 15337 } catch (NoSuchAlgorithmException nsae) { 15338 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15339 return null; 15340 } catch (IOException ioe) { 15341 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15342 return null; 15343 } 15344 } 15345 15346 /* 15347 * Update media status on PackageManager. 15348 */ 15349 @Override 15350 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15351 int callingUid = Binder.getCallingUid(); 15352 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15353 throw new SecurityException("Media status can only be updated by the system"); 15354 } 15355 // reader; this apparently protects mMediaMounted, but should probably 15356 // be a different lock in that case. 15357 synchronized (mPackages) { 15358 Log.i(TAG, "Updating external media status from " 15359 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15360 + (mediaStatus ? "mounted" : "unmounted")); 15361 if (DEBUG_SD_INSTALL) 15362 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15363 + ", mMediaMounted=" + mMediaMounted); 15364 if (mediaStatus == mMediaMounted) { 15365 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15366 : 0, -1); 15367 mHandler.sendMessage(msg); 15368 return; 15369 } 15370 mMediaMounted = mediaStatus; 15371 } 15372 // Queue up an async operation since the package installation may take a 15373 // little while. 15374 mHandler.post(new Runnable() { 15375 public void run() { 15376 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15377 } 15378 }); 15379 } 15380 15381 /** 15382 * Called by MountService when the initial ASECs to scan are available. 15383 * Should block until all the ASEC containers are finished being scanned. 15384 */ 15385 public void scanAvailableAsecs() { 15386 updateExternalMediaStatusInner(true, false, false); 15387 if (mShouldRestoreconData) { 15388 SELinuxMMAC.setRestoreconDone(); 15389 mShouldRestoreconData = false; 15390 } 15391 } 15392 15393 /* 15394 * Collect information of applications on external media, map them against 15395 * existing containers and update information based on current mount status. 15396 * Please note that we always have to report status if reportStatus has been 15397 * set to true especially when unloading packages. 15398 */ 15399 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15400 boolean externalStorage) { 15401 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15402 int[] uidArr = EmptyArray.INT; 15403 15404 final String[] list = PackageHelper.getSecureContainerList(); 15405 if (ArrayUtils.isEmpty(list)) { 15406 Log.i(TAG, "No secure containers found"); 15407 } else { 15408 // Process list of secure containers and categorize them 15409 // as active or stale based on their package internal state. 15410 15411 // reader 15412 synchronized (mPackages) { 15413 for (String cid : list) { 15414 // Leave stages untouched for now; installer service owns them 15415 if (PackageInstallerService.isStageName(cid)) continue; 15416 15417 if (DEBUG_SD_INSTALL) 15418 Log.i(TAG, "Processing container " + cid); 15419 String pkgName = getAsecPackageName(cid); 15420 if (pkgName == null) { 15421 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15422 continue; 15423 } 15424 if (DEBUG_SD_INSTALL) 15425 Log.i(TAG, "Looking for pkg : " + pkgName); 15426 15427 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15428 if (ps == null) { 15429 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15430 continue; 15431 } 15432 15433 /* 15434 * Skip packages that are not external if we're unmounting 15435 * external storage. 15436 */ 15437 if (externalStorage && !isMounted && !isExternal(ps)) { 15438 continue; 15439 } 15440 15441 final AsecInstallArgs args = new AsecInstallArgs(cid, 15442 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15443 // The package status is changed only if the code path 15444 // matches between settings and the container id. 15445 if (ps.codePathString != null 15446 && ps.codePathString.startsWith(args.getCodePath())) { 15447 if (DEBUG_SD_INSTALL) { 15448 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15449 + " at code path: " + ps.codePathString); 15450 } 15451 15452 // We do have a valid package installed on sdcard 15453 processCids.put(args, ps.codePathString); 15454 final int uid = ps.appId; 15455 if (uid != -1) { 15456 uidArr = ArrayUtils.appendInt(uidArr, uid); 15457 } 15458 } else { 15459 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15460 + ps.codePathString); 15461 } 15462 } 15463 } 15464 15465 Arrays.sort(uidArr); 15466 } 15467 15468 // Process packages with valid entries. 15469 if (isMounted) { 15470 if (DEBUG_SD_INSTALL) 15471 Log.i(TAG, "Loading packages"); 15472 loadMediaPackages(processCids, uidArr); 15473 startCleaningPackages(); 15474 mInstallerService.onSecureContainersAvailable(); 15475 } else { 15476 if (DEBUG_SD_INSTALL) 15477 Log.i(TAG, "Unloading packages"); 15478 unloadMediaPackages(processCids, uidArr, reportStatus); 15479 } 15480 } 15481 15482 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15483 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15484 final int size = infos.size(); 15485 final String[] packageNames = new String[size]; 15486 final int[] packageUids = new int[size]; 15487 for (int i = 0; i < size; i++) { 15488 final ApplicationInfo info = infos.get(i); 15489 packageNames[i] = info.packageName; 15490 packageUids[i] = info.uid; 15491 } 15492 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15493 finishedReceiver); 15494 } 15495 15496 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15497 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15498 sendResourcesChangedBroadcast(mediaStatus, replacing, 15499 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15500 } 15501 15502 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15503 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15504 int size = pkgList.length; 15505 if (size > 0) { 15506 // Send broadcasts here 15507 Bundle extras = new Bundle(); 15508 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15509 if (uidArr != null) { 15510 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15511 } 15512 if (replacing) { 15513 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15514 } 15515 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15516 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15517 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15518 } 15519 } 15520 15521 /* 15522 * Look at potentially valid container ids from processCids If package 15523 * information doesn't match the one on record or package scanning fails, 15524 * the cid is added to list of removeCids. We currently don't delete stale 15525 * containers. 15526 */ 15527 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15528 ArrayList<String> pkgList = new ArrayList<String>(); 15529 Set<AsecInstallArgs> keys = processCids.keySet(); 15530 15531 for (AsecInstallArgs args : keys) { 15532 String codePath = processCids.get(args); 15533 if (DEBUG_SD_INSTALL) 15534 Log.i(TAG, "Loading container : " + args.cid); 15535 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15536 try { 15537 // Make sure there are no container errors first. 15538 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15539 Slog.e(TAG, "Failed to mount cid : " + args.cid 15540 + " when installing from sdcard"); 15541 continue; 15542 } 15543 // Check code path here. 15544 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15545 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15546 + " does not match one in settings " + codePath); 15547 continue; 15548 } 15549 // Parse package 15550 int parseFlags = mDefParseFlags; 15551 if (args.isExternalAsec()) { 15552 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15553 } 15554 if (args.isFwdLocked()) { 15555 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15556 } 15557 15558 synchronized (mInstallLock) { 15559 PackageParser.Package pkg = null; 15560 try { 15561 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 15562 } catch (PackageManagerException e) { 15563 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15564 } 15565 // Scan the package 15566 if (pkg != null) { 15567 /* 15568 * TODO why is the lock being held? doPostInstall is 15569 * called in other places without the lock. This needs 15570 * to be straightened out. 15571 */ 15572 // writer 15573 synchronized (mPackages) { 15574 retCode = PackageManager.INSTALL_SUCCEEDED; 15575 pkgList.add(pkg.packageName); 15576 // Post process args 15577 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15578 pkg.applicationInfo.uid); 15579 } 15580 } else { 15581 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15582 } 15583 } 15584 15585 } finally { 15586 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15587 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15588 } 15589 } 15590 } 15591 // writer 15592 synchronized (mPackages) { 15593 // If the platform SDK has changed since the last time we booted, 15594 // we need to re-grant app permission to catch any new ones that 15595 // appear. This is really a hack, and means that apps can in some 15596 // cases get permissions that the user didn't initially explicitly 15597 // allow... it would be nice to have some better way to handle 15598 // this situation. 15599 final VersionInfo ver = mSettings.getExternalVersion(); 15600 15601 int updateFlags = UPDATE_PERMISSIONS_ALL; 15602 if (ver.sdkVersion != mSdkVersion) { 15603 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15604 + mSdkVersion + "; regranting permissions for external"); 15605 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15606 } 15607 updatePermissionsLPw(null, null, updateFlags); 15608 15609 // Yay, everything is now upgraded 15610 ver.forceCurrent(); 15611 15612 // can downgrade to reader 15613 // Persist settings 15614 mSettings.writeLPr(); 15615 } 15616 // Send a broadcast to let everyone know we are done processing 15617 if (pkgList.size() > 0) { 15618 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15619 } 15620 } 15621 15622 /* 15623 * Utility method to unload a list of specified containers 15624 */ 15625 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15626 // Just unmount all valid containers. 15627 for (AsecInstallArgs arg : cidArgs) { 15628 synchronized (mInstallLock) { 15629 arg.doPostDeleteLI(false); 15630 } 15631 } 15632 } 15633 15634 /* 15635 * Unload packages mounted on external media. This involves deleting package 15636 * data from internal structures, sending broadcasts about diabled packages, 15637 * gc'ing to free up references, unmounting all secure containers 15638 * corresponding to packages on external media, and posting a 15639 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15640 * that we always have to post this message if status has been requested no 15641 * matter what. 15642 */ 15643 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15644 final boolean reportStatus) { 15645 if (DEBUG_SD_INSTALL) 15646 Log.i(TAG, "unloading media packages"); 15647 ArrayList<String> pkgList = new ArrayList<String>(); 15648 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15649 final Set<AsecInstallArgs> keys = processCids.keySet(); 15650 for (AsecInstallArgs args : keys) { 15651 String pkgName = args.getPackageName(); 15652 if (DEBUG_SD_INSTALL) 15653 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15654 // Delete package internally 15655 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15656 synchronized (mInstallLock) { 15657 boolean res = deletePackageLI(pkgName, null, false, null, null, 15658 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15659 if (res) { 15660 pkgList.add(pkgName); 15661 } else { 15662 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15663 failedList.add(args); 15664 } 15665 } 15666 } 15667 15668 // reader 15669 synchronized (mPackages) { 15670 // We didn't update the settings after removing each package; 15671 // write them now for all packages. 15672 mSettings.writeLPr(); 15673 } 15674 15675 // We have to absolutely send UPDATED_MEDIA_STATUS only 15676 // after confirming that all the receivers processed the ordered 15677 // broadcast when packages get disabled, force a gc to clean things up. 15678 // and unload all the containers. 15679 if (pkgList.size() > 0) { 15680 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15681 new IIntentReceiver.Stub() { 15682 public void performReceive(Intent intent, int resultCode, String data, 15683 Bundle extras, boolean ordered, boolean sticky, 15684 int sendingUser) throws RemoteException { 15685 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15686 reportStatus ? 1 : 0, 1, keys); 15687 mHandler.sendMessage(msg); 15688 } 15689 }); 15690 } else { 15691 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15692 keys); 15693 mHandler.sendMessage(msg); 15694 } 15695 } 15696 15697 private void loadPrivatePackages(VolumeInfo vol) { 15698 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15699 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15700 synchronized (mInstallLock) { 15701 synchronized (mPackages) { 15702 final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid); 15703 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15704 for (PackageSetting ps : packages) { 15705 final PackageParser.Package pkg; 15706 try { 15707 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15708 loaded.add(pkg.applicationInfo); 15709 } catch (PackageManagerException e) { 15710 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15711 } 15712 15713 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15714 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15715 } 15716 } 15717 15718 int updateFlags = UPDATE_PERMISSIONS_ALL; 15719 if (ver.sdkVersion != mSdkVersion) { 15720 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15721 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15722 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15723 } 15724 updatePermissionsLPw(null, null, updateFlags); 15725 15726 // Yay, everything is now upgraded 15727 ver.forceCurrent(); 15728 15729 mSettings.writeLPr(); 15730 } 15731 } 15732 15733 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15734 sendResourcesChangedBroadcast(true, false, loaded, null); 15735 } 15736 15737 private void unloadPrivatePackages(VolumeInfo vol) { 15738 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15739 synchronized (mInstallLock) { 15740 synchronized (mPackages) { 15741 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15742 for (PackageSetting ps : packages) { 15743 if (ps.pkg == null) continue; 15744 15745 final ApplicationInfo info = ps.pkg.applicationInfo; 15746 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15747 if (deletePackageLI(ps.name, null, false, null, null, 15748 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15749 unloaded.add(info); 15750 } else { 15751 Slog.w(TAG, "Failed to unload " + ps.codePath); 15752 } 15753 } 15754 15755 mSettings.writeLPr(); 15756 } 15757 } 15758 15759 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15760 sendResourcesChangedBroadcast(false, false, unloaded, null); 15761 } 15762 15763 /** 15764 * Examine all users present on given mounted volume, and destroy data 15765 * belonging to users that are no longer valid, or whose user ID has been 15766 * recycled. 15767 */ 15768 private void reconcileUsers(String volumeUuid) { 15769 final File[] files = FileUtils 15770 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15771 for (File file : files) { 15772 if (!file.isDirectory()) continue; 15773 15774 final int userId; 15775 final UserInfo info; 15776 try { 15777 userId = Integer.parseInt(file.getName()); 15778 info = sUserManager.getUserInfo(userId); 15779 } catch (NumberFormatException e) { 15780 Slog.w(TAG, "Invalid user directory " + file); 15781 continue; 15782 } 15783 15784 boolean destroyUser = false; 15785 if (info == null) { 15786 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15787 + " because no matching user was found"); 15788 destroyUser = true; 15789 } else { 15790 try { 15791 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15792 } catch (IOException e) { 15793 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15794 + " because we failed to enforce serial number: " + e); 15795 destroyUser = true; 15796 } 15797 } 15798 15799 if (destroyUser) { 15800 synchronized (mInstallLock) { 15801 mInstaller.removeUserDataDirs(volumeUuid, userId); 15802 } 15803 } 15804 } 15805 15806 final UserManager um = mContext.getSystemService(UserManager.class); 15807 for (UserInfo user : um.getUsers()) { 15808 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15809 if (userDir.exists()) continue; 15810 15811 try { 15812 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15813 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15814 } catch (IOException e) { 15815 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15816 } 15817 } 15818 } 15819 15820 /** 15821 * Examine all apps present on given mounted volume, and destroy apps that 15822 * aren't expected, either due to uninstallation or reinstallation on 15823 * another volume. 15824 */ 15825 private void reconcileApps(String volumeUuid) { 15826 final File[] files = FileUtils 15827 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15828 for (File file : files) { 15829 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15830 && !PackageInstallerService.isStageName(file.getName()); 15831 if (!isPackage) { 15832 // Ignore entries which are not packages 15833 continue; 15834 } 15835 15836 boolean destroyApp = false; 15837 String packageName = null; 15838 try { 15839 final PackageLite pkg = PackageParser.parsePackageLite(file, 15840 PackageParser.PARSE_MUST_BE_APK); 15841 packageName = pkg.packageName; 15842 15843 synchronized (mPackages) { 15844 final PackageSetting ps = mSettings.mPackages.get(packageName); 15845 if (ps == null) { 15846 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15847 + volumeUuid + " because we found no install record"); 15848 destroyApp = true; 15849 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15850 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15851 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15852 destroyApp = true; 15853 } 15854 } 15855 15856 } catch (PackageParserException e) { 15857 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15858 destroyApp = true; 15859 } 15860 15861 if (destroyApp) { 15862 synchronized (mInstallLock) { 15863 if (packageName != null) { 15864 removeDataDirsLI(volumeUuid, packageName); 15865 } 15866 if (file.isDirectory()) { 15867 mInstaller.rmPackageDir(file.getAbsolutePath()); 15868 } else { 15869 file.delete(); 15870 } 15871 } 15872 } 15873 } 15874 } 15875 15876 private void unfreezePackage(String packageName) { 15877 synchronized (mPackages) { 15878 final PackageSetting ps = mSettings.mPackages.get(packageName); 15879 if (ps != null) { 15880 ps.frozen = false; 15881 } 15882 } 15883 } 15884 15885 @Override 15886 public int movePackage(final String packageName, final String volumeUuid) { 15887 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15888 15889 final int moveId = mNextMoveId.getAndIncrement(); 15890 try { 15891 movePackageInternal(packageName, volumeUuid, moveId); 15892 } catch (PackageManagerException e) { 15893 Slog.w(TAG, "Failed to move " + packageName, e); 15894 mMoveCallbacks.notifyStatusChanged(moveId, 15895 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15896 } 15897 return moveId; 15898 } 15899 15900 private void movePackageInternal(final String packageName, final String volumeUuid, 15901 final int moveId) throws PackageManagerException { 15902 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15903 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15904 final PackageManager pm = mContext.getPackageManager(); 15905 15906 final boolean currentAsec; 15907 final String currentVolumeUuid; 15908 final File codeFile; 15909 final String installerPackageName; 15910 final String packageAbiOverride; 15911 final int appId; 15912 final String seinfo; 15913 final String label; 15914 15915 // reader 15916 synchronized (mPackages) { 15917 final PackageParser.Package pkg = mPackages.get(packageName); 15918 final PackageSetting ps = mSettings.mPackages.get(packageName); 15919 if (pkg == null || ps == null) { 15920 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15921 } 15922 15923 if (pkg.applicationInfo.isSystemApp()) { 15924 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15925 "Cannot move system application"); 15926 } 15927 15928 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15929 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15930 "Package already moved to " + volumeUuid); 15931 } 15932 15933 final File probe = new File(pkg.codePath); 15934 final File probeOat = new File(probe, "oat"); 15935 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15936 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15937 "Move only supported for modern cluster style installs"); 15938 } 15939 15940 if (ps.frozen) { 15941 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15942 "Failed to move already frozen package"); 15943 } 15944 ps.frozen = true; 15945 15946 currentAsec = pkg.applicationInfo.isForwardLocked() 15947 || pkg.applicationInfo.isExternalAsec(); 15948 currentVolumeUuid = ps.volumeUuid; 15949 codeFile = new File(pkg.codePath); 15950 installerPackageName = ps.installerPackageName; 15951 packageAbiOverride = ps.cpuAbiOverrideString; 15952 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15953 seinfo = pkg.applicationInfo.seinfo; 15954 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15955 } 15956 15957 // Now that we're guarded by frozen state, kill app during move 15958 final long token = Binder.clearCallingIdentity(); 15959 try { 15960 killApplication(packageName, appId, "move pkg"); 15961 } finally { 15962 Binder.restoreCallingIdentity(token); 15963 } 15964 15965 final Bundle extras = new Bundle(); 15966 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15967 extras.putString(Intent.EXTRA_TITLE, label); 15968 mMoveCallbacks.notifyCreated(moveId, extras); 15969 15970 int installFlags; 15971 final boolean moveCompleteApp; 15972 final File measurePath; 15973 15974 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15975 installFlags = INSTALL_INTERNAL; 15976 moveCompleteApp = !currentAsec; 15977 measurePath = Environment.getDataAppDirectory(volumeUuid); 15978 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15979 installFlags = INSTALL_EXTERNAL; 15980 moveCompleteApp = false; 15981 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15982 } else { 15983 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15984 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15985 || !volume.isMountedWritable()) { 15986 unfreezePackage(packageName); 15987 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15988 "Move location not mounted private volume"); 15989 } 15990 15991 Preconditions.checkState(!currentAsec); 15992 15993 installFlags = INSTALL_INTERNAL; 15994 moveCompleteApp = true; 15995 measurePath = Environment.getDataAppDirectory(volumeUuid); 15996 } 15997 15998 final PackageStats stats = new PackageStats(null, -1); 15999 synchronized (mInstaller) { 16000 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16001 unfreezePackage(packageName); 16002 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16003 "Failed to measure package size"); 16004 } 16005 } 16006 16007 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16008 + stats.dataSize); 16009 16010 final long startFreeBytes = measurePath.getFreeSpace(); 16011 final long sizeBytes; 16012 if (moveCompleteApp) { 16013 sizeBytes = stats.codeSize + stats.dataSize; 16014 } else { 16015 sizeBytes = stats.codeSize; 16016 } 16017 16018 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16019 unfreezePackage(packageName); 16020 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16021 "Not enough free space to move"); 16022 } 16023 16024 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16025 16026 final CountDownLatch installedLatch = new CountDownLatch(1); 16027 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16028 @Override 16029 public void onUserActionRequired(Intent intent) throws RemoteException { 16030 throw new IllegalStateException(); 16031 } 16032 16033 @Override 16034 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16035 Bundle extras) throws RemoteException { 16036 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16037 + PackageManager.installStatusToString(returnCode, msg)); 16038 16039 installedLatch.countDown(); 16040 16041 // Regardless of success or failure of the move operation, 16042 // always unfreeze the package 16043 unfreezePackage(packageName); 16044 16045 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16046 switch (status) { 16047 case PackageInstaller.STATUS_SUCCESS: 16048 mMoveCallbacks.notifyStatusChanged(moveId, 16049 PackageManager.MOVE_SUCCEEDED); 16050 break; 16051 case PackageInstaller.STATUS_FAILURE_STORAGE: 16052 mMoveCallbacks.notifyStatusChanged(moveId, 16053 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16054 break; 16055 default: 16056 mMoveCallbacks.notifyStatusChanged(moveId, 16057 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16058 break; 16059 } 16060 } 16061 }; 16062 16063 final MoveInfo move; 16064 if (moveCompleteApp) { 16065 // Kick off a thread to report progress estimates 16066 new Thread() { 16067 @Override 16068 public void run() { 16069 while (true) { 16070 try { 16071 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16072 break; 16073 } 16074 } catch (InterruptedException ignored) { 16075 } 16076 16077 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16078 final int progress = 10 + (int) MathUtils.constrain( 16079 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16080 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16081 } 16082 } 16083 }.start(); 16084 16085 final String dataAppName = codeFile.getName(); 16086 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16087 dataAppName, appId, seinfo); 16088 } else { 16089 move = null; 16090 } 16091 16092 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16093 16094 final Message msg = mHandler.obtainMessage(INIT_COPY); 16095 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16096 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 16097 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16098 mHandler.sendMessage(msg); 16099 } 16100 16101 @Override 16102 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16103 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16104 16105 final int realMoveId = mNextMoveId.getAndIncrement(); 16106 final Bundle extras = new Bundle(); 16107 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16108 mMoveCallbacks.notifyCreated(realMoveId, extras); 16109 16110 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16111 @Override 16112 public void onCreated(int moveId, Bundle extras) { 16113 // Ignored 16114 } 16115 16116 @Override 16117 public void onStatusChanged(int moveId, int status, long estMillis) { 16118 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16119 } 16120 }; 16121 16122 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16123 storage.setPrimaryStorageUuid(volumeUuid, callback); 16124 return realMoveId; 16125 } 16126 16127 @Override 16128 public int getMoveStatus(int moveId) { 16129 mContext.enforceCallingOrSelfPermission( 16130 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16131 return mMoveCallbacks.mLastStatus.get(moveId); 16132 } 16133 16134 @Override 16135 public void registerMoveCallback(IPackageMoveObserver callback) { 16136 mContext.enforceCallingOrSelfPermission( 16137 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16138 mMoveCallbacks.register(callback); 16139 } 16140 16141 @Override 16142 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16143 mContext.enforceCallingOrSelfPermission( 16144 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16145 mMoveCallbacks.unregister(callback); 16146 } 16147 16148 @Override 16149 public boolean setInstallLocation(int loc) { 16150 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16151 null); 16152 if (getInstallLocation() == loc) { 16153 return true; 16154 } 16155 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16156 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16157 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16158 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16159 return true; 16160 } 16161 return false; 16162 } 16163 16164 @Override 16165 public int getInstallLocation() { 16166 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16167 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16168 PackageHelper.APP_INSTALL_AUTO); 16169 } 16170 16171 /** Called by UserManagerService */ 16172 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16173 mDirtyUsers.remove(userHandle); 16174 mSettings.removeUserLPw(userHandle); 16175 mPendingBroadcasts.remove(userHandle); 16176 if (mInstaller != null) { 16177 // Technically, we shouldn't be doing this with the package lock 16178 // held. However, this is very rare, and there is already so much 16179 // other disk I/O going on, that we'll let it slide for now. 16180 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16181 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16182 final String volumeUuid = vol.getFsUuid(); 16183 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16184 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16185 } 16186 } 16187 mUserNeedsBadging.delete(userHandle); 16188 removeUnusedPackagesLILPw(userManager, userHandle); 16189 } 16190 16191 /** 16192 * We're removing userHandle and would like to remove any downloaded packages 16193 * that are no longer in use by any other user. 16194 * @param userHandle the user being removed 16195 */ 16196 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16197 final boolean DEBUG_CLEAN_APKS = false; 16198 int [] users = userManager.getUserIdsLPr(); 16199 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16200 while (psit.hasNext()) { 16201 PackageSetting ps = psit.next(); 16202 if (ps.pkg == null) { 16203 continue; 16204 } 16205 final String packageName = ps.pkg.packageName; 16206 // Skip over if system app 16207 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16208 continue; 16209 } 16210 if (DEBUG_CLEAN_APKS) { 16211 Slog.i(TAG, "Checking package " + packageName); 16212 } 16213 boolean keep = false; 16214 for (int i = 0; i < users.length; i++) { 16215 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16216 keep = true; 16217 if (DEBUG_CLEAN_APKS) { 16218 Slog.i(TAG, " Keeping package " + packageName + " for user " 16219 + users[i]); 16220 } 16221 break; 16222 } 16223 } 16224 if (!keep) { 16225 if (DEBUG_CLEAN_APKS) { 16226 Slog.i(TAG, " Removing package " + packageName); 16227 } 16228 mHandler.post(new Runnable() { 16229 public void run() { 16230 deletePackageX(packageName, userHandle, 0); 16231 } //end run 16232 }); 16233 } 16234 } 16235 } 16236 16237 /** Called by UserManagerService */ 16238 void createNewUserLILPw(int userHandle) { 16239 if (mInstaller != null) { 16240 mInstaller.createUserConfig(userHandle); 16241 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16242 applyFactoryDefaultBrowserLPw(userHandle); 16243 primeDomainVerificationsLPw(userHandle); 16244 } 16245 } 16246 16247 void newUserCreated(final int userHandle) { 16248 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16249 } 16250 16251 @Override 16252 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16253 mContext.enforceCallingOrSelfPermission( 16254 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16255 "Only package verification agents can read the verifier device identity"); 16256 16257 synchronized (mPackages) { 16258 return mSettings.getVerifierDeviceIdentityLPw(); 16259 } 16260 } 16261 16262 @Override 16263 public void setPermissionEnforced(String permission, boolean enforced) { 16264 // TODO: Now that we no longer change GID for storage, this should to away. 16265 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16266 "setPermissionEnforced"); 16267 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16268 synchronized (mPackages) { 16269 if (mSettings.mReadExternalStorageEnforced == null 16270 || mSettings.mReadExternalStorageEnforced != enforced) { 16271 mSettings.mReadExternalStorageEnforced = enforced; 16272 mSettings.writeLPr(); 16273 } 16274 } 16275 // kill any non-foreground processes so we restart them and 16276 // grant/revoke the GID. 16277 final IActivityManager am = ActivityManagerNative.getDefault(); 16278 if (am != null) { 16279 final long token = Binder.clearCallingIdentity(); 16280 try { 16281 am.killProcessesBelowForeground("setPermissionEnforcement"); 16282 } catch (RemoteException e) { 16283 } finally { 16284 Binder.restoreCallingIdentity(token); 16285 } 16286 } 16287 } else { 16288 throw new IllegalArgumentException("No selective enforcement for " + permission); 16289 } 16290 } 16291 16292 @Override 16293 @Deprecated 16294 public boolean isPermissionEnforced(String permission) { 16295 return true; 16296 } 16297 16298 @Override 16299 public boolean isStorageLow() { 16300 final long token = Binder.clearCallingIdentity(); 16301 try { 16302 final DeviceStorageMonitorInternal 16303 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16304 if (dsm != null) { 16305 return dsm.isMemoryLow(); 16306 } else { 16307 return false; 16308 } 16309 } finally { 16310 Binder.restoreCallingIdentity(token); 16311 } 16312 } 16313 16314 @Override 16315 public IPackageInstaller getPackageInstaller() { 16316 return mInstallerService; 16317 } 16318 16319 private boolean userNeedsBadging(int userId) { 16320 int index = mUserNeedsBadging.indexOfKey(userId); 16321 if (index < 0) { 16322 final UserInfo userInfo; 16323 final long token = Binder.clearCallingIdentity(); 16324 try { 16325 userInfo = sUserManager.getUserInfo(userId); 16326 } finally { 16327 Binder.restoreCallingIdentity(token); 16328 } 16329 final boolean b; 16330 if (userInfo != null && userInfo.isManagedProfile()) { 16331 b = true; 16332 } else { 16333 b = false; 16334 } 16335 mUserNeedsBadging.put(userId, b); 16336 return b; 16337 } 16338 return mUserNeedsBadging.valueAt(index); 16339 } 16340 16341 @Override 16342 public KeySet getKeySetByAlias(String packageName, String alias) { 16343 if (packageName == null || alias == null) { 16344 return null; 16345 } 16346 synchronized(mPackages) { 16347 final PackageParser.Package pkg = mPackages.get(packageName); 16348 if (pkg == null) { 16349 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16350 throw new IllegalArgumentException("Unknown package: " + packageName); 16351 } 16352 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16353 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16354 } 16355 } 16356 16357 @Override 16358 public KeySet getSigningKeySet(String packageName) { 16359 if (packageName == null) { 16360 return null; 16361 } 16362 synchronized(mPackages) { 16363 final PackageParser.Package pkg = mPackages.get(packageName); 16364 if (pkg == null) { 16365 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16366 throw new IllegalArgumentException("Unknown package: " + packageName); 16367 } 16368 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16369 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16370 throw new SecurityException("May not access signing KeySet of other apps."); 16371 } 16372 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16373 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16374 } 16375 } 16376 16377 @Override 16378 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16379 if (packageName == null || ks == null) { 16380 return false; 16381 } 16382 synchronized(mPackages) { 16383 final PackageParser.Package pkg = mPackages.get(packageName); 16384 if (pkg == null) { 16385 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16386 throw new IllegalArgumentException("Unknown package: " + packageName); 16387 } 16388 IBinder ksh = ks.getToken(); 16389 if (ksh instanceof KeySetHandle) { 16390 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16391 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16392 } 16393 return false; 16394 } 16395 } 16396 16397 @Override 16398 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16399 if (packageName == null || ks == null) { 16400 return false; 16401 } 16402 synchronized(mPackages) { 16403 final PackageParser.Package pkg = mPackages.get(packageName); 16404 if (pkg == null) { 16405 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16406 throw new IllegalArgumentException("Unknown package: " + packageName); 16407 } 16408 IBinder ksh = ks.getToken(); 16409 if (ksh instanceof KeySetHandle) { 16410 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16411 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16412 } 16413 return false; 16414 } 16415 } 16416 16417 public void getUsageStatsIfNoPackageUsageInfo() { 16418 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16419 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16420 if (usm == null) { 16421 throw new IllegalStateException("UsageStatsManager must be initialized"); 16422 } 16423 long now = System.currentTimeMillis(); 16424 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16425 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16426 String packageName = entry.getKey(); 16427 PackageParser.Package pkg = mPackages.get(packageName); 16428 if (pkg == null) { 16429 continue; 16430 } 16431 UsageStats usage = entry.getValue(); 16432 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16433 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16434 } 16435 } 16436 } 16437 16438 /** 16439 * Check and throw if the given before/after packages would be considered a 16440 * downgrade. 16441 */ 16442 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16443 throws PackageManagerException { 16444 if (after.versionCode < before.mVersionCode) { 16445 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16446 "Update version code " + after.versionCode + " is older than current " 16447 + before.mVersionCode); 16448 } else if (after.versionCode == before.mVersionCode) { 16449 if (after.baseRevisionCode < before.baseRevisionCode) { 16450 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16451 "Update base revision code " + after.baseRevisionCode 16452 + " is older than current " + before.baseRevisionCode); 16453 } 16454 16455 if (!ArrayUtils.isEmpty(after.splitNames)) { 16456 for (int i = 0; i < after.splitNames.length; i++) { 16457 final String splitName = after.splitNames[i]; 16458 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16459 if (j != -1) { 16460 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16461 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16462 "Update split " + splitName + " revision code " 16463 + after.splitRevisionCodes[i] + " is older than current " 16464 + before.splitRevisionCodes[j]); 16465 } 16466 } 16467 } 16468 } 16469 } 16470 } 16471 16472 private static class MoveCallbacks extends Handler { 16473 private static final int MSG_CREATED = 1; 16474 private static final int MSG_STATUS_CHANGED = 2; 16475 16476 private final RemoteCallbackList<IPackageMoveObserver> 16477 mCallbacks = new RemoteCallbackList<>(); 16478 16479 private final SparseIntArray mLastStatus = new SparseIntArray(); 16480 16481 public MoveCallbacks(Looper looper) { 16482 super(looper); 16483 } 16484 16485 public void register(IPackageMoveObserver callback) { 16486 mCallbacks.register(callback); 16487 } 16488 16489 public void unregister(IPackageMoveObserver callback) { 16490 mCallbacks.unregister(callback); 16491 } 16492 16493 @Override 16494 public void handleMessage(Message msg) { 16495 final SomeArgs args = (SomeArgs) msg.obj; 16496 final int n = mCallbacks.beginBroadcast(); 16497 for (int i = 0; i < n; i++) { 16498 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16499 try { 16500 invokeCallback(callback, msg.what, args); 16501 } catch (RemoteException ignored) { 16502 } 16503 } 16504 mCallbacks.finishBroadcast(); 16505 args.recycle(); 16506 } 16507 16508 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16509 throws RemoteException { 16510 switch (what) { 16511 case MSG_CREATED: { 16512 callback.onCreated(args.argi1, (Bundle) args.arg2); 16513 break; 16514 } 16515 case MSG_STATUS_CHANGED: { 16516 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16517 break; 16518 } 16519 } 16520 } 16521 16522 private void notifyCreated(int moveId, Bundle extras) { 16523 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16524 16525 final SomeArgs args = SomeArgs.obtain(); 16526 args.argi1 = moveId; 16527 args.arg2 = extras; 16528 obtainMessage(MSG_CREATED, args).sendToTarget(); 16529 } 16530 16531 private void notifyStatusChanged(int moveId, int status) { 16532 notifyStatusChanged(moveId, status, -1); 16533 } 16534 16535 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16536 Slog.v(TAG, "Move " + moveId + " status " + status); 16537 16538 final SomeArgs args = SomeArgs.obtain(); 16539 args.argi1 = moveId; 16540 args.argi2 = status; 16541 args.arg3 = estMillis; 16542 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16543 16544 synchronized (mLastStatus) { 16545 mLastStatus.put(moveId, status); 16546 } 16547 } 16548 } 16549 16550 private final class OnPermissionChangeListeners extends Handler { 16551 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16552 16553 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16554 new RemoteCallbackList<>(); 16555 16556 public OnPermissionChangeListeners(Looper looper) { 16557 super(looper); 16558 } 16559 16560 @Override 16561 public void handleMessage(Message msg) { 16562 switch (msg.what) { 16563 case MSG_ON_PERMISSIONS_CHANGED: { 16564 final int uid = msg.arg1; 16565 handleOnPermissionsChanged(uid); 16566 } break; 16567 } 16568 } 16569 16570 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16571 mPermissionListeners.register(listener); 16572 16573 } 16574 16575 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16576 mPermissionListeners.unregister(listener); 16577 } 16578 16579 public void onPermissionsChanged(int uid) { 16580 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16581 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16582 } 16583 } 16584 16585 private void handleOnPermissionsChanged(int uid) { 16586 final int count = mPermissionListeners.beginBroadcast(); 16587 try { 16588 for (int i = 0; i < count; i++) { 16589 IOnPermissionsChangeListener callback = mPermissionListeners 16590 .getBroadcastItem(i); 16591 try { 16592 callback.onPermissionsChanged(uid); 16593 } catch (RemoteException e) { 16594 Log.e(TAG, "Permission listener is dead", e); 16595 } 16596 } 16597 } finally { 16598 mPermissionListeners.finishBroadcast(); 16599 } 16600 } 16601 } 16602 16603 private class PackageManagerInternalImpl extends PackageManagerInternal { 16604 @Override 16605 public void setLocationPackagesProvider(PackagesProvider provider) { 16606 synchronized (mPackages) { 16607 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16608 } 16609 } 16610 16611 @Override 16612 public void setImePackagesProvider(PackagesProvider provider) { 16613 synchronized (mPackages) { 16614 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16615 } 16616 } 16617 16618 @Override 16619 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16620 synchronized (mPackages) { 16621 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16622 } 16623 } 16624 16625 @Override 16626 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16627 synchronized (mPackages) { 16628 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16629 } 16630 } 16631 16632 @Override 16633 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16634 synchronized (mPackages) { 16635 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16636 } 16637 } 16638 16639 @Override 16640 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16641 synchronized (mPackages) { 16642 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16643 } 16644 } 16645 16646 @Override 16647 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16648 synchronized (mPackages) { 16649 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16650 } 16651 } 16652 16653 @Override 16654 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16655 synchronized (mPackages) { 16656 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16657 packageName, userId); 16658 } 16659 } 16660 16661 @Override 16662 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16663 synchronized (mPackages) { 16664 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16665 packageName, userId); 16666 } 16667 } 16668 @Override 16669 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16670 synchronized (mPackages) { 16671 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16672 packageName, userId); 16673 } 16674 } 16675 } 16676 16677 @Override 16678 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16679 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16680 synchronized (mPackages) { 16681 final long identity = Binder.clearCallingIdentity(); 16682 try { 16683 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16684 packageNames, userId); 16685 } finally { 16686 Binder.restoreCallingIdentity(identity); 16687 } 16688 } 16689 } 16690 16691 private static void enforceSystemOrPhoneCaller(String tag) { 16692 int callingUid = Binder.getCallingUid(); 16693 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16694 throw new SecurityException( 16695 "Cannot call " + tag + " from UID " + callingUid); 16696 } 16697 } 16698} 16699