PackageManagerService.java revision 4b72aab7fb063f99406577d4ac0beaeac174982a
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_REVIEW_REQUIRED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 34import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 61import static android.content.pm.PackageManager.MATCH_ALL; 62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 63import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 64import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 65import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 66import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 67import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 68import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 69import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 70import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 71import static android.content.pm.PackageManager.PERMISSION_DENIED; 72import static android.content.pm.PackageManager.PERMISSION_GRANTED; 73import static android.content.pm.PackageParser.isApkFile; 74import static android.os.Process.PACKAGE_INFO_GID; 75import static android.os.Process.SYSTEM_UID; 76import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 77import static android.system.OsConstants.O_CREAT; 78import static android.system.OsConstants.O_RDWR; 79 80import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 81import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 82import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 83import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 84import static com.android.internal.util.ArrayUtils.appendInt; 85import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 86import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 87import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 88import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 89import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 90import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 91import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 92import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 93import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 94 95import android.Manifest; 96import android.annotation.NonNull; 97import android.annotation.Nullable; 98import android.app.ActivityManager; 99import android.app.ActivityManagerNative; 100import android.app.AppGlobals; 101import android.app.IActivityManager; 102import android.app.admin.IDevicePolicyManager; 103import android.app.backup.IBackupManager; 104import android.content.BroadcastReceiver; 105import android.content.ComponentName; 106import android.content.Context; 107import android.content.IIntentReceiver; 108import android.content.Intent; 109import android.content.IntentFilter; 110import android.content.IntentSender; 111import android.content.IntentSender.SendIntentException; 112import android.content.ServiceConnection; 113import android.content.pm.ActivityInfo; 114import android.content.pm.ApplicationInfo; 115import android.content.pm.AppsQueryHelper; 116import android.content.pm.ComponentInfo; 117import android.content.pm.EphemeralApplicationInfo; 118import android.content.pm.EphemeralResolveInfo; 119import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 120import android.content.pm.FeatureInfo; 121import android.content.pm.IOnPermissionsChangeListener; 122import android.content.pm.IPackageDataObserver; 123import android.content.pm.IPackageDeleteObserver; 124import android.content.pm.IPackageDeleteObserver2; 125import android.content.pm.IPackageInstallObserver2; 126import android.content.pm.IPackageInstaller; 127import android.content.pm.IPackageManager; 128import android.content.pm.IPackageMoveObserver; 129import android.content.pm.IPackageStatsObserver; 130import android.content.pm.InstrumentationInfo; 131import android.content.pm.IntentFilterVerificationInfo; 132import android.content.pm.KeySet; 133import android.content.pm.PackageCleanItem; 134import android.content.pm.PackageInfo; 135import android.content.pm.PackageInfoLite; 136import android.content.pm.PackageInstaller; 137import android.content.pm.PackageManager; 138import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 139import android.content.pm.PackageManagerInternal; 140import android.content.pm.PackageParser; 141import android.content.pm.PackageParser.ActivityIntentInfo; 142import android.content.pm.PackageParser.Package; 143import android.content.pm.PackageParser.PackageLite; 144import android.content.pm.PackageParser.PackageParserException; 145import android.content.pm.PackageStats; 146import android.content.pm.PackageUserState; 147import android.content.pm.ParceledListSlice; 148import android.content.pm.PermissionGroupInfo; 149import android.content.pm.PermissionInfo; 150import android.content.pm.ProviderInfo; 151import android.content.pm.ResolveInfo; 152import android.content.pm.ServiceInfo; 153import android.content.pm.Signature; 154import android.content.pm.UserInfo; 155import android.content.pm.VerificationParams; 156import android.content.pm.VerifierDeviceIdentity; 157import android.content.pm.VerifierInfo; 158import android.content.res.Resources; 159import android.graphics.Bitmap; 160import android.hardware.display.DisplayManager; 161import android.net.Uri; 162import android.os.Binder; 163import android.os.Build; 164import android.os.Bundle; 165import android.os.Debug; 166import android.os.Environment; 167import android.os.Environment.UserEnvironment; 168import android.os.FileUtils; 169import android.os.Handler; 170import android.os.IBinder; 171import android.os.Looper; 172import android.os.Message; 173import android.os.Parcel; 174import android.os.ParcelFileDescriptor; 175import android.os.Process; 176import android.os.RemoteCallbackList; 177import android.os.RemoteException; 178import android.os.ResultReceiver; 179import android.os.SELinux; 180import android.os.ServiceManager; 181import android.os.SystemClock; 182import android.os.SystemProperties; 183import android.os.Trace; 184import android.os.UserHandle; 185import android.os.UserManager; 186import android.os.storage.IMountService; 187import android.os.storage.MountServiceInternal; 188import android.os.storage.StorageEventListener; 189import android.os.storage.StorageManager; 190import android.os.storage.VolumeInfo; 191import android.os.storage.VolumeRecord; 192import android.security.KeyStore; 193import android.security.SystemKeyStore; 194import android.system.ErrnoException; 195import android.system.Os; 196import android.text.TextUtils; 197import android.text.format.DateUtils; 198import android.util.ArrayMap; 199import android.util.ArraySet; 200import android.util.AtomicFile; 201import android.util.DisplayMetrics; 202import android.util.EventLog; 203import android.util.ExceptionUtils; 204import android.util.Log; 205import android.util.LogPrinter; 206import android.util.MathUtils; 207import android.util.PrintStreamPrinter; 208import android.util.Slog; 209import android.util.SparseArray; 210import android.util.SparseBooleanArray; 211import android.util.SparseIntArray; 212import android.util.Xml; 213import android.view.Display; 214 215import com.android.internal.R; 216import com.android.internal.annotations.GuardedBy; 217import com.android.internal.app.IMediaContainerService; 218import com.android.internal.app.ResolverActivity; 219import com.android.internal.content.NativeLibraryHelper; 220import com.android.internal.content.PackageHelper; 221import com.android.internal.os.IParcelFileDescriptorFactory; 222import com.android.internal.os.InstallerConnection.InstallerException; 223import com.android.internal.os.SomeArgs; 224import com.android.internal.os.Zygote; 225import com.android.internal.util.ArrayUtils; 226import com.android.internal.util.FastPrintWriter; 227import com.android.internal.util.FastXmlSerializer; 228import com.android.internal.util.IndentingPrintWriter; 229import com.android.internal.util.Preconditions; 230import com.android.internal.util.XmlUtils; 231import com.android.server.EventLogTags; 232import com.android.server.FgThread; 233import com.android.server.IntentResolver; 234import com.android.server.LocalServices; 235import com.android.server.ServiceThread; 236import com.android.server.SystemConfig; 237import com.android.server.Watchdog; 238import com.android.server.pm.PermissionsState.PermissionState; 239import com.android.server.pm.Settings.DatabaseVersion; 240import com.android.server.pm.Settings.VersionInfo; 241import com.android.server.storage.DeviceStorageMonitorInternal; 242 243import dalvik.system.DexFile; 244import dalvik.system.VMRuntime; 245 246import libcore.io.IoUtils; 247import libcore.util.EmptyArray; 248 249import org.xmlpull.v1.XmlPullParser; 250import org.xmlpull.v1.XmlPullParserException; 251import org.xmlpull.v1.XmlSerializer; 252 253import java.io.BufferedInputStream; 254import java.io.BufferedOutputStream; 255import java.io.BufferedReader; 256import java.io.ByteArrayInputStream; 257import java.io.ByteArrayOutputStream; 258import java.io.File; 259import java.io.FileDescriptor; 260import java.io.FileNotFoundException; 261import java.io.FileOutputStream; 262import java.io.FileReader; 263import java.io.FilenameFilter; 264import java.io.IOException; 265import java.io.InputStream; 266import java.io.PrintStream; 267import java.io.PrintWriter; 268import java.nio.charset.StandardCharsets; 269import java.security.MessageDigest; 270import java.security.NoSuchAlgorithmException; 271import java.security.PublicKey; 272import java.security.cert.CertificateEncodingException; 273import java.security.cert.CertificateException; 274import java.text.SimpleDateFormat; 275import java.util.ArrayList; 276import java.util.Arrays; 277import java.util.Collection; 278import java.util.Collections; 279import java.util.Comparator; 280import java.util.Date; 281import java.util.HashSet; 282import java.util.Iterator; 283import java.util.List; 284import java.util.Map; 285import java.util.Objects; 286import java.util.Set; 287import java.util.concurrent.CountDownLatch; 288import java.util.concurrent.TimeUnit; 289import java.util.concurrent.atomic.AtomicBoolean; 290import java.util.concurrent.atomic.AtomicInteger; 291import java.util.concurrent.atomic.AtomicLong; 292 293/** 294 * Keep track of all those .apks everywhere. 295 * 296 * This is very central to the platform's security; please run the unit 297 * tests whenever making modifications here: 298 * 299runtest -c android.content.pm.PackageManagerTests frameworks-core 300 * 301 * {@hide} 302 */ 303public class PackageManagerService extends IPackageManager.Stub { 304 static final String TAG = "PackageManager"; 305 static final boolean DEBUG_SETTINGS = false; 306 static final boolean DEBUG_PREFERRED = false; 307 static final boolean DEBUG_UPGRADE = false; 308 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 309 private static final boolean DEBUG_BACKUP = false; 310 private static final boolean DEBUG_INSTALL = false; 311 private static final boolean DEBUG_REMOVE = false; 312 private static final boolean DEBUG_BROADCASTS = false; 313 private static final boolean DEBUG_SHOW_INFO = false; 314 private static final boolean DEBUG_PACKAGE_INFO = false; 315 private static final boolean DEBUG_INTENT_MATCHING = false; 316 private static final boolean DEBUG_PACKAGE_SCANNING = false; 317 private static final boolean DEBUG_VERIFY = false; 318 319 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 320 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 321 // user, but by default initialize to this. 322 static final boolean DEBUG_DEXOPT = false; 323 324 private static final boolean DEBUG_ABI_SELECTION = false; 325 private static final boolean DEBUG_EPHEMERAL = false; 326 private static final boolean DEBUG_TRIAGED_MISSING = false; 327 private static final boolean DEBUG_APP_DATA = false; 328 329 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 330 331 private static final boolean DISABLE_EPHEMERAL_APPS = true; 332 333 private static final int RADIO_UID = Process.PHONE_UID; 334 private static final int LOG_UID = Process.LOG_UID; 335 private static final int NFC_UID = Process.NFC_UID; 336 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 337 private static final int SHELL_UID = Process.SHELL_UID; 338 339 // Cap the size of permission trees that 3rd party apps can define 340 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 341 342 // Suffix used during package installation when copying/moving 343 // package apks to install directory. 344 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 345 346 static final int SCAN_NO_DEX = 1<<1; 347 static final int SCAN_FORCE_DEX = 1<<2; 348 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 349 static final int SCAN_NEW_INSTALL = 1<<4; 350 static final int SCAN_NO_PATHS = 1<<5; 351 static final int SCAN_UPDATE_TIME = 1<<6; 352 static final int SCAN_DEFER_DEX = 1<<7; 353 static final int SCAN_BOOTING = 1<<8; 354 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 355 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 356 static final int SCAN_REPLACING = 1<<11; 357 static final int SCAN_REQUIRE_KNOWN = 1<<12; 358 static final int SCAN_MOVE = 1<<13; 359 static final int SCAN_INITIAL = 1<<14; 360 361 static final int REMOVE_CHATTY = 1<<16; 362 363 private static final int[] EMPTY_INT_ARRAY = new int[0]; 364 365 /** 366 * Timeout (in milliseconds) after which the watchdog should declare that 367 * our handler thread is wedged. The usual default for such things is one 368 * minute but we sometimes do very lengthy I/O operations on this thread, 369 * such as installing multi-gigabyte applications, so ours needs to be longer. 370 */ 371 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 372 373 /** 374 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 375 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 376 * settings entry if available, otherwise we use the hardcoded default. If it's been 377 * more than this long since the last fstrim, we force one during the boot sequence. 378 * 379 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 380 * one gets run at the next available charging+idle time. This final mandatory 381 * no-fstrim check kicks in only of the other scheduling criteria is never met. 382 */ 383 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 384 385 /** 386 * Whether verification is enabled by default. 387 */ 388 private static final boolean DEFAULT_VERIFY_ENABLE = true; 389 390 /** 391 * The default maximum time to wait for the verification agent to return in 392 * milliseconds. 393 */ 394 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 395 396 /** 397 * The default response for package verification timeout. 398 * 399 * This can be either PackageManager.VERIFICATION_ALLOW or 400 * PackageManager.VERIFICATION_REJECT. 401 */ 402 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 403 404 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 405 406 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 407 DEFAULT_CONTAINER_PACKAGE, 408 "com.android.defcontainer.DefaultContainerService"); 409 410 private static final String KILL_APP_REASON_GIDS_CHANGED = 411 "permission grant or revoke changed gids"; 412 413 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 414 "permissions revoked"; 415 416 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 417 418 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 419 420 /** Permission grant: not grant the permission. */ 421 private static final int GRANT_DENIED = 1; 422 423 /** Permission grant: grant the permission as an install permission. */ 424 private static final int GRANT_INSTALL = 2; 425 426 /** Permission grant: grant the permission as a runtime one. */ 427 private static final int GRANT_RUNTIME = 3; 428 429 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 430 private static final int GRANT_UPGRADE = 4; 431 432 /** Canonical intent used to identify what counts as a "web browser" app */ 433 private static final Intent sBrowserIntent; 434 static { 435 sBrowserIntent = new Intent(); 436 sBrowserIntent.setAction(Intent.ACTION_VIEW); 437 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 438 sBrowserIntent.setData(Uri.parse("http:")); 439 } 440 441 final ServiceThread mHandlerThread; 442 443 final PackageHandler mHandler; 444 445 /** 446 * Messages for {@link #mHandler} that need to wait for system ready before 447 * being dispatched. 448 */ 449 private ArrayList<Message> mPostSystemReadyMessages; 450 451 final int mSdkVersion = Build.VERSION.SDK_INT; 452 453 final Context mContext; 454 final boolean mFactoryTest; 455 final boolean mOnlyCore; 456 final DisplayMetrics mMetrics; 457 final int mDefParseFlags; 458 final String[] mSeparateProcesses; 459 final boolean mIsUpgrade; 460 461 /** The location for ASEC container files on internal storage. */ 462 final String mAsecInternalPath; 463 464 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 465 // LOCK HELD. Can be called with mInstallLock held. 466 @GuardedBy("mInstallLock") 467 final Installer mInstaller; 468 469 /** Directory where installed third-party apps stored */ 470 final File mAppInstallDir; 471 final File mEphemeralInstallDir; 472 473 /** 474 * Directory to which applications installed internally have their 475 * 32 bit native libraries copied. 476 */ 477 private File mAppLib32InstallDir; 478 479 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 480 // apps. 481 final File mDrmAppPrivateInstallDir; 482 483 // ---------------------------------------------------------------- 484 485 // Lock for state used when installing and doing other long running 486 // operations. Methods that must be called with this lock held have 487 // the suffix "LI". 488 final Object mInstallLock = new Object(); 489 490 // ---------------------------------------------------------------- 491 492 // Keys are String (package name), values are Package. This also serves 493 // as the lock for the global state. Methods that must be called with 494 // this lock held have the prefix "LP". 495 @GuardedBy("mPackages") 496 final ArrayMap<String, PackageParser.Package> mPackages = 497 new ArrayMap<String, PackageParser.Package>(); 498 499 // Tracks available target package names -> overlay package paths. 500 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 501 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 502 503 /** 504 * Tracks new system packages [received in an OTA] that we expect to 505 * find updated user-installed versions. Keys are package name, values 506 * are package location. 507 */ 508 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 509 510 /** 511 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 512 */ 513 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 514 /** 515 * Whether or not system app permissions should be promoted from install to runtime. 516 */ 517 boolean mPromoteSystemApps; 518 519 final Settings mSettings; 520 boolean mRestoredSettings; 521 522 // System configuration read by SystemConfig. 523 final int[] mGlobalGids; 524 final SparseArray<ArraySet<String>> mSystemPermissions; 525 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 526 527 // If mac_permissions.xml was found for seinfo labeling. 528 boolean mFoundPolicyFile; 529 530 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 531 532 public static final class SharedLibraryEntry { 533 public final String path; 534 public final String apk; 535 536 SharedLibraryEntry(String _path, String _apk) { 537 path = _path; 538 apk = _apk; 539 } 540 } 541 542 // Currently known shared libraries. 543 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 544 new ArrayMap<String, SharedLibraryEntry>(); 545 546 // All available activities, for your resolving pleasure. 547 final ActivityIntentResolver mActivities = 548 new ActivityIntentResolver(); 549 550 // All available receivers, for your resolving pleasure. 551 final ActivityIntentResolver mReceivers = 552 new ActivityIntentResolver(); 553 554 // All available services, for your resolving pleasure. 555 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 556 557 // All available providers, for your resolving pleasure. 558 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 559 560 // Mapping from provider base names (first directory in content URI codePath) 561 // to the provider information. 562 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 563 new ArrayMap<String, PackageParser.Provider>(); 564 565 // Mapping from instrumentation class names to info about them. 566 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 567 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 568 569 // Mapping from permission names to info about them. 570 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 571 new ArrayMap<String, PackageParser.PermissionGroup>(); 572 573 // Packages whose data we have transfered into another package, thus 574 // should no longer exist. 575 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 576 577 // Broadcast actions that are only available to the system. 578 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 579 580 /** List of packages waiting for verification. */ 581 final SparseArray<PackageVerificationState> mPendingVerification 582 = new SparseArray<PackageVerificationState>(); 583 584 /** Set of packages associated with each app op permission. */ 585 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 586 587 final PackageInstallerService mInstallerService; 588 589 private final PackageDexOptimizer mPackageDexOptimizer; 590 591 private AtomicInteger mNextMoveId = new AtomicInteger(); 592 private final MoveCallbacks mMoveCallbacks; 593 594 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 595 596 // Cache of users who need badging. 597 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 598 599 /** Token for keys in mPendingVerification. */ 600 private int mPendingVerificationToken = 0; 601 602 volatile boolean mSystemReady; 603 volatile boolean mSafeMode; 604 volatile boolean mHasSystemUidErrors; 605 606 ApplicationInfo mAndroidApplication; 607 final ActivityInfo mResolveActivity = new ActivityInfo(); 608 final ResolveInfo mResolveInfo = new ResolveInfo(); 609 ComponentName mResolveComponentName; 610 PackageParser.Package mPlatformPackage; 611 ComponentName mCustomResolverComponentName; 612 613 boolean mResolverReplaced = false; 614 615 private final @Nullable ComponentName mIntentFilterVerifierComponent; 616 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 617 618 private int mIntentFilterVerificationToken = 0; 619 620 /** Component that knows whether or not an ephemeral application exists */ 621 final ComponentName mEphemeralResolverComponent; 622 /** The service connection to the ephemeral resolver */ 623 final EphemeralResolverConnection mEphemeralResolverConnection; 624 625 /** Component used to install ephemeral applications */ 626 final ComponentName mEphemeralInstallerComponent; 627 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 628 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 629 630 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 631 = new SparseArray<IntentFilterVerificationState>(); 632 633 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 634 new DefaultPermissionGrantPolicy(this); 635 636 // List of packages names to keep cached, even if they are uninstalled for all users 637 private List<String> mKeepUninstalledPackages; 638 639 private boolean mUseJitProfiles = 640 SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false); 641 642 private static class IFVerificationParams { 643 PackageParser.Package pkg; 644 boolean replacing; 645 int userId; 646 int verifierUid; 647 648 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 649 int _userId, int _verifierUid) { 650 pkg = _pkg; 651 replacing = _replacing; 652 userId = _userId; 653 replacing = _replacing; 654 verifierUid = _verifierUid; 655 } 656 } 657 658 private interface IntentFilterVerifier<T extends IntentFilter> { 659 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 660 T filter, String packageName); 661 void startVerifications(int userId); 662 void receiveVerificationResponse(int verificationId); 663 } 664 665 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 666 private Context mContext; 667 private ComponentName mIntentFilterVerifierComponent; 668 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 669 670 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 671 mContext = context; 672 mIntentFilterVerifierComponent = verifierComponent; 673 } 674 675 private String getDefaultScheme() { 676 return IntentFilter.SCHEME_HTTPS; 677 } 678 679 @Override 680 public void startVerifications(int userId) { 681 // Launch verifications requests 682 int count = mCurrentIntentFilterVerifications.size(); 683 for (int n=0; n<count; n++) { 684 int verificationId = mCurrentIntentFilterVerifications.get(n); 685 final IntentFilterVerificationState ivs = 686 mIntentFilterVerificationStates.get(verificationId); 687 688 String packageName = ivs.getPackageName(); 689 690 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 691 final int filterCount = filters.size(); 692 ArraySet<String> domainsSet = new ArraySet<>(); 693 for (int m=0; m<filterCount; m++) { 694 PackageParser.ActivityIntentInfo filter = filters.get(m); 695 domainsSet.addAll(filter.getHostsList()); 696 } 697 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 698 synchronized (mPackages) { 699 if (mSettings.createIntentFilterVerificationIfNeededLPw( 700 packageName, domainsList) != null) { 701 scheduleWriteSettingsLocked(); 702 } 703 } 704 sendVerificationRequest(userId, verificationId, ivs); 705 } 706 mCurrentIntentFilterVerifications.clear(); 707 } 708 709 private void sendVerificationRequest(int userId, int verificationId, 710 IntentFilterVerificationState ivs) { 711 712 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 713 verificationIntent.putExtra( 714 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 715 verificationId); 716 verificationIntent.putExtra( 717 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 718 getDefaultScheme()); 719 verificationIntent.putExtra( 720 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 721 ivs.getHostsString()); 722 verificationIntent.putExtra( 723 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 724 ivs.getPackageName()); 725 verificationIntent.setComponent(mIntentFilterVerifierComponent); 726 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 727 728 UserHandle user = new UserHandle(userId); 729 mContext.sendBroadcastAsUser(verificationIntent, user); 730 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 731 "Sending IntentFilter verification broadcast"); 732 } 733 734 public void receiveVerificationResponse(int verificationId) { 735 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 736 737 final boolean verified = ivs.isVerified(); 738 739 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 740 final int count = filters.size(); 741 if (DEBUG_DOMAIN_VERIFICATION) { 742 Slog.i(TAG, "Received verification response " + verificationId 743 + " for " + count + " filters, verified=" + verified); 744 } 745 for (int n=0; n<count; n++) { 746 PackageParser.ActivityIntentInfo filter = filters.get(n); 747 filter.setVerified(verified); 748 749 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 750 + " verified with result:" + verified + " and hosts:" 751 + ivs.getHostsString()); 752 } 753 754 mIntentFilterVerificationStates.remove(verificationId); 755 756 final String packageName = ivs.getPackageName(); 757 IntentFilterVerificationInfo ivi = null; 758 759 synchronized (mPackages) { 760 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 761 } 762 if (ivi == null) { 763 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 764 + verificationId + " packageName:" + packageName); 765 return; 766 } 767 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 768 "Updating IntentFilterVerificationInfo for package " + packageName 769 +" verificationId:" + verificationId); 770 771 synchronized (mPackages) { 772 if (verified) { 773 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 774 } else { 775 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 776 } 777 scheduleWriteSettingsLocked(); 778 779 final int userId = ivs.getUserId(); 780 if (userId != UserHandle.USER_ALL) { 781 final int userStatus = 782 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 783 784 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 785 boolean needUpdate = false; 786 787 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 788 // already been set by the User thru the Disambiguation dialog 789 switch (userStatus) { 790 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 791 if (verified) { 792 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 793 } else { 794 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 795 } 796 needUpdate = true; 797 break; 798 799 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 800 if (verified) { 801 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 802 needUpdate = true; 803 } 804 break; 805 806 default: 807 // Nothing to do 808 } 809 810 if (needUpdate) { 811 mSettings.updateIntentFilterVerificationStatusLPw( 812 packageName, updatedStatus, userId); 813 scheduleWritePackageRestrictionsLocked(userId); 814 } 815 } 816 } 817 } 818 819 @Override 820 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 821 ActivityIntentInfo filter, String packageName) { 822 if (!hasValidDomains(filter)) { 823 return false; 824 } 825 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 826 if (ivs == null) { 827 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 828 packageName); 829 } 830 if (DEBUG_DOMAIN_VERIFICATION) { 831 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 832 } 833 ivs.addFilter(filter); 834 return true; 835 } 836 837 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 838 int userId, int verificationId, String packageName) { 839 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 840 verifierUid, userId, packageName); 841 ivs.setPendingState(); 842 synchronized (mPackages) { 843 mIntentFilterVerificationStates.append(verificationId, ivs); 844 mCurrentIntentFilterVerifications.add(verificationId); 845 } 846 return ivs; 847 } 848 } 849 850 private static boolean hasValidDomains(ActivityIntentInfo filter) { 851 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 852 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 853 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 854 } 855 856 // Set of pending broadcasts for aggregating enable/disable of components. 857 static class PendingPackageBroadcasts { 858 // for each user id, a map of <package name -> components within that package> 859 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 860 861 public PendingPackageBroadcasts() { 862 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 863 } 864 865 public ArrayList<String> get(int userId, String packageName) { 866 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 867 return packages.get(packageName); 868 } 869 870 public void put(int userId, String packageName, ArrayList<String> components) { 871 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 872 packages.put(packageName, components); 873 } 874 875 public void remove(int userId, String packageName) { 876 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 877 if (packages != null) { 878 packages.remove(packageName); 879 } 880 } 881 882 public void remove(int userId) { 883 mUidMap.remove(userId); 884 } 885 886 public int userIdCount() { 887 return mUidMap.size(); 888 } 889 890 public int userIdAt(int n) { 891 return mUidMap.keyAt(n); 892 } 893 894 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 895 return mUidMap.get(userId); 896 } 897 898 public int size() { 899 // total number of pending broadcast entries across all userIds 900 int num = 0; 901 for (int i = 0; i< mUidMap.size(); i++) { 902 num += mUidMap.valueAt(i).size(); 903 } 904 return num; 905 } 906 907 public void clear() { 908 mUidMap.clear(); 909 } 910 911 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 912 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 913 if (map == null) { 914 map = new ArrayMap<String, ArrayList<String>>(); 915 mUidMap.put(userId, map); 916 } 917 return map; 918 } 919 } 920 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 921 922 // Service Connection to remote media container service to copy 923 // package uri's from external media onto secure containers 924 // or internal storage. 925 private IMediaContainerService mContainerService = null; 926 927 static final int SEND_PENDING_BROADCAST = 1; 928 static final int MCS_BOUND = 3; 929 static final int END_COPY = 4; 930 static final int INIT_COPY = 5; 931 static final int MCS_UNBIND = 6; 932 static final int START_CLEANING_PACKAGE = 7; 933 static final int FIND_INSTALL_LOC = 8; 934 static final int POST_INSTALL = 9; 935 static final int MCS_RECONNECT = 10; 936 static final int MCS_GIVE_UP = 11; 937 static final int UPDATED_MEDIA_STATUS = 12; 938 static final int WRITE_SETTINGS = 13; 939 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 940 static final int PACKAGE_VERIFIED = 15; 941 static final int CHECK_PENDING_VERIFICATION = 16; 942 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 943 static final int INTENT_FILTER_VERIFIED = 18; 944 945 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 946 947 // Delay time in millisecs 948 static final int BROADCAST_DELAY = 10 * 1000; 949 950 static UserManagerService sUserManager; 951 952 // Stores a list of users whose package restrictions file needs to be updated 953 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 954 955 final private DefaultContainerConnection mDefContainerConn = 956 new DefaultContainerConnection(); 957 class DefaultContainerConnection implements ServiceConnection { 958 public void onServiceConnected(ComponentName name, IBinder service) { 959 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 960 IMediaContainerService imcs = 961 IMediaContainerService.Stub.asInterface(service); 962 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 963 } 964 965 public void onServiceDisconnected(ComponentName name) { 966 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 967 } 968 } 969 970 // Recordkeeping of restore-after-install operations that are currently in flight 971 // between the Package Manager and the Backup Manager 972 static class PostInstallData { 973 public InstallArgs args; 974 public PackageInstalledInfo res; 975 976 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 977 args = _a; 978 res = _r; 979 } 980 } 981 982 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 983 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 984 985 // XML tags for backup/restore of various bits of state 986 private static final String TAG_PREFERRED_BACKUP = "pa"; 987 private static final String TAG_DEFAULT_APPS = "da"; 988 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 989 990 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 991 private static final String TAG_ALL_GRANTS = "rt-grants"; 992 private static final String TAG_GRANT = "grant"; 993 private static final String ATTR_PACKAGE_NAME = "pkg"; 994 995 private static final String TAG_PERMISSION = "perm"; 996 private static final String ATTR_PERMISSION_NAME = "name"; 997 private static final String ATTR_IS_GRANTED = "g"; 998 private static final String ATTR_USER_SET = "set"; 999 private static final String ATTR_USER_FIXED = "fixed"; 1000 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1001 1002 // System/policy permission grants are not backed up 1003 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1004 FLAG_PERMISSION_POLICY_FIXED 1005 | FLAG_PERMISSION_SYSTEM_FIXED 1006 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1007 1008 // And we back up these user-adjusted states 1009 private static final int USER_RUNTIME_GRANT_MASK = 1010 FLAG_PERMISSION_USER_SET 1011 | FLAG_PERMISSION_USER_FIXED 1012 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1013 1014 final @Nullable String mRequiredVerifierPackage; 1015 final @Nullable String mRequiredInstallerPackage; 1016 1017 private final PackageUsage mPackageUsage = new PackageUsage(); 1018 1019 private class PackageUsage { 1020 private static final int WRITE_INTERVAL 1021 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1022 1023 private final Object mFileLock = new Object(); 1024 private final AtomicLong mLastWritten = new AtomicLong(0); 1025 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1026 1027 private boolean mIsHistoricalPackageUsageAvailable = true; 1028 1029 boolean isHistoricalPackageUsageAvailable() { 1030 return mIsHistoricalPackageUsageAvailable; 1031 } 1032 1033 void write(boolean force) { 1034 if (force) { 1035 writeInternal(); 1036 return; 1037 } 1038 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1039 && !DEBUG_DEXOPT) { 1040 return; 1041 } 1042 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1043 new Thread("PackageUsage_DiskWriter") { 1044 @Override 1045 public void run() { 1046 try { 1047 writeInternal(); 1048 } finally { 1049 mBackgroundWriteRunning.set(false); 1050 } 1051 } 1052 }.start(); 1053 } 1054 } 1055 1056 private void writeInternal() { 1057 synchronized (mPackages) { 1058 synchronized (mFileLock) { 1059 AtomicFile file = getFile(); 1060 FileOutputStream f = null; 1061 try { 1062 f = file.startWrite(); 1063 BufferedOutputStream out = new BufferedOutputStream(f); 1064 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1065 StringBuilder sb = new StringBuilder(); 1066 for (PackageParser.Package pkg : mPackages.values()) { 1067 if (pkg.mLastPackageUsageTimeInMills == 0) { 1068 continue; 1069 } 1070 sb.setLength(0); 1071 sb.append(pkg.packageName); 1072 sb.append(' '); 1073 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1074 sb.append('\n'); 1075 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1076 } 1077 out.flush(); 1078 file.finishWrite(f); 1079 } catch (IOException e) { 1080 if (f != null) { 1081 file.failWrite(f); 1082 } 1083 Log.e(TAG, "Failed to write package usage times", e); 1084 } 1085 } 1086 } 1087 mLastWritten.set(SystemClock.elapsedRealtime()); 1088 } 1089 1090 void readLP() { 1091 synchronized (mFileLock) { 1092 AtomicFile file = getFile(); 1093 BufferedInputStream in = null; 1094 try { 1095 in = new BufferedInputStream(file.openRead()); 1096 StringBuffer sb = new StringBuffer(); 1097 while (true) { 1098 String packageName = readToken(in, sb, ' '); 1099 if (packageName == null) { 1100 break; 1101 } 1102 String timeInMillisString = readToken(in, sb, '\n'); 1103 if (timeInMillisString == null) { 1104 throw new IOException("Failed to find last usage time for package " 1105 + packageName); 1106 } 1107 PackageParser.Package pkg = mPackages.get(packageName); 1108 if (pkg == null) { 1109 continue; 1110 } 1111 long timeInMillis; 1112 try { 1113 timeInMillis = Long.parseLong(timeInMillisString); 1114 } catch (NumberFormatException e) { 1115 throw new IOException("Failed to parse " + timeInMillisString 1116 + " as a long.", e); 1117 } 1118 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1119 } 1120 } catch (FileNotFoundException expected) { 1121 mIsHistoricalPackageUsageAvailable = false; 1122 } catch (IOException e) { 1123 Log.w(TAG, "Failed to read package usage times", e); 1124 } finally { 1125 IoUtils.closeQuietly(in); 1126 } 1127 } 1128 mLastWritten.set(SystemClock.elapsedRealtime()); 1129 } 1130 1131 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1132 throws IOException { 1133 sb.setLength(0); 1134 while (true) { 1135 int ch = in.read(); 1136 if (ch == -1) { 1137 if (sb.length() == 0) { 1138 return null; 1139 } 1140 throw new IOException("Unexpected EOF"); 1141 } 1142 if (ch == endOfToken) { 1143 return sb.toString(); 1144 } 1145 sb.append((char)ch); 1146 } 1147 } 1148 1149 private AtomicFile getFile() { 1150 File dataDir = Environment.getDataDirectory(); 1151 File systemDir = new File(dataDir, "system"); 1152 File fname = new File(systemDir, "package-usage.list"); 1153 return new AtomicFile(fname); 1154 } 1155 } 1156 1157 class PackageHandler extends Handler { 1158 private boolean mBound = false; 1159 final ArrayList<HandlerParams> mPendingInstalls = 1160 new ArrayList<HandlerParams>(); 1161 1162 private boolean connectToService() { 1163 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1164 " DefaultContainerService"); 1165 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1166 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1167 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1168 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1169 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1170 mBound = true; 1171 return true; 1172 } 1173 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1174 return false; 1175 } 1176 1177 private void disconnectService() { 1178 mContainerService = null; 1179 mBound = false; 1180 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1181 mContext.unbindService(mDefContainerConn); 1182 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1183 } 1184 1185 PackageHandler(Looper looper) { 1186 super(looper); 1187 } 1188 1189 public void handleMessage(Message msg) { 1190 try { 1191 doHandleMessage(msg); 1192 } finally { 1193 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1194 } 1195 } 1196 1197 void doHandleMessage(Message msg) { 1198 switch (msg.what) { 1199 case INIT_COPY: { 1200 HandlerParams params = (HandlerParams) msg.obj; 1201 int idx = mPendingInstalls.size(); 1202 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1203 // If a bind was already initiated we dont really 1204 // need to do anything. The pending install 1205 // will be processed later on. 1206 if (!mBound) { 1207 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1208 System.identityHashCode(mHandler)); 1209 // If this is the only one pending we might 1210 // have to bind to the service again. 1211 if (!connectToService()) { 1212 Slog.e(TAG, "Failed to bind to media container service"); 1213 params.serviceError(); 1214 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1215 System.identityHashCode(mHandler)); 1216 if (params.traceMethod != null) { 1217 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1218 params.traceCookie); 1219 } 1220 return; 1221 } else { 1222 // Once we bind to the service, the first 1223 // pending request will be processed. 1224 mPendingInstalls.add(idx, params); 1225 } 1226 } else { 1227 mPendingInstalls.add(idx, params); 1228 // Already bound to the service. Just make 1229 // sure we trigger off processing the first request. 1230 if (idx == 0) { 1231 mHandler.sendEmptyMessage(MCS_BOUND); 1232 } 1233 } 1234 break; 1235 } 1236 case MCS_BOUND: { 1237 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1238 if (msg.obj != null) { 1239 mContainerService = (IMediaContainerService) msg.obj; 1240 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1241 System.identityHashCode(mHandler)); 1242 } 1243 if (mContainerService == null) { 1244 if (!mBound) { 1245 // Something seriously wrong since we are not bound and we are not 1246 // waiting for connection. Bail out. 1247 Slog.e(TAG, "Cannot bind to media container service"); 1248 for (HandlerParams params : mPendingInstalls) { 1249 // Indicate service bind error 1250 params.serviceError(); 1251 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1252 System.identityHashCode(params)); 1253 if (params.traceMethod != null) { 1254 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1255 params.traceMethod, params.traceCookie); 1256 } 1257 return; 1258 } 1259 mPendingInstalls.clear(); 1260 } else { 1261 Slog.w(TAG, "Waiting to connect to media container service"); 1262 } 1263 } else if (mPendingInstalls.size() > 0) { 1264 HandlerParams params = mPendingInstalls.get(0); 1265 if (params != null) { 1266 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1267 System.identityHashCode(params)); 1268 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1269 if (params.startCopy()) { 1270 // We are done... look for more work or to 1271 // go idle. 1272 if (DEBUG_SD_INSTALL) Log.i(TAG, 1273 "Checking for more work or unbind..."); 1274 // Delete pending install 1275 if (mPendingInstalls.size() > 0) { 1276 mPendingInstalls.remove(0); 1277 } 1278 if (mPendingInstalls.size() == 0) { 1279 if (mBound) { 1280 if (DEBUG_SD_INSTALL) Log.i(TAG, 1281 "Posting delayed MCS_UNBIND"); 1282 removeMessages(MCS_UNBIND); 1283 Message ubmsg = obtainMessage(MCS_UNBIND); 1284 // Unbind after a little delay, to avoid 1285 // continual thrashing. 1286 sendMessageDelayed(ubmsg, 10000); 1287 } 1288 } else { 1289 // There are more pending requests in queue. 1290 // Just post MCS_BOUND message to trigger processing 1291 // of next pending install. 1292 if (DEBUG_SD_INSTALL) Log.i(TAG, 1293 "Posting MCS_BOUND for next work"); 1294 mHandler.sendEmptyMessage(MCS_BOUND); 1295 } 1296 } 1297 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1298 } 1299 } else { 1300 // Should never happen ideally. 1301 Slog.w(TAG, "Empty queue"); 1302 } 1303 break; 1304 } 1305 case MCS_RECONNECT: { 1306 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1307 if (mPendingInstalls.size() > 0) { 1308 if (mBound) { 1309 disconnectService(); 1310 } 1311 if (!connectToService()) { 1312 Slog.e(TAG, "Failed to bind to media container service"); 1313 for (HandlerParams params : mPendingInstalls) { 1314 // Indicate service bind error 1315 params.serviceError(); 1316 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1317 System.identityHashCode(params)); 1318 } 1319 mPendingInstalls.clear(); 1320 } 1321 } 1322 break; 1323 } 1324 case MCS_UNBIND: { 1325 // If there is no actual work left, then time to unbind. 1326 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1327 1328 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1329 if (mBound) { 1330 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1331 1332 disconnectService(); 1333 } 1334 } else if (mPendingInstalls.size() > 0) { 1335 // There are more pending requests in queue. 1336 // Just post MCS_BOUND message to trigger processing 1337 // of next pending install. 1338 mHandler.sendEmptyMessage(MCS_BOUND); 1339 } 1340 1341 break; 1342 } 1343 case MCS_GIVE_UP: { 1344 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1345 HandlerParams params = mPendingInstalls.remove(0); 1346 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1347 System.identityHashCode(params)); 1348 break; 1349 } 1350 case SEND_PENDING_BROADCAST: { 1351 String packages[]; 1352 ArrayList<String> components[]; 1353 int size = 0; 1354 int uids[]; 1355 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1356 synchronized (mPackages) { 1357 if (mPendingBroadcasts == null) { 1358 return; 1359 } 1360 size = mPendingBroadcasts.size(); 1361 if (size <= 0) { 1362 // Nothing to be done. Just return 1363 return; 1364 } 1365 packages = new String[size]; 1366 components = new ArrayList[size]; 1367 uids = new int[size]; 1368 int i = 0; // filling out the above arrays 1369 1370 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1371 int packageUserId = mPendingBroadcasts.userIdAt(n); 1372 Iterator<Map.Entry<String, ArrayList<String>>> it 1373 = mPendingBroadcasts.packagesForUserId(packageUserId) 1374 .entrySet().iterator(); 1375 while (it.hasNext() && i < size) { 1376 Map.Entry<String, ArrayList<String>> ent = it.next(); 1377 packages[i] = ent.getKey(); 1378 components[i] = ent.getValue(); 1379 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1380 uids[i] = (ps != null) 1381 ? UserHandle.getUid(packageUserId, ps.appId) 1382 : -1; 1383 i++; 1384 } 1385 } 1386 size = i; 1387 mPendingBroadcasts.clear(); 1388 } 1389 // Send broadcasts 1390 for (int i = 0; i < size; i++) { 1391 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1392 } 1393 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1394 break; 1395 } 1396 case START_CLEANING_PACKAGE: { 1397 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1398 final String packageName = (String)msg.obj; 1399 final int userId = msg.arg1; 1400 final boolean andCode = msg.arg2 != 0; 1401 synchronized (mPackages) { 1402 if (userId == UserHandle.USER_ALL) { 1403 int[] users = sUserManager.getUserIds(); 1404 for (int user : users) { 1405 mSettings.addPackageToCleanLPw( 1406 new PackageCleanItem(user, packageName, andCode)); 1407 } 1408 } else { 1409 mSettings.addPackageToCleanLPw( 1410 new PackageCleanItem(userId, packageName, andCode)); 1411 } 1412 } 1413 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1414 startCleaningPackages(); 1415 } break; 1416 case POST_INSTALL: { 1417 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1418 1419 PostInstallData data = mRunningInstalls.get(msg.arg1); 1420 mRunningInstalls.delete(msg.arg1); 1421 boolean deleteOld = false; 1422 1423 if (data != null) { 1424 InstallArgs args = data.args; 1425 PackageInstalledInfo res = data.res; 1426 1427 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1428 final String packageName = res.pkg.applicationInfo.packageName; 1429 res.removedInfo.sendBroadcast(false, true, false); 1430 Bundle extras = new Bundle(1); 1431 extras.putInt(Intent.EXTRA_UID, res.uid); 1432 1433 // Now that we successfully installed the package, grant runtime 1434 // permissions if requested before broadcasting the install. 1435 if ((args.installFlags 1436 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 1437 && res.pkg.applicationInfo.targetSdkVersion 1438 >= Build.VERSION_CODES.M) { 1439 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1440 args.installGrantPermissions); 1441 } 1442 1443 synchronized (mPackages) { 1444 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1445 } 1446 1447 // Determine the set of users who are adding this 1448 // package for the first time vs. those who are seeing 1449 // an update. 1450 int[] firstUsers; 1451 int[] updateUsers = new int[0]; 1452 if (res.origUsers == null || res.origUsers.length == 0) { 1453 firstUsers = res.newUsers; 1454 } else { 1455 firstUsers = new int[0]; 1456 for (int i=0; i<res.newUsers.length; i++) { 1457 int user = res.newUsers[i]; 1458 boolean isNew = true; 1459 for (int j=0; j<res.origUsers.length; j++) { 1460 if (res.origUsers[j] == user) { 1461 isNew = false; 1462 break; 1463 } 1464 } 1465 if (isNew) { 1466 int[] newFirst = new int[firstUsers.length+1]; 1467 System.arraycopy(firstUsers, 0, newFirst, 0, 1468 firstUsers.length); 1469 newFirst[firstUsers.length] = user; 1470 firstUsers = newFirst; 1471 } else { 1472 int[] newUpdate = new int[updateUsers.length+1]; 1473 System.arraycopy(updateUsers, 0, newUpdate, 0, 1474 updateUsers.length); 1475 newUpdate[updateUsers.length] = user; 1476 updateUsers = newUpdate; 1477 } 1478 } 1479 } 1480 // don't broadcast for ephemeral installs/updates 1481 final boolean isEphemeral = isEphemeral(res.pkg); 1482 if (!isEphemeral) { 1483 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1484 extras, 0 /*flags*/, null /*targetPackage*/, 1485 null /*finishedReceiver*/, firstUsers); 1486 } 1487 final boolean update = res.removedInfo.removedPackage != null; 1488 if (update) { 1489 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1490 } 1491 if (!isEphemeral) { 1492 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1493 extras, 0 /*flags*/, null /*targetPackage*/, 1494 null /*finishedReceiver*/, updateUsers); 1495 } 1496 if (update) { 1497 if (!isEphemeral) { 1498 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1499 packageName, extras, 0 /*flags*/, 1500 null /*targetPackage*/, null /*finishedReceiver*/, 1501 updateUsers); 1502 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1503 null /*package*/, null /*extras*/, 0 /*flags*/, 1504 packageName /*targetPackage*/, 1505 null /*finishedReceiver*/, updateUsers); 1506 } 1507 1508 // treat asec-hosted packages like removable media on upgrade 1509 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1510 if (DEBUG_INSTALL) { 1511 Slog.i(TAG, "upgrading pkg " + res.pkg 1512 + " is ASEC-hosted -> AVAILABLE"); 1513 } 1514 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1515 ArrayList<String> pkgList = new ArrayList<String>(1); 1516 pkgList.add(packageName); 1517 sendResourcesChangedBroadcast(true, true, 1518 pkgList,uidArray, null); 1519 } 1520 } 1521 if (res.removedInfo.args != null) { 1522 // Remove the replaced package's older resources safely now 1523 deleteOld = true; 1524 } 1525 1526 1527 // Work that needs to happen on first install within each user 1528 if (firstUsers.length > 0) { 1529 for (int userId : firstUsers) { 1530 synchronized (mPackages) { 1531 // If this app is a browser and it's newly-installed for 1532 // some users, clear any default-browser state in those 1533 // users. The app's nature doesn't depend on the user, 1534 // so we can just check its browser nature in any user 1535 // and generalize. 1536 if (packageIsBrowser(packageName, firstUsers[0])) { 1537 mSettings.setDefaultBrowserPackageNameLPw( 1538 null, userId); 1539 } 1540 1541 // We may also need to apply pending (restored) runtime 1542 // permission grants within these users. 1543 mSettings.applyPendingPermissionGrantsLPw( 1544 packageName, userId); 1545 } 1546 } 1547 } 1548 // Log current value of "unknown sources" setting 1549 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1550 getUnknownSourcesSettings()); 1551 } 1552 // Force a gc to clear up things 1553 Runtime.getRuntime().gc(); 1554 // We delete after a gc for applications on sdcard. 1555 if (deleteOld) { 1556 synchronized (mInstallLock) { 1557 res.removedInfo.args.doPostDeleteLI(true); 1558 } 1559 } 1560 if (args.observer != null) { 1561 try { 1562 Bundle extras = extrasForInstallResult(res); 1563 args.observer.onPackageInstalled(res.name, res.returnCode, 1564 res.returnMsg, extras); 1565 } catch (RemoteException e) { 1566 Slog.i(TAG, "Observer no longer exists."); 1567 } 1568 } 1569 if (args.traceMethod != null) { 1570 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1571 args.traceCookie); 1572 } 1573 return; 1574 } else { 1575 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1576 } 1577 1578 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1579 } break; 1580 case UPDATED_MEDIA_STATUS: { 1581 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1582 boolean reportStatus = msg.arg1 == 1; 1583 boolean doGc = msg.arg2 == 1; 1584 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1585 if (doGc) { 1586 // Force a gc to clear up stale containers. 1587 Runtime.getRuntime().gc(); 1588 } 1589 if (msg.obj != null) { 1590 @SuppressWarnings("unchecked") 1591 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1592 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1593 // Unload containers 1594 unloadAllContainers(args); 1595 } 1596 if (reportStatus) { 1597 try { 1598 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1599 PackageHelper.getMountService().finishMediaUpdate(); 1600 } catch (RemoteException e) { 1601 Log.e(TAG, "MountService not running?"); 1602 } 1603 } 1604 } break; 1605 case WRITE_SETTINGS: { 1606 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1607 synchronized (mPackages) { 1608 removeMessages(WRITE_SETTINGS); 1609 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1610 mSettings.writeLPr(); 1611 mDirtyUsers.clear(); 1612 } 1613 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1614 } break; 1615 case WRITE_PACKAGE_RESTRICTIONS: { 1616 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1617 synchronized (mPackages) { 1618 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1619 for (int userId : mDirtyUsers) { 1620 mSettings.writePackageRestrictionsLPr(userId); 1621 } 1622 mDirtyUsers.clear(); 1623 } 1624 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1625 } break; 1626 case CHECK_PENDING_VERIFICATION: { 1627 final int verificationId = msg.arg1; 1628 final PackageVerificationState state = mPendingVerification.get(verificationId); 1629 1630 if ((state != null) && !state.timeoutExtended()) { 1631 final InstallArgs args = state.getInstallArgs(); 1632 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1633 1634 Slog.i(TAG, "Verification timed out for " + originUri); 1635 mPendingVerification.remove(verificationId); 1636 1637 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1638 1639 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1640 Slog.i(TAG, "Continuing with installation of " + originUri); 1641 state.setVerifierResponse(Binder.getCallingUid(), 1642 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1643 broadcastPackageVerified(verificationId, originUri, 1644 PackageManager.VERIFICATION_ALLOW, 1645 state.getInstallArgs().getUser()); 1646 try { 1647 ret = args.copyApk(mContainerService, true); 1648 } catch (RemoteException e) { 1649 Slog.e(TAG, "Could not contact the ContainerService"); 1650 } 1651 } else { 1652 broadcastPackageVerified(verificationId, originUri, 1653 PackageManager.VERIFICATION_REJECT, 1654 state.getInstallArgs().getUser()); 1655 } 1656 1657 Trace.asyncTraceEnd( 1658 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1659 1660 processPendingInstall(args, ret); 1661 mHandler.sendEmptyMessage(MCS_UNBIND); 1662 } 1663 break; 1664 } 1665 case PACKAGE_VERIFIED: { 1666 final int verificationId = msg.arg1; 1667 1668 final PackageVerificationState state = mPendingVerification.get(verificationId); 1669 if (state == null) { 1670 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1671 break; 1672 } 1673 1674 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1675 1676 state.setVerifierResponse(response.callerUid, response.code); 1677 1678 if (state.isVerificationComplete()) { 1679 mPendingVerification.remove(verificationId); 1680 1681 final InstallArgs args = state.getInstallArgs(); 1682 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1683 1684 int ret; 1685 if (state.isInstallAllowed()) { 1686 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1687 broadcastPackageVerified(verificationId, originUri, 1688 response.code, state.getInstallArgs().getUser()); 1689 try { 1690 ret = args.copyApk(mContainerService, true); 1691 } catch (RemoteException e) { 1692 Slog.e(TAG, "Could not contact the ContainerService"); 1693 } 1694 } else { 1695 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1696 } 1697 1698 Trace.asyncTraceEnd( 1699 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1700 1701 processPendingInstall(args, ret); 1702 mHandler.sendEmptyMessage(MCS_UNBIND); 1703 } 1704 1705 break; 1706 } 1707 case START_INTENT_FILTER_VERIFICATIONS: { 1708 IFVerificationParams params = (IFVerificationParams) msg.obj; 1709 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1710 params.replacing, params.pkg); 1711 break; 1712 } 1713 case INTENT_FILTER_VERIFIED: { 1714 final int verificationId = msg.arg1; 1715 1716 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1717 verificationId); 1718 if (state == null) { 1719 Slog.w(TAG, "Invalid IntentFilter verification token " 1720 + verificationId + " received"); 1721 break; 1722 } 1723 1724 final int userId = state.getUserId(); 1725 1726 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1727 "Processing IntentFilter verification with token:" 1728 + verificationId + " and userId:" + userId); 1729 1730 final IntentFilterVerificationResponse response = 1731 (IntentFilterVerificationResponse) msg.obj; 1732 1733 state.setVerifierResponse(response.callerUid, response.code); 1734 1735 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1736 "IntentFilter verification with token:" + verificationId 1737 + " and userId:" + userId 1738 + " is settings verifier response with response code:" 1739 + response.code); 1740 1741 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1742 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1743 + response.getFailedDomainsString()); 1744 } 1745 1746 if (state.isVerificationComplete()) { 1747 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1748 } else { 1749 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1750 "IntentFilter verification with token:" + verificationId 1751 + " was not said to be complete"); 1752 } 1753 1754 break; 1755 } 1756 } 1757 } 1758 } 1759 1760 private StorageEventListener mStorageListener = new StorageEventListener() { 1761 @Override 1762 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1763 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1764 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1765 final String volumeUuid = vol.getFsUuid(); 1766 1767 // Clean up any users or apps that were removed or recreated 1768 // while this volume was missing 1769 reconcileUsers(volumeUuid); 1770 reconcileApps(volumeUuid); 1771 1772 // Clean up any install sessions that expired or were 1773 // cancelled while this volume was missing 1774 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1775 1776 loadPrivatePackages(vol); 1777 1778 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1779 unloadPrivatePackages(vol); 1780 } 1781 } 1782 1783 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1784 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1785 updateExternalMediaStatus(true, false); 1786 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1787 updateExternalMediaStatus(false, false); 1788 } 1789 } 1790 } 1791 1792 @Override 1793 public void onVolumeForgotten(String fsUuid) { 1794 if (TextUtils.isEmpty(fsUuid)) { 1795 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1796 return; 1797 } 1798 1799 // Remove any apps installed on the forgotten volume 1800 synchronized (mPackages) { 1801 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1802 for (PackageSetting ps : packages) { 1803 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1804 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1805 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1806 } 1807 1808 mSettings.onVolumeForgotten(fsUuid); 1809 mSettings.writeLPr(); 1810 } 1811 } 1812 }; 1813 1814 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1815 String[] grantedPermissions) { 1816 if (userId >= UserHandle.USER_SYSTEM) { 1817 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1818 } else if (userId == UserHandle.USER_ALL) { 1819 final int[] userIds; 1820 synchronized (mPackages) { 1821 userIds = UserManagerService.getInstance().getUserIds(); 1822 } 1823 for (int someUserId : userIds) { 1824 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1825 } 1826 } 1827 1828 // We could have touched GID membership, so flush out packages.list 1829 synchronized (mPackages) { 1830 mSettings.writePackageListLPr(); 1831 } 1832 } 1833 1834 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1835 String[] grantedPermissions) { 1836 SettingBase sb = (SettingBase) pkg.mExtras; 1837 if (sb == null) { 1838 return; 1839 } 1840 1841 PermissionsState permissionsState = sb.getPermissionsState(); 1842 1843 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1844 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1845 1846 synchronized (mPackages) { 1847 for (String permission : pkg.requestedPermissions) { 1848 BasePermission bp = mSettings.mPermissions.get(permission); 1849 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1850 && (grantedPermissions == null 1851 || ArrayUtils.contains(grantedPermissions, permission))) { 1852 final int flags = permissionsState.getPermissionFlags(permission, userId); 1853 // Installer cannot change immutable permissions. 1854 if ((flags & immutableFlags) == 0) { 1855 grantRuntimePermission(pkg.packageName, permission, userId); 1856 } 1857 } 1858 } 1859 } 1860 } 1861 1862 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1863 Bundle extras = null; 1864 switch (res.returnCode) { 1865 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1866 extras = new Bundle(); 1867 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1868 res.origPermission); 1869 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1870 res.origPackage); 1871 break; 1872 } 1873 case PackageManager.INSTALL_SUCCEEDED: { 1874 extras = new Bundle(); 1875 extras.putBoolean(Intent.EXTRA_REPLACING, 1876 res.removedInfo != null && res.removedInfo.removedPackage != null); 1877 break; 1878 } 1879 } 1880 return extras; 1881 } 1882 1883 void scheduleWriteSettingsLocked() { 1884 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1885 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1886 } 1887 } 1888 1889 void scheduleWritePackageRestrictionsLocked(int userId) { 1890 if (!sUserManager.exists(userId)) return; 1891 mDirtyUsers.add(userId); 1892 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1893 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1894 } 1895 } 1896 1897 public static PackageManagerService main(Context context, Installer installer, 1898 boolean factoryTest, boolean onlyCore) { 1899 PackageManagerService m = new PackageManagerService(context, installer, 1900 factoryTest, onlyCore); 1901 m.enableSystemUserPackages(); 1902 ServiceManager.addService("package", m); 1903 return m; 1904 } 1905 1906 private void enableSystemUserPackages() { 1907 if (!UserManager.isSplitSystemUser()) { 1908 return; 1909 } 1910 // For system user, enable apps based on the following conditions: 1911 // - app is whitelisted or belong to one of these groups: 1912 // -- system app which has no launcher icons 1913 // -- system app which has INTERACT_ACROSS_USERS permission 1914 // -- system IME app 1915 // - app is not in the blacklist 1916 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1917 Set<String> enableApps = new ArraySet<>(); 1918 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1919 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1920 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1921 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1922 enableApps.addAll(wlApps); 1923 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1924 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1925 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1926 enableApps.removeAll(blApps); 1927 Log.i(TAG, "Applications installed for system user: " + enableApps); 1928 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1929 UserHandle.SYSTEM); 1930 final int allAppsSize = allAps.size(); 1931 synchronized (mPackages) { 1932 for (int i = 0; i < allAppsSize; i++) { 1933 String pName = allAps.get(i); 1934 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1935 // Should not happen, but we shouldn't be failing if it does 1936 if (pkgSetting == null) { 1937 continue; 1938 } 1939 boolean install = enableApps.contains(pName); 1940 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 1941 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 1942 + " for system user"); 1943 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 1944 } 1945 } 1946 } 1947 } 1948 1949 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1950 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1951 Context.DISPLAY_SERVICE); 1952 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1953 } 1954 1955 public PackageManagerService(Context context, Installer installer, 1956 boolean factoryTest, boolean onlyCore) { 1957 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1958 SystemClock.uptimeMillis()); 1959 1960 if (mSdkVersion <= 0) { 1961 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1962 } 1963 1964 mContext = context; 1965 mFactoryTest = factoryTest; 1966 mOnlyCore = onlyCore; 1967 mMetrics = new DisplayMetrics(); 1968 mSettings = new Settings(mPackages); 1969 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1970 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1971 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1972 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1973 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1974 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1975 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1976 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1977 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1978 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1979 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1980 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1981 1982 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1983 if (separateProcesses != null && separateProcesses.length() > 0) { 1984 if ("*".equals(separateProcesses)) { 1985 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1986 mSeparateProcesses = null; 1987 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1988 } else { 1989 mDefParseFlags = 0; 1990 mSeparateProcesses = separateProcesses.split(","); 1991 Slog.w(TAG, "Running with debug.separate_processes: " 1992 + separateProcesses); 1993 } 1994 } else { 1995 mDefParseFlags = 0; 1996 mSeparateProcesses = null; 1997 } 1998 1999 mInstaller = installer; 2000 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2001 "*dexopt*"); 2002 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2003 2004 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2005 FgThread.get().getLooper()); 2006 2007 getDefaultDisplayMetrics(context, mMetrics); 2008 2009 SystemConfig systemConfig = SystemConfig.getInstance(); 2010 mGlobalGids = systemConfig.getGlobalGids(); 2011 mSystemPermissions = systemConfig.getSystemPermissions(); 2012 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2013 2014 synchronized (mInstallLock) { 2015 // writer 2016 synchronized (mPackages) { 2017 mHandlerThread = new ServiceThread(TAG, 2018 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2019 mHandlerThread.start(); 2020 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2021 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2022 2023 File dataDir = Environment.getDataDirectory(); 2024 mAppInstallDir = new File(dataDir, "app"); 2025 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2026 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2027 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2028 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2029 2030 sUserManager = new UserManagerService(context, this, mPackages); 2031 2032 // Propagate permission configuration in to package manager. 2033 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2034 = systemConfig.getPermissions(); 2035 for (int i=0; i<permConfig.size(); i++) { 2036 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2037 BasePermission bp = mSettings.mPermissions.get(perm.name); 2038 if (bp == null) { 2039 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2040 mSettings.mPermissions.put(perm.name, bp); 2041 } 2042 if (perm.gids != null) { 2043 bp.setGids(perm.gids, perm.perUser); 2044 } 2045 } 2046 2047 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2048 for (int i=0; i<libConfig.size(); i++) { 2049 mSharedLibraries.put(libConfig.keyAt(i), 2050 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2051 } 2052 2053 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2054 2055 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2056 2057 String customResolverActivity = Resources.getSystem().getString( 2058 R.string.config_customResolverActivity); 2059 if (TextUtils.isEmpty(customResolverActivity)) { 2060 customResolverActivity = null; 2061 } else { 2062 mCustomResolverComponentName = ComponentName.unflattenFromString( 2063 customResolverActivity); 2064 } 2065 2066 long startTime = SystemClock.uptimeMillis(); 2067 2068 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2069 startTime); 2070 2071 // Set flag to monitor and not change apk file paths when 2072 // scanning install directories. 2073 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2074 2075 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2076 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2077 2078 if (bootClassPath == null) { 2079 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2080 } 2081 2082 if (systemServerClassPath == null) { 2083 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2084 } 2085 2086 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2087 final String[] dexCodeInstructionSets = 2088 getDexCodeInstructionSets( 2089 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2090 2091 /** 2092 * Ensure all external libraries have had dexopt run on them. 2093 */ 2094 if (mSharedLibraries.size() > 0) { 2095 // NOTE: For now, we're compiling these system "shared libraries" 2096 // (and framework jars) into all available architectures. It's possible 2097 // to compile them only when we come across an app that uses them (there's 2098 // already logic for that in scanPackageLI) but that adds some complexity. 2099 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2100 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2101 final String lib = libEntry.path; 2102 if (lib == null) { 2103 continue; 2104 } 2105 2106 try { 2107 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2108 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2109 // Shared libraries do not have profiles so we perform a full 2110 // AOT compilation. 2111 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2112 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2113 StorageManager.UUID_PRIVATE_INTERNAL, 2114 false /*useProfiles*/); 2115 } 2116 } catch (FileNotFoundException e) { 2117 Slog.w(TAG, "Library not found: " + lib); 2118 } catch (IOException | InstallerException e) { 2119 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2120 + e.getMessage()); 2121 } 2122 } 2123 } 2124 } 2125 2126 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2127 2128 final VersionInfo ver = mSettings.getInternalVersion(); 2129 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2130 // when upgrading from pre-M, promote system app permissions from install to runtime 2131 mPromoteSystemApps = 2132 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2133 2134 // save off the names of pre-existing system packages prior to scanning; we don't 2135 // want to automatically grant runtime permissions for new system apps 2136 if (mPromoteSystemApps) { 2137 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2138 while (pkgSettingIter.hasNext()) { 2139 PackageSetting ps = pkgSettingIter.next(); 2140 if (isSystemApp(ps)) { 2141 mExistingSystemPackages.add(ps.name); 2142 } 2143 } 2144 } 2145 2146 // Collect vendor overlay packages. 2147 // (Do this before scanning any apps.) 2148 // For security and version matching reason, only consider 2149 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2150 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2151 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2152 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2153 2154 // Find base frameworks (resource packages without code). 2155 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2156 | PackageParser.PARSE_IS_SYSTEM_DIR 2157 | PackageParser.PARSE_IS_PRIVILEGED, 2158 scanFlags | SCAN_NO_DEX, 0); 2159 2160 // Collected privileged system packages. 2161 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2162 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2163 | PackageParser.PARSE_IS_SYSTEM_DIR 2164 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2165 2166 // Collect ordinary system packages. 2167 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2168 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2169 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2170 2171 // Collect all vendor packages. 2172 File vendorAppDir = new File("/vendor/app"); 2173 try { 2174 vendorAppDir = vendorAppDir.getCanonicalFile(); 2175 } catch (IOException e) { 2176 // failed to look up canonical path, continue with original one 2177 } 2178 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2179 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2180 2181 // Collect all OEM packages. 2182 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2183 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2184 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2185 2186 // Prune any system packages that no longer exist. 2187 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2188 if (!mOnlyCore) { 2189 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2190 while (psit.hasNext()) { 2191 PackageSetting ps = psit.next(); 2192 2193 /* 2194 * If this is not a system app, it can't be a 2195 * disable system app. 2196 */ 2197 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2198 continue; 2199 } 2200 2201 /* 2202 * If the package is scanned, it's not erased. 2203 */ 2204 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2205 if (scannedPkg != null) { 2206 /* 2207 * If the system app is both scanned and in the 2208 * disabled packages list, then it must have been 2209 * added via OTA. Remove it from the currently 2210 * scanned package so the previously user-installed 2211 * application can be scanned. 2212 */ 2213 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2214 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2215 + ps.name + "; removing system app. Last known codePath=" 2216 + ps.codePathString + ", installStatus=" + ps.installStatus 2217 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2218 + scannedPkg.mVersionCode); 2219 removePackageLI(ps, true); 2220 mExpectingBetter.put(ps.name, ps.codePath); 2221 } 2222 2223 continue; 2224 } 2225 2226 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2227 psit.remove(); 2228 logCriticalInfo(Log.WARN, "System package " + ps.name 2229 + " no longer exists; wiping its data"); 2230 removeDataDirsLI(null, ps.name); 2231 } else { 2232 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2233 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2234 possiblyDeletedUpdatedSystemApps.add(ps.name); 2235 } 2236 } 2237 } 2238 } 2239 2240 //look for any incomplete package installations 2241 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2242 //clean up list 2243 for(int i = 0; i < deletePkgsList.size(); i++) { 2244 //clean up here 2245 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2246 } 2247 //delete tmp files 2248 deleteTempPackageFiles(); 2249 2250 // Remove any shared userIDs that have no associated packages 2251 mSettings.pruneSharedUsersLPw(); 2252 2253 if (!mOnlyCore) { 2254 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2255 SystemClock.uptimeMillis()); 2256 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2257 2258 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2259 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2260 2261 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2262 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2263 2264 /** 2265 * Remove disable package settings for any updated system 2266 * apps that were removed via an OTA. If they're not a 2267 * previously-updated app, remove them completely. 2268 * Otherwise, just revoke their system-level permissions. 2269 */ 2270 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2271 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2272 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2273 2274 String msg; 2275 if (deletedPkg == null) { 2276 msg = "Updated system package " + deletedAppName 2277 + " no longer exists; wiping its data"; 2278 removeDataDirsLI(null, deletedAppName); 2279 } else { 2280 msg = "Updated system app + " + deletedAppName 2281 + " no longer present; removing system privileges for " 2282 + deletedAppName; 2283 2284 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2285 2286 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2287 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2288 } 2289 logCriticalInfo(Log.WARN, msg); 2290 } 2291 2292 /** 2293 * Make sure all system apps that we expected to appear on 2294 * the userdata partition actually showed up. If they never 2295 * appeared, crawl back and revive the system version. 2296 */ 2297 for (int i = 0; i < mExpectingBetter.size(); i++) { 2298 final String packageName = mExpectingBetter.keyAt(i); 2299 if (!mPackages.containsKey(packageName)) { 2300 final File scanFile = mExpectingBetter.valueAt(i); 2301 2302 logCriticalInfo(Log.WARN, "Expected better " + packageName 2303 + " but never showed up; reverting to system"); 2304 2305 final int reparseFlags; 2306 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2307 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2308 | PackageParser.PARSE_IS_SYSTEM_DIR 2309 | PackageParser.PARSE_IS_PRIVILEGED; 2310 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2311 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2312 | PackageParser.PARSE_IS_SYSTEM_DIR; 2313 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2314 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2315 | PackageParser.PARSE_IS_SYSTEM_DIR; 2316 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2317 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2318 | PackageParser.PARSE_IS_SYSTEM_DIR; 2319 } else { 2320 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2321 continue; 2322 } 2323 2324 mSettings.enableSystemPackageLPw(packageName); 2325 2326 try { 2327 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2328 } catch (PackageManagerException e) { 2329 Slog.e(TAG, "Failed to parse original system package: " 2330 + e.getMessage()); 2331 } 2332 } 2333 } 2334 } 2335 mExpectingBetter.clear(); 2336 2337 // Now that we know all of the shared libraries, update all clients to have 2338 // the correct library paths. 2339 updateAllSharedLibrariesLPw(); 2340 2341 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2342 // NOTE: We ignore potential failures here during a system scan (like 2343 // the rest of the commands above) because there's precious little we 2344 // can do about it. A settings error is reported, though. 2345 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2346 false /* boot complete */); 2347 } 2348 2349 // Now that we know all the packages we are keeping, 2350 // read and update their last usage times. 2351 mPackageUsage.readLP(); 2352 2353 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2354 SystemClock.uptimeMillis()); 2355 Slog.i(TAG, "Time to scan packages: " 2356 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2357 + " seconds"); 2358 2359 // If the platform SDK has changed since the last time we booted, 2360 // we need to re-grant app permission to catch any new ones that 2361 // appear. This is really a hack, and means that apps can in some 2362 // cases get permissions that the user didn't initially explicitly 2363 // allow... it would be nice to have some better way to handle 2364 // this situation. 2365 int updateFlags = UPDATE_PERMISSIONS_ALL; 2366 if (ver.sdkVersion != mSdkVersion) { 2367 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2368 + mSdkVersion + "; regranting permissions for internal storage"); 2369 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2370 } 2371 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2372 ver.sdkVersion = mSdkVersion; 2373 2374 // If this is the first boot or an update from pre-M, and it is a normal 2375 // boot, then we need to initialize the default preferred apps across 2376 // all defined users. 2377 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2378 for (UserInfo user : sUserManager.getUsers(true)) { 2379 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2380 applyFactoryDefaultBrowserLPw(user.id); 2381 primeDomainVerificationsLPw(user.id); 2382 } 2383 } 2384 2385 // Prepare storage for system user really early during boot, 2386 // since core system apps like SettingsProvider and SystemUI 2387 // can't wait for user to start 2388 final int storageFlags; 2389 if (StorageManager.isFileBasedEncryptionEnabled()) { 2390 storageFlags = StorageManager.FLAG_STORAGE_DE; 2391 } else { 2392 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2393 } 2394 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2395 storageFlags); 2396 2397 if (!StorageManager.isFileBasedEncryptionEnabled() 2398 && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) { 2399 // When upgrading a non-FBE device, we might need to shuffle 2400 // around the default storage location of system apps 2401 final List<UserInfo> users = sUserManager.getUsers(true); 2402 for (PackageSetting ps : mSettings.mPackages.values()) { 2403 if (ps.pkg == null || !ps.isSystem()) continue; 2404 final int storageTarget = ps.pkg.applicationInfo.isForceDeviceEncrypted() 2405 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 2406 for (UserInfo user : users) { 2407 if (ps.getInstalled(user.id)) { 2408 try { 2409 mInstaller.migrateAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2410 ps.name, user.id, storageTarget); 2411 } catch (InstallerException e) { 2412 logCriticalInfo(Log.WARN, 2413 "Failed to migrate " + ps.name + ": " + e.getMessage()); 2414 } 2415 // We may have just shuffled around app data 2416 // directories, so prepare it one more time 2417 prepareAppData(StorageManager.UUID_PRIVATE_INTERNAL, user.id, 2418 storageFlags, ps.pkg, false); 2419 } 2420 } 2421 } 2422 } 2423 2424 // If this is first boot after an OTA, and a normal boot, then 2425 // we need to clear code cache directories. 2426 if (mIsUpgrade && !onlyCore) { 2427 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2428 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2429 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2430 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2431 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2432 } 2433 } 2434 ver.fingerprint = Build.FINGERPRINT; 2435 } 2436 2437 checkDefaultBrowser(); 2438 2439 // clear only after permissions and other defaults have been updated 2440 mExistingSystemPackages.clear(); 2441 mPromoteSystemApps = false; 2442 2443 // All the changes are done during package scanning. 2444 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2445 2446 // can downgrade to reader 2447 mSettings.writeLPr(); 2448 2449 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2450 SystemClock.uptimeMillis()); 2451 2452 if (!mOnlyCore) { 2453 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2454 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2455 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2456 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2457 mIntentFilterVerifierComponent); 2458 } else { 2459 mRequiredVerifierPackage = null; 2460 mRequiredInstallerPackage = null; 2461 mIntentFilterVerifierComponent = null; 2462 mIntentFilterVerifier = null; 2463 } 2464 2465 mInstallerService = new PackageInstallerService(context, this); 2466 2467 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2468 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2469 // both the installer and resolver must be present to enable ephemeral 2470 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2471 if (DEBUG_EPHEMERAL) { 2472 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2473 + " installer:" + ephemeralInstallerComponent); 2474 } 2475 mEphemeralResolverComponent = ephemeralResolverComponent; 2476 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2477 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2478 mEphemeralResolverConnection = 2479 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2480 } else { 2481 if (DEBUG_EPHEMERAL) { 2482 final String missingComponent = 2483 (ephemeralResolverComponent == null) 2484 ? (ephemeralInstallerComponent == null) 2485 ? "resolver and installer" 2486 : "resolver" 2487 : "installer"; 2488 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2489 } 2490 mEphemeralResolverComponent = null; 2491 mEphemeralInstallerComponent = null; 2492 mEphemeralResolverConnection = null; 2493 } 2494 2495 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2496 } // synchronized (mPackages) 2497 } // synchronized (mInstallLock) 2498 2499 // Now after opening every single application zip, make sure they 2500 // are all flushed. Not really needed, but keeps things nice and 2501 // tidy. 2502 Runtime.getRuntime().gc(); 2503 2504 // The initial scanning above does many calls into installd while 2505 // holding the mPackages lock, but we're mostly interested in yelling 2506 // once we have a booted system. 2507 mInstaller.setWarnIfHeld(mPackages); 2508 2509 // Expose private service for system components to use. 2510 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2511 } 2512 2513 @Override 2514 public boolean isFirstBoot() { 2515 return !mRestoredSettings; 2516 } 2517 2518 @Override 2519 public boolean isOnlyCoreApps() { 2520 return mOnlyCore; 2521 } 2522 2523 @Override 2524 public boolean isUpgrade() { 2525 return mIsUpgrade; 2526 } 2527 2528 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2529 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2530 2531 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2532 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2533 if (matches.size() == 1) { 2534 return matches.get(0).getComponentInfo().packageName; 2535 } else { 2536 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2537 return null; 2538 } 2539 } 2540 2541 private @NonNull String getRequiredInstallerLPr() { 2542 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2543 intent.addCategory(Intent.CATEGORY_DEFAULT); 2544 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2545 2546 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2547 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2548 if (matches.size() == 1) { 2549 return matches.get(0).getComponentInfo().packageName; 2550 } else { 2551 throw new RuntimeException("There must be exactly one installer; found " + matches); 2552 } 2553 } 2554 2555 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2556 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2557 2558 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2559 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2560 ResolveInfo best = null; 2561 final int N = matches.size(); 2562 for (int i = 0; i < N; i++) { 2563 final ResolveInfo cur = matches.get(i); 2564 final String packageName = cur.getComponentInfo().packageName; 2565 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2566 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2567 continue; 2568 } 2569 2570 if (best == null || cur.priority > best.priority) { 2571 best = cur; 2572 } 2573 } 2574 2575 if (best != null) { 2576 return best.getComponentInfo().getComponentName(); 2577 } else { 2578 throw new RuntimeException("There must be at least one intent filter verifier"); 2579 } 2580 } 2581 2582 private @Nullable ComponentName getEphemeralResolverLPr() { 2583 final String[] packageArray = 2584 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2585 if (packageArray.length == 0) { 2586 if (DEBUG_EPHEMERAL) { 2587 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2588 } 2589 return null; 2590 } 2591 2592 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2593 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null, 2594 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2595 2596 final int N = resolvers.size(); 2597 if (N == 0) { 2598 if (DEBUG_EPHEMERAL) { 2599 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2600 } 2601 return null; 2602 } 2603 2604 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2605 for (int i = 0; i < N; i++) { 2606 final ResolveInfo info = resolvers.get(i); 2607 2608 if (info.serviceInfo == null) { 2609 continue; 2610 } 2611 2612 final String packageName = info.serviceInfo.packageName; 2613 if (!possiblePackages.contains(packageName)) { 2614 if (DEBUG_EPHEMERAL) { 2615 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2616 + " pkg: " + packageName + ", info:" + info); 2617 } 2618 continue; 2619 } 2620 2621 if (DEBUG_EPHEMERAL) { 2622 Slog.v(TAG, "Ephemeral resolver found;" 2623 + " pkg: " + packageName + ", info:" + info); 2624 } 2625 return new ComponentName(packageName, info.serviceInfo.name); 2626 } 2627 if (DEBUG_EPHEMERAL) { 2628 Slog.v(TAG, "Ephemeral resolver NOT found"); 2629 } 2630 return null; 2631 } 2632 2633 private @Nullable ComponentName getEphemeralInstallerLPr() { 2634 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2635 intent.addCategory(Intent.CATEGORY_DEFAULT); 2636 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2637 2638 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2639 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2640 if (matches.size() == 0) { 2641 return null; 2642 } else if (matches.size() == 1) { 2643 return matches.get(0).getComponentInfo().getComponentName(); 2644 } else { 2645 throw new RuntimeException( 2646 "There must be at most one ephemeral installer; found " + matches); 2647 } 2648 } 2649 2650 private void primeDomainVerificationsLPw(int userId) { 2651 if (DEBUG_DOMAIN_VERIFICATION) { 2652 Slog.d(TAG, "Priming domain verifications in user " + userId); 2653 } 2654 2655 SystemConfig systemConfig = SystemConfig.getInstance(); 2656 ArraySet<String> packages = systemConfig.getLinkedApps(); 2657 ArraySet<String> domains = new ArraySet<String>(); 2658 2659 for (String packageName : packages) { 2660 PackageParser.Package pkg = mPackages.get(packageName); 2661 if (pkg != null) { 2662 if (!pkg.isSystemApp()) { 2663 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2664 continue; 2665 } 2666 2667 domains.clear(); 2668 for (PackageParser.Activity a : pkg.activities) { 2669 for (ActivityIntentInfo filter : a.intents) { 2670 if (hasValidDomains(filter)) { 2671 domains.addAll(filter.getHostsList()); 2672 } 2673 } 2674 } 2675 2676 if (domains.size() > 0) { 2677 if (DEBUG_DOMAIN_VERIFICATION) { 2678 Slog.v(TAG, " + " + packageName); 2679 } 2680 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2681 // state w.r.t. the formal app-linkage "no verification attempted" state; 2682 // and then 'always' in the per-user state actually used for intent resolution. 2683 final IntentFilterVerificationInfo ivi; 2684 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2685 new ArrayList<String>(domains)); 2686 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2687 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2688 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2689 } else { 2690 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2691 + "' does not handle web links"); 2692 } 2693 } else { 2694 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2695 } 2696 } 2697 2698 scheduleWritePackageRestrictionsLocked(userId); 2699 scheduleWriteSettingsLocked(); 2700 } 2701 2702 private void applyFactoryDefaultBrowserLPw(int userId) { 2703 // The default browser app's package name is stored in a string resource, 2704 // with a product-specific overlay used for vendor customization. 2705 String browserPkg = mContext.getResources().getString( 2706 com.android.internal.R.string.default_browser); 2707 if (!TextUtils.isEmpty(browserPkg)) { 2708 // non-empty string => required to be a known package 2709 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2710 if (ps == null) { 2711 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2712 browserPkg = null; 2713 } else { 2714 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2715 } 2716 } 2717 2718 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2719 // default. If there's more than one, just leave everything alone. 2720 if (browserPkg == null) { 2721 calculateDefaultBrowserLPw(userId); 2722 } 2723 } 2724 2725 private void calculateDefaultBrowserLPw(int userId) { 2726 List<String> allBrowsers = resolveAllBrowserApps(userId); 2727 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2728 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2729 } 2730 2731 private List<String> resolveAllBrowserApps(int userId) { 2732 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2733 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2734 PackageManager.MATCH_ALL, userId); 2735 2736 final int count = list.size(); 2737 List<String> result = new ArrayList<String>(count); 2738 for (int i=0; i<count; i++) { 2739 ResolveInfo info = list.get(i); 2740 if (info.activityInfo == null 2741 || !info.handleAllWebDataURI 2742 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2743 || result.contains(info.activityInfo.packageName)) { 2744 continue; 2745 } 2746 result.add(info.activityInfo.packageName); 2747 } 2748 2749 return result; 2750 } 2751 2752 private boolean packageIsBrowser(String packageName, int userId) { 2753 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2754 PackageManager.MATCH_ALL, userId); 2755 final int N = list.size(); 2756 for (int i = 0; i < N; i++) { 2757 ResolveInfo info = list.get(i); 2758 if (packageName.equals(info.activityInfo.packageName)) { 2759 return true; 2760 } 2761 } 2762 return false; 2763 } 2764 2765 private void checkDefaultBrowser() { 2766 final int myUserId = UserHandle.myUserId(); 2767 final String packageName = getDefaultBrowserPackageName(myUserId); 2768 if (packageName != null) { 2769 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2770 if (info == null) { 2771 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2772 synchronized (mPackages) { 2773 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2774 } 2775 } 2776 } 2777 } 2778 2779 @Override 2780 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2781 throws RemoteException { 2782 try { 2783 return super.onTransact(code, data, reply, flags); 2784 } catch (RuntimeException e) { 2785 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2786 Slog.wtf(TAG, "Package Manager Crash", e); 2787 } 2788 throw e; 2789 } 2790 } 2791 2792 void cleanupInstallFailedPackage(PackageSetting ps) { 2793 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2794 2795 removeDataDirsLI(ps.volumeUuid, ps.name); 2796 if (ps.codePath != null) { 2797 removeCodePathLI(ps.codePath); 2798 } 2799 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2800 if (ps.resourcePath.isDirectory()) { 2801 FileUtils.deleteContents(ps.resourcePath); 2802 } 2803 ps.resourcePath.delete(); 2804 } 2805 mSettings.removePackageLPw(ps.name); 2806 } 2807 2808 static int[] appendInts(int[] cur, int[] add) { 2809 if (add == null) return cur; 2810 if (cur == null) return add; 2811 final int N = add.length; 2812 for (int i=0; i<N; i++) { 2813 cur = appendInt(cur, add[i]); 2814 } 2815 return cur; 2816 } 2817 2818 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2819 if (!sUserManager.exists(userId)) return null; 2820 final PackageSetting ps = (PackageSetting) p.mExtras; 2821 if (ps == null) { 2822 return null; 2823 } 2824 2825 final PermissionsState permissionsState = ps.getPermissionsState(); 2826 2827 final int[] gids = permissionsState.computeGids(userId); 2828 final Set<String> permissions = permissionsState.getPermissions(userId); 2829 final PackageUserState state = ps.readUserState(userId); 2830 2831 return PackageParser.generatePackageInfo(p, gids, flags, 2832 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2833 } 2834 2835 @Override 2836 public void checkPackageStartable(String packageName, int userId) { 2837 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2838 2839 synchronized (mPackages) { 2840 final PackageSetting ps = mSettings.mPackages.get(packageName); 2841 if (ps == null) { 2842 throw new SecurityException("Package " + packageName + " was not found!"); 2843 } 2844 2845 if (ps.frozen) { 2846 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2847 } 2848 2849 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2850 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2851 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2852 } 2853 } 2854 } 2855 2856 @Override 2857 public boolean isPackageAvailable(String packageName, int userId) { 2858 if (!sUserManager.exists(userId)) return false; 2859 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2860 synchronized (mPackages) { 2861 PackageParser.Package p = mPackages.get(packageName); 2862 if (p != null) { 2863 final PackageSetting ps = (PackageSetting) p.mExtras; 2864 if (ps != null) { 2865 final PackageUserState state = ps.readUserState(userId); 2866 if (state != null) { 2867 return PackageParser.isAvailable(state); 2868 } 2869 } 2870 } 2871 } 2872 return false; 2873 } 2874 2875 @Override 2876 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2877 if (!sUserManager.exists(userId)) return null; 2878 flags = updateFlagsForPackage(flags, userId, packageName); 2879 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2880 // reader 2881 synchronized (mPackages) { 2882 PackageParser.Package p = mPackages.get(packageName); 2883 if (DEBUG_PACKAGE_INFO) 2884 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2885 if (p != null) { 2886 return generatePackageInfo(p, flags, userId); 2887 } 2888 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2889 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2890 } 2891 } 2892 return null; 2893 } 2894 2895 @Override 2896 public String[] currentToCanonicalPackageNames(String[] names) { 2897 String[] out = new String[names.length]; 2898 // reader 2899 synchronized (mPackages) { 2900 for (int i=names.length-1; i>=0; i--) { 2901 PackageSetting ps = mSettings.mPackages.get(names[i]); 2902 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2903 } 2904 } 2905 return out; 2906 } 2907 2908 @Override 2909 public String[] canonicalToCurrentPackageNames(String[] names) { 2910 String[] out = new String[names.length]; 2911 // reader 2912 synchronized (mPackages) { 2913 for (int i=names.length-1; i>=0; i--) { 2914 String cur = mSettings.mRenamedPackages.get(names[i]); 2915 out[i] = cur != null ? cur : names[i]; 2916 } 2917 } 2918 return out; 2919 } 2920 2921 @Override 2922 public int getPackageUid(String packageName, int flags, int userId) { 2923 if (!sUserManager.exists(userId)) return -1; 2924 flags = updateFlagsForPackage(flags, userId, packageName); 2925 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2926 2927 // reader 2928 synchronized (mPackages) { 2929 final PackageParser.Package p = mPackages.get(packageName); 2930 if (p != null && p.isMatch(flags)) { 2931 return UserHandle.getUid(userId, p.applicationInfo.uid); 2932 } 2933 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2934 final PackageSetting ps = mSettings.mPackages.get(packageName); 2935 if (ps != null && ps.isMatch(flags)) { 2936 return UserHandle.getUid(userId, ps.appId); 2937 } 2938 } 2939 } 2940 2941 return -1; 2942 } 2943 2944 @Override 2945 public int[] getPackageGids(String packageName, int flags, int userId) { 2946 if (!sUserManager.exists(userId)) return null; 2947 flags = updateFlagsForPackage(flags, userId, packageName); 2948 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2949 "getPackageGids"); 2950 2951 // reader 2952 synchronized (mPackages) { 2953 final PackageParser.Package p = mPackages.get(packageName); 2954 if (p != null && p.isMatch(flags)) { 2955 PackageSetting ps = (PackageSetting) p.mExtras; 2956 return ps.getPermissionsState().computeGids(userId); 2957 } 2958 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2959 final PackageSetting ps = mSettings.mPackages.get(packageName); 2960 if (ps != null && ps.isMatch(flags)) { 2961 return ps.getPermissionsState().computeGids(userId); 2962 } 2963 } 2964 } 2965 2966 return null; 2967 } 2968 2969 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 2970 if (bp.perm != null) { 2971 return PackageParser.generatePermissionInfo(bp.perm, flags); 2972 } 2973 PermissionInfo pi = new PermissionInfo(); 2974 pi.name = bp.name; 2975 pi.packageName = bp.sourcePackage; 2976 pi.nonLocalizedLabel = bp.name; 2977 pi.protectionLevel = bp.protectionLevel; 2978 return pi; 2979 } 2980 2981 @Override 2982 public PermissionInfo getPermissionInfo(String name, int flags) { 2983 // reader 2984 synchronized (mPackages) { 2985 final BasePermission p = mSettings.mPermissions.get(name); 2986 if (p != null) { 2987 return generatePermissionInfo(p, flags); 2988 } 2989 return null; 2990 } 2991 } 2992 2993 @Override 2994 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2995 // reader 2996 synchronized (mPackages) { 2997 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2998 for (BasePermission p : mSettings.mPermissions.values()) { 2999 if (group == null) { 3000 if (p.perm == null || p.perm.info.group == null) { 3001 out.add(generatePermissionInfo(p, flags)); 3002 } 3003 } else { 3004 if (p.perm != null && group.equals(p.perm.info.group)) { 3005 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3006 } 3007 } 3008 } 3009 3010 if (out.size() > 0) { 3011 return out; 3012 } 3013 return mPermissionGroups.containsKey(group) ? out : null; 3014 } 3015 } 3016 3017 @Override 3018 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3019 // reader 3020 synchronized (mPackages) { 3021 return PackageParser.generatePermissionGroupInfo( 3022 mPermissionGroups.get(name), flags); 3023 } 3024 } 3025 3026 @Override 3027 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3028 // reader 3029 synchronized (mPackages) { 3030 final int N = mPermissionGroups.size(); 3031 ArrayList<PermissionGroupInfo> out 3032 = new ArrayList<PermissionGroupInfo>(N); 3033 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3034 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3035 } 3036 return out; 3037 } 3038 } 3039 3040 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3041 int userId) { 3042 if (!sUserManager.exists(userId)) return null; 3043 PackageSetting ps = mSettings.mPackages.get(packageName); 3044 if (ps != null) { 3045 if (ps.pkg == null) { 3046 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3047 flags, userId); 3048 if (pInfo != null) { 3049 return pInfo.applicationInfo; 3050 } 3051 return null; 3052 } 3053 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3054 ps.readUserState(userId), userId); 3055 } 3056 return null; 3057 } 3058 3059 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3060 int userId) { 3061 if (!sUserManager.exists(userId)) return null; 3062 PackageSetting ps = mSettings.mPackages.get(packageName); 3063 if (ps != null) { 3064 PackageParser.Package pkg = ps.pkg; 3065 if (pkg == null) { 3066 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3067 return null; 3068 } 3069 // Only data remains, so we aren't worried about code paths 3070 pkg = new PackageParser.Package(packageName); 3071 pkg.applicationInfo.packageName = packageName; 3072 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3073 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3074 pkg.applicationInfo.uid = ps.appId; 3075 pkg.applicationInfo.initForUser(userId); 3076 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3077 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3078 } 3079 return generatePackageInfo(pkg, flags, userId); 3080 } 3081 return null; 3082 } 3083 3084 @Override 3085 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3086 if (!sUserManager.exists(userId)) return null; 3087 flags = updateFlagsForApplication(flags, userId, packageName); 3088 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3089 // writer 3090 synchronized (mPackages) { 3091 PackageParser.Package p = mPackages.get(packageName); 3092 if (DEBUG_PACKAGE_INFO) Log.v( 3093 TAG, "getApplicationInfo " + packageName 3094 + ": " + p); 3095 if (p != null) { 3096 PackageSetting ps = mSettings.mPackages.get(packageName); 3097 if (ps == null) return null; 3098 // Note: isEnabledLP() does not apply here - always return info 3099 return PackageParser.generateApplicationInfo( 3100 p, flags, ps.readUserState(userId), userId); 3101 } 3102 if ("android".equals(packageName)||"system".equals(packageName)) { 3103 return mAndroidApplication; 3104 } 3105 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3106 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3107 } 3108 } 3109 return null; 3110 } 3111 3112 @Override 3113 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3114 final IPackageDataObserver observer) { 3115 mContext.enforceCallingOrSelfPermission( 3116 android.Manifest.permission.CLEAR_APP_CACHE, null); 3117 // Queue up an async operation since clearing cache may take a little while. 3118 mHandler.post(new Runnable() { 3119 public void run() { 3120 mHandler.removeCallbacks(this); 3121 boolean success = true; 3122 synchronized (mInstallLock) { 3123 try { 3124 mInstaller.freeCache(volumeUuid, freeStorageSize); 3125 } catch (InstallerException e) { 3126 Slog.w(TAG, "Couldn't clear application caches: " + e); 3127 success = false; 3128 } 3129 } 3130 if (observer != null) { 3131 try { 3132 observer.onRemoveCompleted(null, success); 3133 } catch (RemoteException e) { 3134 Slog.w(TAG, "RemoveException when invoking call back"); 3135 } 3136 } 3137 } 3138 }); 3139 } 3140 3141 @Override 3142 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3143 final IntentSender pi) { 3144 mContext.enforceCallingOrSelfPermission( 3145 android.Manifest.permission.CLEAR_APP_CACHE, null); 3146 // Queue up an async operation since clearing cache may take a little while. 3147 mHandler.post(new Runnable() { 3148 public void run() { 3149 mHandler.removeCallbacks(this); 3150 boolean success = true; 3151 synchronized (mInstallLock) { 3152 try { 3153 mInstaller.freeCache(volumeUuid, freeStorageSize); 3154 } catch (InstallerException e) { 3155 Slog.w(TAG, "Couldn't clear application caches: " + e); 3156 success = false; 3157 } 3158 } 3159 if(pi != null) { 3160 try { 3161 // Callback via pending intent 3162 int code = success ? 1 : 0; 3163 pi.sendIntent(null, code, null, 3164 null, null); 3165 } catch (SendIntentException e1) { 3166 Slog.i(TAG, "Failed to send pending intent"); 3167 } 3168 } 3169 } 3170 }); 3171 } 3172 3173 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3174 synchronized (mInstallLock) { 3175 try { 3176 mInstaller.freeCache(volumeUuid, freeStorageSize); 3177 } catch (InstallerException e) { 3178 throw new IOException("Failed to free enough space", e); 3179 } 3180 } 3181 } 3182 3183 /** 3184 * Return if the user key is currently unlocked. 3185 */ 3186 private boolean isUserKeyUnlocked(int userId) { 3187 if (StorageManager.isFileBasedEncryptionEnabled()) { 3188 final IMountService mount = IMountService.Stub 3189 .asInterface(ServiceManager.getService("mount")); 3190 if (mount == null) { 3191 Slog.w(TAG, "Early during boot, assuming locked"); 3192 return false; 3193 } 3194 final long token = Binder.clearCallingIdentity(); 3195 try { 3196 return mount.isUserKeyUnlocked(userId); 3197 } catch (RemoteException e) { 3198 throw e.rethrowAsRuntimeException(); 3199 } finally { 3200 Binder.restoreCallingIdentity(token); 3201 } 3202 } else { 3203 return true; 3204 } 3205 } 3206 3207 /** 3208 * Update given flags based on encryption status of current user. 3209 */ 3210 private int updateFlags(int flags, int userId) { 3211 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3212 | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) { 3213 // Caller expressed an explicit opinion about what encryption 3214 // aware/unaware components they want to see, so fall through and 3215 // give them what they want 3216 } else { 3217 // Caller expressed no opinion, so match based on user state 3218 if (isUserKeyUnlocked(userId)) { 3219 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 3220 } else { 3221 flags |= PackageManager.MATCH_ENCRYPTION_AWARE; 3222 } 3223 } 3224 3225 // Safe mode means we should ignore any third-party apps 3226 if (mSafeMode) { 3227 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3228 } 3229 3230 return flags; 3231 } 3232 3233 /** 3234 * Update given flags when being used to request {@link PackageInfo}. 3235 */ 3236 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3237 boolean triaged = true; 3238 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3239 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3240 // Caller is asking for component details, so they'd better be 3241 // asking for specific encryption matching behavior, or be triaged 3242 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3243 | PackageManager.MATCH_ENCRYPTION_AWARE 3244 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3245 triaged = false; 3246 } 3247 } 3248 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3249 | PackageManager.MATCH_SYSTEM_ONLY 3250 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3251 triaged = false; 3252 } 3253 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3254 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3255 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3256 } 3257 return updateFlags(flags, userId); 3258 } 3259 3260 /** 3261 * Update given flags when being used to request {@link ApplicationInfo}. 3262 */ 3263 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3264 return updateFlagsForPackage(flags, userId, cookie); 3265 } 3266 3267 /** 3268 * Update given flags when being used to request {@link ComponentInfo}. 3269 */ 3270 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3271 if (cookie instanceof Intent) { 3272 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3273 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3274 } 3275 } 3276 3277 boolean triaged = true; 3278 // Caller is asking for component details, so they'd better be 3279 // asking for specific encryption matching behavior, or be triaged 3280 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3281 | PackageManager.MATCH_ENCRYPTION_AWARE 3282 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3283 triaged = false; 3284 } 3285 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3286 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3287 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3288 } 3289 return updateFlags(flags, userId); 3290 } 3291 3292 /** 3293 * Update given flags when being used to request {@link ResolveInfo}. 3294 */ 3295 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3296 return updateFlagsForComponent(flags, userId, cookie); 3297 } 3298 3299 @Override 3300 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3301 if (!sUserManager.exists(userId)) return null; 3302 flags = updateFlagsForComponent(flags, userId, component); 3303 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3304 synchronized (mPackages) { 3305 PackageParser.Activity a = mActivities.mActivities.get(component); 3306 3307 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3308 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3309 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3310 if (ps == null) return null; 3311 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3312 userId); 3313 } 3314 if (mResolveComponentName.equals(component)) { 3315 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3316 new PackageUserState(), userId); 3317 } 3318 } 3319 return null; 3320 } 3321 3322 @Override 3323 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3324 String resolvedType) { 3325 synchronized (mPackages) { 3326 if (component.equals(mResolveComponentName)) { 3327 // The resolver supports EVERYTHING! 3328 return true; 3329 } 3330 PackageParser.Activity a = mActivities.mActivities.get(component); 3331 if (a == null) { 3332 return false; 3333 } 3334 for (int i=0; i<a.intents.size(); i++) { 3335 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3336 intent.getData(), intent.getCategories(), TAG) >= 0) { 3337 return true; 3338 } 3339 } 3340 return false; 3341 } 3342 } 3343 3344 @Override 3345 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3346 if (!sUserManager.exists(userId)) return null; 3347 flags = updateFlagsForComponent(flags, userId, component); 3348 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3349 synchronized (mPackages) { 3350 PackageParser.Activity a = mReceivers.mActivities.get(component); 3351 if (DEBUG_PACKAGE_INFO) Log.v( 3352 TAG, "getReceiverInfo " + component + ": " + a); 3353 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3354 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3355 if (ps == null) return null; 3356 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3357 userId); 3358 } 3359 } 3360 return null; 3361 } 3362 3363 @Override 3364 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3365 if (!sUserManager.exists(userId)) return null; 3366 flags = updateFlagsForComponent(flags, userId, component); 3367 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3368 synchronized (mPackages) { 3369 PackageParser.Service s = mServices.mServices.get(component); 3370 if (DEBUG_PACKAGE_INFO) Log.v( 3371 TAG, "getServiceInfo " + component + ": " + s); 3372 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3373 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3374 if (ps == null) return null; 3375 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3376 userId); 3377 } 3378 } 3379 return null; 3380 } 3381 3382 @Override 3383 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3384 if (!sUserManager.exists(userId)) return null; 3385 flags = updateFlagsForComponent(flags, userId, component); 3386 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3387 synchronized (mPackages) { 3388 PackageParser.Provider p = mProviders.mProviders.get(component); 3389 if (DEBUG_PACKAGE_INFO) Log.v( 3390 TAG, "getProviderInfo " + component + ": " + p); 3391 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3392 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3393 if (ps == null) return null; 3394 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3395 userId); 3396 } 3397 } 3398 return null; 3399 } 3400 3401 @Override 3402 public String[] getSystemSharedLibraryNames() { 3403 Set<String> libSet; 3404 synchronized (mPackages) { 3405 libSet = mSharedLibraries.keySet(); 3406 int size = libSet.size(); 3407 if (size > 0) { 3408 String[] libs = new String[size]; 3409 libSet.toArray(libs); 3410 return libs; 3411 } 3412 } 3413 return null; 3414 } 3415 3416 @Override 3417 public FeatureInfo[] getSystemAvailableFeatures() { 3418 Collection<FeatureInfo> featSet; 3419 synchronized (mPackages) { 3420 featSet = mAvailableFeatures.values(); 3421 int size = featSet.size(); 3422 if (size > 0) { 3423 FeatureInfo[] features = new FeatureInfo[size+1]; 3424 featSet.toArray(features); 3425 FeatureInfo fi = new FeatureInfo(); 3426 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3427 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3428 features[size] = fi; 3429 return features; 3430 } 3431 } 3432 return null; 3433 } 3434 3435 @Override 3436 public boolean hasSystemFeature(String name) { 3437 synchronized (mPackages) { 3438 return mAvailableFeatures.containsKey(name); 3439 } 3440 } 3441 3442 @Override 3443 public int checkPermission(String permName, String pkgName, int userId) { 3444 if (!sUserManager.exists(userId)) { 3445 return PackageManager.PERMISSION_DENIED; 3446 } 3447 3448 synchronized (mPackages) { 3449 final PackageParser.Package p = mPackages.get(pkgName); 3450 if (p != null && p.mExtras != null) { 3451 final PackageSetting ps = (PackageSetting) p.mExtras; 3452 final PermissionsState permissionsState = ps.getPermissionsState(); 3453 if (permissionsState.hasPermission(permName, userId)) { 3454 return PackageManager.PERMISSION_GRANTED; 3455 } 3456 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3457 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3458 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3459 return PackageManager.PERMISSION_GRANTED; 3460 } 3461 } 3462 } 3463 3464 return PackageManager.PERMISSION_DENIED; 3465 } 3466 3467 @Override 3468 public int checkUidPermission(String permName, int uid) { 3469 final int userId = UserHandle.getUserId(uid); 3470 3471 if (!sUserManager.exists(userId)) { 3472 return PackageManager.PERMISSION_DENIED; 3473 } 3474 3475 synchronized (mPackages) { 3476 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3477 if (obj != null) { 3478 final SettingBase ps = (SettingBase) obj; 3479 final PermissionsState permissionsState = ps.getPermissionsState(); 3480 if (permissionsState.hasPermission(permName, userId)) { 3481 return PackageManager.PERMISSION_GRANTED; 3482 } 3483 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3484 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3485 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3486 return PackageManager.PERMISSION_GRANTED; 3487 } 3488 } else { 3489 ArraySet<String> perms = mSystemPermissions.get(uid); 3490 if (perms != null) { 3491 if (perms.contains(permName)) { 3492 return PackageManager.PERMISSION_GRANTED; 3493 } 3494 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3495 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3496 return PackageManager.PERMISSION_GRANTED; 3497 } 3498 } 3499 } 3500 } 3501 3502 return PackageManager.PERMISSION_DENIED; 3503 } 3504 3505 @Override 3506 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3507 if (UserHandle.getCallingUserId() != userId) { 3508 mContext.enforceCallingPermission( 3509 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3510 "isPermissionRevokedByPolicy for user " + userId); 3511 } 3512 3513 if (checkPermission(permission, packageName, userId) 3514 == PackageManager.PERMISSION_GRANTED) { 3515 return false; 3516 } 3517 3518 final long identity = Binder.clearCallingIdentity(); 3519 try { 3520 final int flags = getPermissionFlags(permission, packageName, userId); 3521 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3522 } finally { 3523 Binder.restoreCallingIdentity(identity); 3524 } 3525 } 3526 3527 @Override 3528 public String getPermissionControllerPackageName() { 3529 synchronized (mPackages) { 3530 return mRequiredInstallerPackage; 3531 } 3532 } 3533 3534 /** 3535 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3536 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3537 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3538 * @param message the message to log on security exception 3539 */ 3540 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3541 boolean checkShell, String message) { 3542 if (userId < 0) { 3543 throw new IllegalArgumentException("Invalid userId " + userId); 3544 } 3545 if (checkShell) { 3546 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3547 } 3548 if (userId == UserHandle.getUserId(callingUid)) return; 3549 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3550 if (requireFullPermission) { 3551 mContext.enforceCallingOrSelfPermission( 3552 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3553 } else { 3554 try { 3555 mContext.enforceCallingOrSelfPermission( 3556 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3557 } catch (SecurityException se) { 3558 mContext.enforceCallingOrSelfPermission( 3559 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3560 } 3561 } 3562 } 3563 } 3564 3565 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3566 if (callingUid == Process.SHELL_UID) { 3567 if (userHandle >= 0 3568 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3569 throw new SecurityException("Shell does not have permission to access user " 3570 + userHandle); 3571 } else if (userHandle < 0) { 3572 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3573 + Debug.getCallers(3)); 3574 } 3575 } 3576 } 3577 3578 private BasePermission findPermissionTreeLP(String permName) { 3579 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3580 if (permName.startsWith(bp.name) && 3581 permName.length() > bp.name.length() && 3582 permName.charAt(bp.name.length()) == '.') { 3583 return bp; 3584 } 3585 } 3586 return null; 3587 } 3588 3589 private BasePermission checkPermissionTreeLP(String permName) { 3590 if (permName != null) { 3591 BasePermission bp = findPermissionTreeLP(permName); 3592 if (bp != null) { 3593 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3594 return bp; 3595 } 3596 throw new SecurityException("Calling uid " 3597 + Binder.getCallingUid() 3598 + " is not allowed to add to permission tree " 3599 + bp.name + " owned by uid " + bp.uid); 3600 } 3601 } 3602 throw new SecurityException("No permission tree found for " + permName); 3603 } 3604 3605 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3606 if (s1 == null) { 3607 return s2 == null; 3608 } 3609 if (s2 == null) { 3610 return false; 3611 } 3612 if (s1.getClass() != s2.getClass()) { 3613 return false; 3614 } 3615 return s1.equals(s2); 3616 } 3617 3618 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3619 if (pi1.icon != pi2.icon) return false; 3620 if (pi1.logo != pi2.logo) return false; 3621 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3622 if (!compareStrings(pi1.name, pi2.name)) return false; 3623 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3624 // We'll take care of setting this one. 3625 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3626 // These are not currently stored in settings. 3627 //if (!compareStrings(pi1.group, pi2.group)) return false; 3628 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3629 //if (pi1.labelRes != pi2.labelRes) return false; 3630 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3631 return true; 3632 } 3633 3634 int permissionInfoFootprint(PermissionInfo info) { 3635 int size = info.name.length(); 3636 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3637 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3638 return size; 3639 } 3640 3641 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3642 int size = 0; 3643 for (BasePermission perm : mSettings.mPermissions.values()) { 3644 if (perm.uid == tree.uid) { 3645 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3646 } 3647 } 3648 return size; 3649 } 3650 3651 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3652 // We calculate the max size of permissions defined by this uid and throw 3653 // if that plus the size of 'info' would exceed our stated maximum. 3654 if (tree.uid != Process.SYSTEM_UID) { 3655 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3656 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3657 throw new SecurityException("Permission tree size cap exceeded"); 3658 } 3659 } 3660 } 3661 3662 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3663 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3664 throw new SecurityException("Label must be specified in permission"); 3665 } 3666 BasePermission tree = checkPermissionTreeLP(info.name); 3667 BasePermission bp = mSettings.mPermissions.get(info.name); 3668 boolean added = bp == null; 3669 boolean changed = true; 3670 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3671 if (added) { 3672 enforcePermissionCapLocked(info, tree); 3673 bp = new BasePermission(info.name, tree.sourcePackage, 3674 BasePermission.TYPE_DYNAMIC); 3675 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3676 throw new SecurityException( 3677 "Not allowed to modify non-dynamic permission " 3678 + info.name); 3679 } else { 3680 if (bp.protectionLevel == fixedLevel 3681 && bp.perm.owner.equals(tree.perm.owner) 3682 && bp.uid == tree.uid 3683 && comparePermissionInfos(bp.perm.info, info)) { 3684 changed = false; 3685 } 3686 } 3687 bp.protectionLevel = fixedLevel; 3688 info = new PermissionInfo(info); 3689 info.protectionLevel = fixedLevel; 3690 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3691 bp.perm.info.packageName = tree.perm.info.packageName; 3692 bp.uid = tree.uid; 3693 if (added) { 3694 mSettings.mPermissions.put(info.name, bp); 3695 } 3696 if (changed) { 3697 if (!async) { 3698 mSettings.writeLPr(); 3699 } else { 3700 scheduleWriteSettingsLocked(); 3701 } 3702 } 3703 return added; 3704 } 3705 3706 @Override 3707 public boolean addPermission(PermissionInfo info) { 3708 synchronized (mPackages) { 3709 return addPermissionLocked(info, false); 3710 } 3711 } 3712 3713 @Override 3714 public boolean addPermissionAsync(PermissionInfo info) { 3715 synchronized (mPackages) { 3716 return addPermissionLocked(info, true); 3717 } 3718 } 3719 3720 @Override 3721 public void removePermission(String name) { 3722 synchronized (mPackages) { 3723 checkPermissionTreeLP(name); 3724 BasePermission bp = mSettings.mPermissions.get(name); 3725 if (bp != null) { 3726 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3727 throw new SecurityException( 3728 "Not allowed to modify non-dynamic permission " 3729 + name); 3730 } 3731 mSettings.mPermissions.remove(name); 3732 mSettings.writeLPr(); 3733 } 3734 } 3735 } 3736 3737 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3738 BasePermission bp) { 3739 int index = pkg.requestedPermissions.indexOf(bp.name); 3740 if (index == -1) { 3741 throw new SecurityException("Package " + pkg.packageName 3742 + " has not requested permission " + bp.name); 3743 } 3744 if (!bp.isRuntime() && !bp.isDevelopment()) { 3745 throw new SecurityException("Permission " + bp.name 3746 + " is not a changeable permission type"); 3747 } 3748 } 3749 3750 @Override 3751 public void grantRuntimePermission(String packageName, String name, final int userId) { 3752 if (!sUserManager.exists(userId)) { 3753 Log.e(TAG, "No such user:" + userId); 3754 return; 3755 } 3756 3757 mContext.enforceCallingOrSelfPermission( 3758 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3759 "grantRuntimePermission"); 3760 3761 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3762 "grantRuntimePermission"); 3763 3764 final int uid; 3765 final SettingBase sb; 3766 3767 synchronized (mPackages) { 3768 final PackageParser.Package pkg = mPackages.get(packageName); 3769 if (pkg == null) { 3770 throw new IllegalArgumentException("Unknown package: " + packageName); 3771 } 3772 3773 final BasePermission bp = mSettings.mPermissions.get(name); 3774 if (bp == null) { 3775 throw new IllegalArgumentException("Unknown permission: " + name); 3776 } 3777 3778 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3779 3780 // If a permission review is required for legacy apps we represent 3781 // their permissions as always granted runtime ones since we need 3782 // to keep the review required permission flag per user while an 3783 // install permission's state is shared across all users. 3784 if (Build.PERMISSIONS_REVIEW_REQUIRED 3785 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3786 && bp.isRuntime()) { 3787 return; 3788 } 3789 3790 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3791 sb = (SettingBase) pkg.mExtras; 3792 if (sb == null) { 3793 throw new IllegalArgumentException("Unknown package: " + packageName); 3794 } 3795 3796 final PermissionsState permissionsState = sb.getPermissionsState(); 3797 3798 final int flags = permissionsState.getPermissionFlags(name, userId); 3799 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3800 throw new SecurityException("Cannot grant system fixed permission " 3801 + name + " for package " + packageName); 3802 } 3803 3804 if (bp.isDevelopment()) { 3805 // Development permissions must be handled specially, since they are not 3806 // normal runtime permissions. For now they apply to all users. 3807 if (permissionsState.grantInstallPermission(bp) != 3808 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3809 scheduleWriteSettingsLocked(); 3810 } 3811 return; 3812 } 3813 3814 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3815 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3816 return; 3817 } 3818 3819 final int result = permissionsState.grantRuntimePermission(bp, userId); 3820 switch (result) { 3821 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3822 return; 3823 } 3824 3825 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3826 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3827 mHandler.post(new Runnable() { 3828 @Override 3829 public void run() { 3830 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3831 } 3832 }); 3833 } 3834 break; 3835 } 3836 3837 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3838 3839 // Not critical if that is lost - app has to request again. 3840 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3841 } 3842 3843 // Only need to do this if user is initialized. Otherwise it's a new user 3844 // and there are no processes running as the user yet and there's no need 3845 // to make an expensive call to remount processes for the changed permissions. 3846 if (READ_EXTERNAL_STORAGE.equals(name) 3847 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3848 final long token = Binder.clearCallingIdentity(); 3849 try { 3850 if (sUserManager.isInitialized(userId)) { 3851 MountServiceInternal mountServiceInternal = LocalServices.getService( 3852 MountServiceInternal.class); 3853 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3854 } 3855 } finally { 3856 Binder.restoreCallingIdentity(token); 3857 } 3858 } 3859 } 3860 3861 @Override 3862 public void revokeRuntimePermission(String packageName, String name, int userId) { 3863 if (!sUserManager.exists(userId)) { 3864 Log.e(TAG, "No such user:" + userId); 3865 return; 3866 } 3867 3868 mContext.enforceCallingOrSelfPermission( 3869 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3870 "revokeRuntimePermission"); 3871 3872 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3873 "revokeRuntimePermission"); 3874 3875 final int appId; 3876 3877 synchronized (mPackages) { 3878 final PackageParser.Package pkg = mPackages.get(packageName); 3879 if (pkg == null) { 3880 throw new IllegalArgumentException("Unknown package: " + packageName); 3881 } 3882 3883 final BasePermission bp = mSettings.mPermissions.get(name); 3884 if (bp == null) { 3885 throw new IllegalArgumentException("Unknown permission: " + name); 3886 } 3887 3888 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3889 3890 // If a permission review is required for legacy apps we represent 3891 // their permissions as always granted runtime ones since we need 3892 // to keep the review required permission flag per user while an 3893 // install permission's state is shared across all users. 3894 if (Build.PERMISSIONS_REVIEW_REQUIRED 3895 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3896 && bp.isRuntime()) { 3897 return; 3898 } 3899 3900 SettingBase sb = (SettingBase) pkg.mExtras; 3901 if (sb == null) { 3902 throw new IllegalArgumentException("Unknown package: " + packageName); 3903 } 3904 3905 final PermissionsState permissionsState = sb.getPermissionsState(); 3906 3907 final int flags = permissionsState.getPermissionFlags(name, userId); 3908 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3909 throw new SecurityException("Cannot revoke system fixed permission " 3910 + name + " for package " + packageName); 3911 } 3912 3913 if (bp.isDevelopment()) { 3914 // Development permissions must be handled specially, since they are not 3915 // normal runtime permissions. For now they apply to all users. 3916 if (permissionsState.revokeInstallPermission(bp) != 3917 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3918 scheduleWriteSettingsLocked(); 3919 } 3920 return; 3921 } 3922 3923 if (permissionsState.revokeRuntimePermission(bp, userId) == 3924 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3925 return; 3926 } 3927 3928 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3929 3930 // Critical, after this call app should never have the permission. 3931 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3932 3933 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3934 } 3935 3936 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3937 } 3938 3939 @Override 3940 public void resetRuntimePermissions() { 3941 mContext.enforceCallingOrSelfPermission( 3942 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3943 "revokeRuntimePermission"); 3944 3945 int callingUid = Binder.getCallingUid(); 3946 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3947 mContext.enforceCallingOrSelfPermission( 3948 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3949 "resetRuntimePermissions"); 3950 } 3951 3952 synchronized (mPackages) { 3953 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3954 for (int userId : UserManagerService.getInstance().getUserIds()) { 3955 final int packageCount = mPackages.size(); 3956 for (int i = 0; i < packageCount; i++) { 3957 PackageParser.Package pkg = mPackages.valueAt(i); 3958 if (!(pkg.mExtras instanceof PackageSetting)) { 3959 continue; 3960 } 3961 PackageSetting ps = (PackageSetting) pkg.mExtras; 3962 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3963 } 3964 } 3965 } 3966 } 3967 3968 @Override 3969 public int getPermissionFlags(String name, String packageName, int userId) { 3970 if (!sUserManager.exists(userId)) { 3971 return 0; 3972 } 3973 3974 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3975 3976 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3977 "getPermissionFlags"); 3978 3979 synchronized (mPackages) { 3980 final PackageParser.Package pkg = mPackages.get(packageName); 3981 if (pkg == null) { 3982 throw new IllegalArgumentException("Unknown package: " + packageName); 3983 } 3984 3985 final BasePermission bp = mSettings.mPermissions.get(name); 3986 if (bp == null) { 3987 throw new IllegalArgumentException("Unknown permission: " + name); 3988 } 3989 3990 SettingBase sb = (SettingBase) pkg.mExtras; 3991 if (sb == null) { 3992 throw new IllegalArgumentException("Unknown package: " + packageName); 3993 } 3994 3995 PermissionsState permissionsState = sb.getPermissionsState(); 3996 return permissionsState.getPermissionFlags(name, userId); 3997 } 3998 } 3999 4000 @Override 4001 public void updatePermissionFlags(String name, String packageName, int flagMask, 4002 int flagValues, int userId) { 4003 if (!sUserManager.exists(userId)) { 4004 return; 4005 } 4006 4007 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4008 4009 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4010 "updatePermissionFlags"); 4011 4012 // Only the system can change these flags and nothing else. 4013 if (getCallingUid() != Process.SYSTEM_UID) { 4014 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4015 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4016 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4017 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4018 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4019 } 4020 4021 synchronized (mPackages) { 4022 final PackageParser.Package pkg = mPackages.get(packageName); 4023 if (pkg == null) { 4024 throw new IllegalArgumentException("Unknown package: " + packageName); 4025 } 4026 4027 final BasePermission bp = mSettings.mPermissions.get(name); 4028 if (bp == null) { 4029 throw new IllegalArgumentException("Unknown permission: " + name); 4030 } 4031 4032 SettingBase sb = (SettingBase) pkg.mExtras; 4033 if (sb == null) { 4034 throw new IllegalArgumentException("Unknown package: " + packageName); 4035 } 4036 4037 PermissionsState permissionsState = sb.getPermissionsState(); 4038 4039 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4040 4041 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4042 // Install and runtime permissions are stored in different places, 4043 // so figure out what permission changed and persist the change. 4044 if (permissionsState.getInstallPermissionState(name) != null) { 4045 scheduleWriteSettingsLocked(); 4046 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4047 || hadState) { 4048 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4049 } 4050 } 4051 } 4052 } 4053 4054 /** 4055 * Update the permission flags for all packages and runtime permissions of a user in order 4056 * to allow device or profile owner to remove POLICY_FIXED. 4057 */ 4058 @Override 4059 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4060 if (!sUserManager.exists(userId)) { 4061 return; 4062 } 4063 4064 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4065 4066 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4067 "updatePermissionFlagsForAllApps"); 4068 4069 // Only the system can change system fixed flags. 4070 if (getCallingUid() != Process.SYSTEM_UID) { 4071 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4072 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4073 } 4074 4075 synchronized (mPackages) { 4076 boolean changed = false; 4077 final int packageCount = mPackages.size(); 4078 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4079 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4080 SettingBase sb = (SettingBase) pkg.mExtras; 4081 if (sb == null) { 4082 continue; 4083 } 4084 PermissionsState permissionsState = sb.getPermissionsState(); 4085 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4086 userId, flagMask, flagValues); 4087 } 4088 if (changed) { 4089 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4090 } 4091 } 4092 } 4093 4094 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4095 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4096 != PackageManager.PERMISSION_GRANTED 4097 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4098 != PackageManager.PERMISSION_GRANTED) { 4099 throw new SecurityException(message + " requires " 4100 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4101 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4102 } 4103 } 4104 4105 @Override 4106 public boolean shouldShowRequestPermissionRationale(String permissionName, 4107 String packageName, int userId) { 4108 if (UserHandle.getCallingUserId() != userId) { 4109 mContext.enforceCallingPermission( 4110 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4111 "canShowRequestPermissionRationale for user " + userId); 4112 } 4113 4114 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4115 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4116 return false; 4117 } 4118 4119 if (checkPermission(permissionName, packageName, userId) 4120 == PackageManager.PERMISSION_GRANTED) { 4121 return false; 4122 } 4123 4124 final int flags; 4125 4126 final long identity = Binder.clearCallingIdentity(); 4127 try { 4128 flags = getPermissionFlags(permissionName, 4129 packageName, userId); 4130 } finally { 4131 Binder.restoreCallingIdentity(identity); 4132 } 4133 4134 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4135 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4136 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4137 4138 if ((flags & fixedFlags) != 0) { 4139 return false; 4140 } 4141 4142 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4143 } 4144 4145 @Override 4146 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4147 mContext.enforceCallingOrSelfPermission( 4148 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4149 "addOnPermissionsChangeListener"); 4150 4151 synchronized (mPackages) { 4152 mOnPermissionChangeListeners.addListenerLocked(listener); 4153 } 4154 } 4155 4156 @Override 4157 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4158 synchronized (mPackages) { 4159 mOnPermissionChangeListeners.removeListenerLocked(listener); 4160 } 4161 } 4162 4163 @Override 4164 public boolean isProtectedBroadcast(String actionName) { 4165 synchronized (mPackages) { 4166 if (mProtectedBroadcasts.contains(actionName)) { 4167 return true; 4168 } else if (actionName != null) { 4169 // TODO: remove these terrible hacks 4170 if (actionName.startsWith("android.net.netmon.lingerExpired") 4171 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) { 4172 return true; 4173 } 4174 } 4175 } 4176 return false; 4177 } 4178 4179 @Override 4180 public int checkSignatures(String pkg1, String pkg2) { 4181 synchronized (mPackages) { 4182 final PackageParser.Package p1 = mPackages.get(pkg1); 4183 final PackageParser.Package p2 = mPackages.get(pkg2); 4184 if (p1 == null || p1.mExtras == null 4185 || p2 == null || p2.mExtras == null) { 4186 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4187 } 4188 return compareSignatures(p1.mSignatures, p2.mSignatures); 4189 } 4190 } 4191 4192 @Override 4193 public int checkUidSignatures(int uid1, int uid2) { 4194 // Map to base uids. 4195 uid1 = UserHandle.getAppId(uid1); 4196 uid2 = UserHandle.getAppId(uid2); 4197 // reader 4198 synchronized (mPackages) { 4199 Signature[] s1; 4200 Signature[] s2; 4201 Object obj = mSettings.getUserIdLPr(uid1); 4202 if (obj != null) { 4203 if (obj instanceof SharedUserSetting) { 4204 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4205 } else if (obj instanceof PackageSetting) { 4206 s1 = ((PackageSetting)obj).signatures.mSignatures; 4207 } else { 4208 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4209 } 4210 } else { 4211 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4212 } 4213 obj = mSettings.getUserIdLPr(uid2); 4214 if (obj != null) { 4215 if (obj instanceof SharedUserSetting) { 4216 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4217 } else if (obj instanceof PackageSetting) { 4218 s2 = ((PackageSetting)obj).signatures.mSignatures; 4219 } else { 4220 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4221 } 4222 } else { 4223 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4224 } 4225 return compareSignatures(s1, s2); 4226 } 4227 } 4228 4229 private void killUid(int appId, int userId, String reason) { 4230 final long identity = Binder.clearCallingIdentity(); 4231 try { 4232 IActivityManager am = ActivityManagerNative.getDefault(); 4233 if (am != null) { 4234 try { 4235 am.killUid(appId, userId, reason); 4236 } catch (RemoteException e) { 4237 /* ignore - same process */ 4238 } 4239 } 4240 } finally { 4241 Binder.restoreCallingIdentity(identity); 4242 } 4243 } 4244 4245 /** 4246 * Compares two sets of signatures. Returns: 4247 * <br /> 4248 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4249 * <br /> 4250 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4251 * <br /> 4252 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4253 * <br /> 4254 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4255 * <br /> 4256 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4257 */ 4258 static int compareSignatures(Signature[] s1, Signature[] s2) { 4259 if (s1 == null) { 4260 return s2 == null 4261 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4262 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4263 } 4264 4265 if (s2 == null) { 4266 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4267 } 4268 4269 if (s1.length != s2.length) { 4270 return PackageManager.SIGNATURE_NO_MATCH; 4271 } 4272 4273 // Since both signature sets are of size 1, we can compare without HashSets. 4274 if (s1.length == 1) { 4275 return s1[0].equals(s2[0]) ? 4276 PackageManager.SIGNATURE_MATCH : 4277 PackageManager.SIGNATURE_NO_MATCH; 4278 } 4279 4280 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4281 for (Signature sig : s1) { 4282 set1.add(sig); 4283 } 4284 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4285 for (Signature sig : s2) { 4286 set2.add(sig); 4287 } 4288 // Make sure s2 contains all signatures in s1. 4289 if (set1.equals(set2)) { 4290 return PackageManager.SIGNATURE_MATCH; 4291 } 4292 return PackageManager.SIGNATURE_NO_MATCH; 4293 } 4294 4295 /** 4296 * If the database version for this type of package (internal storage or 4297 * external storage) is less than the version where package signatures 4298 * were updated, return true. 4299 */ 4300 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4301 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4302 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4303 } 4304 4305 /** 4306 * Used for backward compatibility to make sure any packages with 4307 * certificate chains get upgraded to the new style. {@code existingSigs} 4308 * will be in the old format (since they were stored on disk from before the 4309 * system upgrade) and {@code scannedSigs} will be in the newer format. 4310 */ 4311 private int compareSignaturesCompat(PackageSignatures existingSigs, 4312 PackageParser.Package scannedPkg) { 4313 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4314 return PackageManager.SIGNATURE_NO_MATCH; 4315 } 4316 4317 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4318 for (Signature sig : existingSigs.mSignatures) { 4319 existingSet.add(sig); 4320 } 4321 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4322 for (Signature sig : scannedPkg.mSignatures) { 4323 try { 4324 Signature[] chainSignatures = sig.getChainSignatures(); 4325 for (Signature chainSig : chainSignatures) { 4326 scannedCompatSet.add(chainSig); 4327 } 4328 } catch (CertificateEncodingException e) { 4329 scannedCompatSet.add(sig); 4330 } 4331 } 4332 /* 4333 * Make sure the expanded scanned set contains all signatures in the 4334 * existing one. 4335 */ 4336 if (scannedCompatSet.equals(existingSet)) { 4337 // Migrate the old signatures to the new scheme. 4338 existingSigs.assignSignatures(scannedPkg.mSignatures); 4339 // The new KeySets will be re-added later in the scanning process. 4340 synchronized (mPackages) { 4341 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4342 } 4343 return PackageManager.SIGNATURE_MATCH; 4344 } 4345 return PackageManager.SIGNATURE_NO_MATCH; 4346 } 4347 4348 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4349 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4350 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4351 } 4352 4353 private int compareSignaturesRecover(PackageSignatures existingSigs, 4354 PackageParser.Package scannedPkg) { 4355 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4356 return PackageManager.SIGNATURE_NO_MATCH; 4357 } 4358 4359 String msg = null; 4360 try { 4361 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4362 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4363 + scannedPkg.packageName); 4364 return PackageManager.SIGNATURE_MATCH; 4365 } 4366 } catch (CertificateException e) { 4367 msg = e.getMessage(); 4368 } 4369 4370 logCriticalInfo(Log.INFO, 4371 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4372 return PackageManager.SIGNATURE_NO_MATCH; 4373 } 4374 4375 @Override 4376 public String[] getPackagesForUid(int uid) { 4377 uid = UserHandle.getAppId(uid); 4378 // reader 4379 synchronized (mPackages) { 4380 Object obj = mSettings.getUserIdLPr(uid); 4381 if (obj instanceof SharedUserSetting) { 4382 final SharedUserSetting sus = (SharedUserSetting) obj; 4383 final int N = sus.packages.size(); 4384 final String[] res = new String[N]; 4385 final Iterator<PackageSetting> it = sus.packages.iterator(); 4386 int i = 0; 4387 while (it.hasNext()) { 4388 res[i++] = it.next().name; 4389 } 4390 return res; 4391 } else if (obj instanceof PackageSetting) { 4392 final PackageSetting ps = (PackageSetting) obj; 4393 return new String[] { ps.name }; 4394 } 4395 } 4396 return null; 4397 } 4398 4399 @Override 4400 public String getNameForUid(int uid) { 4401 // reader 4402 synchronized (mPackages) { 4403 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4404 if (obj instanceof SharedUserSetting) { 4405 final SharedUserSetting sus = (SharedUserSetting) obj; 4406 return sus.name + ":" + sus.userId; 4407 } else if (obj instanceof PackageSetting) { 4408 final PackageSetting ps = (PackageSetting) obj; 4409 return ps.name; 4410 } 4411 } 4412 return null; 4413 } 4414 4415 @Override 4416 public int getUidForSharedUser(String sharedUserName) { 4417 if(sharedUserName == null) { 4418 return -1; 4419 } 4420 // reader 4421 synchronized (mPackages) { 4422 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4423 if (suid == null) { 4424 return -1; 4425 } 4426 return suid.userId; 4427 } 4428 } 4429 4430 @Override 4431 public int getFlagsForUid(int uid) { 4432 synchronized (mPackages) { 4433 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4434 if (obj instanceof SharedUserSetting) { 4435 final SharedUserSetting sus = (SharedUserSetting) obj; 4436 return sus.pkgFlags; 4437 } else if (obj instanceof PackageSetting) { 4438 final PackageSetting ps = (PackageSetting) obj; 4439 return ps.pkgFlags; 4440 } 4441 } 4442 return 0; 4443 } 4444 4445 @Override 4446 public int getPrivateFlagsForUid(int uid) { 4447 synchronized (mPackages) { 4448 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4449 if (obj instanceof SharedUserSetting) { 4450 final SharedUserSetting sus = (SharedUserSetting) obj; 4451 return sus.pkgPrivateFlags; 4452 } else if (obj instanceof PackageSetting) { 4453 final PackageSetting ps = (PackageSetting) obj; 4454 return ps.pkgPrivateFlags; 4455 } 4456 } 4457 return 0; 4458 } 4459 4460 @Override 4461 public boolean isUidPrivileged(int uid) { 4462 uid = UserHandle.getAppId(uid); 4463 // reader 4464 synchronized (mPackages) { 4465 Object obj = mSettings.getUserIdLPr(uid); 4466 if (obj instanceof SharedUserSetting) { 4467 final SharedUserSetting sus = (SharedUserSetting) obj; 4468 final Iterator<PackageSetting> it = sus.packages.iterator(); 4469 while (it.hasNext()) { 4470 if (it.next().isPrivileged()) { 4471 return true; 4472 } 4473 } 4474 } else if (obj instanceof PackageSetting) { 4475 final PackageSetting ps = (PackageSetting) obj; 4476 return ps.isPrivileged(); 4477 } 4478 } 4479 return false; 4480 } 4481 4482 @Override 4483 public String[] getAppOpPermissionPackages(String permissionName) { 4484 synchronized (mPackages) { 4485 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4486 if (pkgs == null) { 4487 return null; 4488 } 4489 return pkgs.toArray(new String[pkgs.size()]); 4490 } 4491 } 4492 4493 @Override 4494 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4495 int flags, int userId) { 4496 if (!sUserManager.exists(userId)) return null; 4497 flags = updateFlagsForResolve(flags, userId, intent); 4498 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4499 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4500 final ResolveInfo bestChoice = 4501 chooseBestActivity(intent, resolvedType, flags, query, userId); 4502 4503 if (isEphemeralAllowed(intent, query, userId)) { 4504 final EphemeralResolveInfo ai = 4505 getEphemeralResolveInfo(intent, resolvedType, userId); 4506 if (ai != null) { 4507 if (DEBUG_EPHEMERAL) { 4508 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4509 } 4510 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4511 bestChoice.ephemeralResolveInfo = ai; 4512 } 4513 } 4514 return bestChoice; 4515 } 4516 4517 @Override 4518 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4519 IntentFilter filter, int match, ComponentName activity) { 4520 final int userId = UserHandle.getCallingUserId(); 4521 if (DEBUG_PREFERRED) { 4522 Log.v(TAG, "setLastChosenActivity intent=" + intent 4523 + " resolvedType=" + resolvedType 4524 + " flags=" + flags 4525 + " filter=" + filter 4526 + " match=" + match 4527 + " activity=" + activity); 4528 filter.dump(new PrintStreamPrinter(System.out), " "); 4529 } 4530 intent.setComponent(null); 4531 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4532 // Find any earlier preferred or last chosen entries and nuke them 4533 findPreferredActivity(intent, resolvedType, 4534 flags, query, 0, false, true, false, userId); 4535 // Add the new activity as the last chosen for this filter 4536 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4537 "Setting last chosen"); 4538 } 4539 4540 @Override 4541 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4542 final int userId = UserHandle.getCallingUserId(); 4543 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4544 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4545 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4546 false, false, false, userId); 4547 } 4548 4549 4550 private boolean isEphemeralAllowed( 4551 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4552 // Short circuit and return early if possible. 4553 if (DISABLE_EPHEMERAL_APPS) { 4554 return false; 4555 } 4556 final int callingUser = UserHandle.getCallingUserId(); 4557 if (callingUser != UserHandle.USER_SYSTEM) { 4558 return false; 4559 } 4560 if (mEphemeralResolverConnection == null) { 4561 return false; 4562 } 4563 if (intent.getComponent() != null) { 4564 return false; 4565 } 4566 if (intent.getPackage() != null) { 4567 return false; 4568 } 4569 final boolean isWebUri = hasWebURI(intent); 4570 if (!isWebUri) { 4571 return false; 4572 } 4573 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4574 synchronized (mPackages) { 4575 final int count = resolvedActivites.size(); 4576 for (int n = 0; n < count; n++) { 4577 ResolveInfo info = resolvedActivites.get(n); 4578 String packageName = info.activityInfo.packageName; 4579 PackageSetting ps = mSettings.mPackages.get(packageName); 4580 if (ps != null) { 4581 // Try to get the status from User settings first 4582 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4583 int status = (int) (packedStatus >> 32); 4584 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4585 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4586 if (DEBUG_EPHEMERAL) { 4587 Slog.v(TAG, "DENY ephemeral apps;" 4588 + " pkg: " + packageName + ", status: " + status); 4589 } 4590 return false; 4591 } 4592 } 4593 } 4594 } 4595 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4596 return true; 4597 } 4598 4599 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4600 int userId) { 4601 MessageDigest digest = null; 4602 try { 4603 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4604 } catch (NoSuchAlgorithmException e) { 4605 // If we can't create a digest, ignore ephemeral apps. 4606 return null; 4607 } 4608 4609 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4610 final byte[] digestBytes = digest.digest(hostBytes); 4611 int shaPrefix = 4612 digestBytes[0] << 24 4613 | digestBytes[1] << 16 4614 | digestBytes[2] << 8 4615 | digestBytes[3] << 0; 4616 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4617 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4618 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4619 // No hash prefix match; there are no ephemeral apps for this domain. 4620 return null; 4621 } 4622 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4623 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4624 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4625 continue; 4626 } 4627 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4628 // No filters; this should never happen. 4629 if (filters.isEmpty()) { 4630 continue; 4631 } 4632 // We have a domain match; resolve the filters to see if anything matches. 4633 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4634 for (int j = filters.size() - 1; j >= 0; --j) { 4635 final EphemeralResolveIntentInfo intentInfo = 4636 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4637 ephemeralResolver.addFilter(intentInfo); 4638 } 4639 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4640 intent, resolvedType, false /*defaultOnly*/, userId); 4641 if (!matchedResolveInfoList.isEmpty()) { 4642 return matchedResolveInfoList.get(0); 4643 } 4644 } 4645 // Hash or filter mis-match; no ephemeral apps for this domain. 4646 return null; 4647 } 4648 4649 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4650 int flags, List<ResolveInfo> query, int userId) { 4651 if (query != null) { 4652 final int N = query.size(); 4653 if (N == 1) { 4654 return query.get(0); 4655 } else if (N > 1) { 4656 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4657 // If there is more than one activity with the same priority, 4658 // then let the user decide between them. 4659 ResolveInfo r0 = query.get(0); 4660 ResolveInfo r1 = query.get(1); 4661 if (DEBUG_INTENT_MATCHING || debug) { 4662 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4663 + r1.activityInfo.name + "=" + r1.priority); 4664 } 4665 // If the first activity has a higher priority, or a different 4666 // default, then it is always desirable to pick it. 4667 if (r0.priority != r1.priority 4668 || r0.preferredOrder != r1.preferredOrder 4669 || r0.isDefault != r1.isDefault) { 4670 return query.get(0); 4671 } 4672 // If we have saved a preference for a preferred activity for 4673 // this Intent, use that. 4674 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4675 flags, query, r0.priority, true, false, debug, userId); 4676 if (ri != null) { 4677 return ri; 4678 } 4679 ri = new ResolveInfo(mResolveInfo); 4680 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4681 ri.activityInfo.applicationInfo = new ApplicationInfo( 4682 ri.activityInfo.applicationInfo); 4683 if (userId != 0) { 4684 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4685 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4686 } 4687 // Make sure that the resolver is displayable in car mode 4688 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4689 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4690 return ri; 4691 } 4692 } 4693 return null; 4694 } 4695 4696 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4697 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4698 final int N = query.size(); 4699 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4700 .get(userId); 4701 // Get the list of persistent preferred activities that handle the intent 4702 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4703 List<PersistentPreferredActivity> pprefs = ppir != null 4704 ? ppir.queryIntent(intent, resolvedType, 4705 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4706 : null; 4707 if (pprefs != null && pprefs.size() > 0) { 4708 final int M = pprefs.size(); 4709 for (int i=0; i<M; i++) { 4710 final PersistentPreferredActivity ppa = pprefs.get(i); 4711 if (DEBUG_PREFERRED || debug) { 4712 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4713 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4714 + "\n component=" + ppa.mComponent); 4715 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4716 } 4717 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4718 flags | MATCH_DISABLED_COMPONENTS, userId); 4719 if (DEBUG_PREFERRED || debug) { 4720 Slog.v(TAG, "Found persistent preferred activity:"); 4721 if (ai != null) { 4722 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4723 } else { 4724 Slog.v(TAG, " null"); 4725 } 4726 } 4727 if (ai == null) { 4728 // This previously registered persistent preferred activity 4729 // component is no longer known. Ignore it and do NOT remove it. 4730 continue; 4731 } 4732 for (int j=0; j<N; j++) { 4733 final ResolveInfo ri = query.get(j); 4734 if (!ri.activityInfo.applicationInfo.packageName 4735 .equals(ai.applicationInfo.packageName)) { 4736 continue; 4737 } 4738 if (!ri.activityInfo.name.equals(ai.name)) { 4739 continue; 4740 } 4741 // Found a persistent preference that can handle the intent. 4742 if (DEBUG_PREFERRED || debug) { 4743 Slog.v(TAG, "Returning persistent preferred activity: " + 4744 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4745 } 4746 return ri; 4747 } 4748 } 4749 } 4750 return null; 4751 } 4752 4753 // TODO: handle preferred activities missing while user has amnesia 4754 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4755 List<ResolveInfo> query, int priority, boolean always, 4756 boolean removeMatches, boolean debug, int userId) { 4757 if (!sUserManager.exists(userId)) return null; 4758 flags = updateFlagsForResolve(flags, userId, intent); 4759 // writer 4760 synchronized (mPackages) { 4761 if (intent.getSelector() != null) { 4762 intent = intent.getSelector(); 4763 } 4764 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4765 4766 // Try to find a matching persistent preferred activity. 4767 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4768 debug, userId); 4769 4770 // If a persistent preferred activity matched, use it. 4771 if (pri != null) { 4772 return pri; 4773 } 4774 4775 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4776 // Get the list of preferred activities that handle the intent 4777 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4778 List<PreferredActivity> prefs = pir != null 4779 ? pir.queryIntent(intent, resolvedType, 4780 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4781 : null; 4782 if (prefs != null && prefs.size() > 0) { 4783 boolean changed = false; 4784 try { 4785 // First figure out how good the original match set is. 4786 // We will only allow preferred activities that came 4787 // from the same match quality. 4788 int match = 0; 4789 4790 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4791 4792 final int N = query.size(); 4793 for (int j=0; j<N; j++) { 4794 final ResolveInfo ri = query.get(j); 4795 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4796 + ": 0x" + Integer.toHexString(match)); 4797 if (ri.match > match) { 4798 match = ri.match; 4799 } 4800 } 4801 4802 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4803 + Integer.toHexString(match)); 4804 4805 match &= IntentFilter.MATCH_CATEGORY_MASK; 4806 final int M = prefs.size(); 4807 for (int i=0; i<M; i++) { 4808 final PreferredActivity pa = prefs.get(i); 4809 if (DEBUG_PREFERRED || debug) { 4810 Slog.v(TAG, "Checking PreferredActivity ds=" 4811 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4812 + "\n component=" + pa.mPref.mComponent); 4813 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4814 } 4815 if (pa.mPref.mMatch != match) { 4816 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4817 + Integer.toHexString(pa.mPref.mMatch)); 4818 continue; 4819 } 4820 // If it's not an "always" type preferred activity and that's what we're 4821 // looking for, skip it. 4822 if (always && !pa.mPref.mAlways) { 4823 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4824 continue; 4825 } 4826 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4827 flags | MATCH_DISABLED_COMPONENTS, userId); 4828 if (DEBUG_PREFERRED || debug) { 4829 Slog.v(TAG, "Found preferred activity:"); 4830 if (ai != null) { 4831 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4832 } else { 4833 Slog.v(TAG, " null"); 4834 } 4835 } 4836 if (ai == null) { 4837 // This previously registered preferred activity 4838 // component is no longer known. Most likely an update 4839 // to the app was installed and in the new version this 4840 // component no longer exists. Clean it up by removing 4841 // it from the preferred activities list, and skip it. 4842 Slog.w(TAG, "Removing dangling preferred activity: " 4843 + pa.mPref.mComponent); 4844 pir.removeFilter(pa); 4845 changed = true; 4846 continue; 4847 } 4848 for (int j=0; j<N; j++) { 4849 final ResolveInfo ri = query.get(j); 4850 if (!ri.activityInfo.applicationInfo.packageName 4851 .equals(ai.applicationInfo.packageName)) { 4852 continue; 4853 } 4854 if (!ri.activityInfo.name.equals(ai.name)) { 4855 continue; 4856 } 4857 4858 if (removeMatches) { 4859 pir.removeFilter(pa); 4860 changed = true; 4861 if (DEBUG_PREFERRED) { 4862 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4863 } 4864 break; 4865 } 4866 4867 // Okay we found a previously set preferred or last chosen app. 4868 // If the result set is different from when this 4869 // was created, we need to clear it and re-ask the 4870 // user their preference, if we're looking for an "always" type entry. 4871 if (always && !pa.mPref.sameSet(query)) { 4872 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4873 + intent + " type " + resolvedType); 4874 if (DEBUG_PREFERRED) { 4875 Slog.v(TAG, "Removing preferred activity since set changed " 4876 + pa.mPref.mComponent); 4877 } 4878 pir.removeFilter(pa); 4879 // Re-add the filter as a "last chosen" entry (!always) 4880 PreferredActivity lastChosen = new PreferredActivity( 4881 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4882 pir.addFilter(lastChosen); 4883 changed = true; 4884 return null; 4885 } 4886 4887 // Yay! Either the set matched or we're looking for the last chosen 4888 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4889 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4890 return ri; 4891 } 4892 } 4893 } finally { 4894 if (changed) { 4895 if (DEBUG_PREFERRED) { 4896 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4897 } 4898 scheduleWritePackageRestrictionsLocked(userId); 4899 } 4900 } 4901 } 4902 } 4903 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4904 return null; 4905 } 4906 4907 /* 4908 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4909 */ 4910 @Override 4911 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4912 int targetUserId) { 4913 mContext.enforceCallingOrSelfPermission( 4914 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4915 List<CrossProfileIntentFilter> matches = 4916 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4917 if (matches != null) { 4918 int size = matches.size(); 4919 for (int i = 0; i < size; i++) { 4920 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4921 } 4922 } 4923 if (hasWebURI(intent)) { 4924 // cross-profile app linking works only towards the parent. 4925 final UserInfo parent = getProfileParent(sourceUserId); 4926 synchronized(mPackages) { 4927 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4928 intent, resolvedType, 0, sourceUserId, parent.id); 4929 return xpDomainInfo != null; 4930 } 4931 } 4932 return false; 4933 } 4934 4935 private UserInfo getProfileParent(int userId) { 4936 final long identity = Binder.clearCallingIdentity(); 4937 try { 4938 return sUserManager.getProfileParent(userId); 4939 } finally { 4940 Binder.restoreCallingIdentity(identity); 4941 } 4942 } 4943 4944 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4945 String resolvedType, int userId) { 4946 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4947 if (resolver != null) { 4948 return resolver.queryIntent(intent, resolvedType, false, userId); 4949 } 4950 return null; 4951 } 4952 4953 @Override 4954 public List<ResolveInfo> queryIntentActivities(Intent intent, 4955 String resolvedType, int flags, int userId) { 4956 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4957 flags = updateFlagsForResolve(flags, userId, intent); 4958 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4959 ComponentName comp = intent.getComponent(); 4960 if (comp == null) { 4961 if (intent.getSelector() != null) { 4962 intent = intent.getSelector(); 4963 comp = intent.getComponent(); 4964 } 4965 } 4966 4967 if (comp != null) { 4968 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4969 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4970 if (ai != null) { 4971 final ResolveInfo ri = new ResolveInfo(); 4972 ri.activityInfo = ai; 4973 list.add(ri); 4974 } 4975 return list; 4976 } 4977 4978 // reader 4979 synchronized (mPackages) { 4980 final String pkgName = intent.getPackage(); 4981 if (pkgName == null) { 4982 List<CrossProfileIntentFilter> matchingFilters = 4983 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4984 // Check for results that need to skip the current profile. 4985 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4986 resolvedType, flags, userId); 4987 if (xpResolveInfo != null) { 4988 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4989 result.add(xpResolveInfo); 4990 return filterIfNotSystemUser(result, userId); 4991 } 4992 4993 // Check for results in the current profile. 4994 List<ResolveInfo> result = mActivities.queryIntent( 4995 intent, resolvedType, flags, userId); 4996 result = filterIfNotSystemUser(result, userId); 4997 4998 // Check for cross profile results. 4999 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5000 xpResolveInfo = queryCrossProfileIntents( 5001 matchingFilters, intent, resolvedType, flags, userId, 5002 hasNonNegativePriorityResult); 5003 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5004 boolean isVisibleToUser = filterIfNotSystemUser( 5005 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5006 if (isVisibleToUser) { 5007 result.add(xpResolveInfo); 5008 Collections.sort(result, mResolvePrioritySorter); 5009 } 5010 } 5011 if (hasWebURI(intent)) { 5012 CrossProfileDomainInfo xpDomainInfo = null; 5013 final UserInfo parent = getProfileParent(userId); 5014 if (parent != null) { 5015 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5016 flags, userId, parent.id); 5017 } 5018 if (xpDomainInfo != null) { 5019 if (xpResolveInfo != null) { 5020 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5021 // in the result. 5022 result.remove(xpResolveInfo); 5023 } 5024 if (result.size() == 0) { 5025 result.add(xpDomainInfo.resolveInfo); 5026 return result; 5027 } 5028 } else if (result.size() <= 1) { 5029 return result; 5030 } 5031 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5032 xpDomainInfo, userId); 5033 Collections.sort(result, mResolvePrioritySorter); 5034 } 5035 return result; 5036 } 5037 final PackageParser.Package pkg = mPackages.get(pkgName); 5038 if (pkg != null) { 5039 return filterIfNotSystemUser( 5040 mActivities.queryIntentForPackage( 5041 intent, resolvedType, flags, pkg.activities, userId), 5042 userId); 5043 } 5044 return new ArrayList<ResolveInfo>(); 5045 } 5046 } 5047 5048 private static class CrossProfileDomainInfo { 5049 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5050 ResolveInfo resolveInfo; 5051 /* Best domain verification status of the activities found in the other profile */ 5052 int bestDomainVerificationStatus; 5053 } 5054 5055 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5056 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5057 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5058 sourceUserId)) { 5059 return null; 5060 } 5061 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5062 resolvedType, flags, parentUserId); 5063 5064 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5065 return null; 5066 } 5067 CrossProfileDomainInfo result = null; 5068 int size = resultTargetUser.size(); 5069 for (int i = 0; i < size; i++) { 5070 ResolveInfo riTargetUser = resultTargetUser.get(i); 5071 // Intent filter verification is only for filters that specify a host. So don't return 5072 // those that handle all web uris. 5073 if (riTargetUser.handleAllWebDataURI) { 5074 continue; 5075 } 5076 String packageName = riTargetUser.activityInfo.packageName; 5077 PackageSetting ps = mSettings.mPackages.get(packageName); 5078 if (ps == null) { 5079 continue; 5080 } 5081 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5082 int status = (int)(verificationState >> 32); 5083 if (result == null) { 5084 result = new CrossProfileDomainInfo(); 5085 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5086 sourceUserId, parentUserId); 5087 result.bestDomainVerificationStatus = status; 5088 } else { 5089 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5090 result.bestDomainVerificationStatus); 5091 } 5092 } 5093 // Don't consider matches with status NEVER across profiles. 5094 if (result != null && result.bestDomainVerificationStatus 5095 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5096 return null; 5097 } 5098 return result; 5099 } 5100 5101 /** 5102 * Verification statuses are ordered from the worse to the best, except for 5103 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5104 */ 5105 private int bestDomainVerificationStatus(int status1, int status2) { 5106 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5107 return status2; 5108 } 5109 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5110 return status1; 5111 } 5112 return (int) MathUtils.max(status1, status2); 5113 } 5114 5115 private boolean isUserEnabled(int userId) { 5116 long callingId = Binder.clearCallingIdentity(); 5117 try { 5118 UserInfo userInfo = sUserManager.getUserInfo(userId); 5119 return userInfo != null && userInfo.isEnabled(); 5120 } finally { 5121 Binder.restoreCallingIdentity(callingId); 5122 } 5123 } 5124 5125 /** 5126 * Filter out activities with systemUserOnly flag set, when current user is not System. 5127 * 5128 * @return filtered list 5129 */ 5130 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5131 if (userId == UserHandle.USER_SYSTEM) { 5132 return resolveInfos; 5133 } 5134 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5135 ResolveInfo info = resolveInfos.get(i); 5136 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5137 resolveInfos.remove(i); 5138 } 5139 } 5140 return resolveInfos; 5141 } 5142 5143 /** 5144 * @param resolveInfos list of resolve infos in descending priority order 5145 * @return if the list contains a resolve info with non-negative priority 5146 */ 5147 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5148 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5149 } 5150 5151 private static boolean hasWebURI(Intent intent) { 5152 if (intent.getData() == null) { 5153 return false; 5154 } 5155 final String scheme = intent.getScheme(); 5156 if (TextUtils.isEmpty(scheme)) { 5157 return false; 5158 } 5159 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5160 } 5161 5162 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5163 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5164 int userId) { 5165 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5166 5167 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5168 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5169 candidates.size()); 5170 } 5171 5172 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5173 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5174 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5175 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5176 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5177 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5178 5179 synchronized (mPackages) { 5180 final int count = candidates.size(); 5181 // First, try to use linked apps. Partition the candidates into four lists: 5182 // one for the final results, one for the "do not use ever", one for "undefined status" 5183 // and finally one for "browser app type". 5184 for (int n=0; n<count; n++) { 5185 ResolveInfo info = candidates.get(n); 5186 String packageName = info.activityInfo.packageName; 5187 PackageSetting ps = mSettings.mPackages.get(packageName); 5188 if (ps != null) { 5189 // Add to the special match all list (Browser use case) 5190 if (info.handleAllWebDataURI) { 5191 matchAllList.add(info); 5192 continue; 5193 } 5194 // Try to get the status from User settings first 5195 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5196 int status = (int)(packedStatus >> 32); 5197 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5198 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5199 if (DEBUG_DOMAIN_VERIFICATION) { 5200 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5201 + " : linkgen=" + linkGeneration); 5202 } 5203 // Use link-enabled generation as preferredOrder, i.e. 5204 // prefer newly-enabled over earlier-enabled. 5205 info.preferredOrder = linkGeneration; 5206 alwaysList.add(info); 5207 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5208 if (DEBUG_DOMAIN_VERIFICATION) { 5209 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5210 } 5211 neverList.add(info); 5212 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5213 if (DEBUG_DOMAIN_VERIFICATION) { 5214 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5215 } 5216 alwaysAskList.add(info); 5217 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5218 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5219 if (DEBUG_DOMAIN_VERIFICATION) { 5220 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5221 } 5222 undefinedList.add(info); 5223 } 5224 } 5225 } 5226 5227 // We'll want to include browser possibilities in a few cases 5228 boolean includeBrowser = false; 5229 5230 // First try to add the "always" resolution(s) for the current user, if any 5231 if (alwaysList.size() > 0) { 5232 result.addAll(alwaysList); 5233 } else { 5234 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5235 result.addAll(undefinedList); 5236 // Maybe add one for the other profile. 5237 if (xpDomainInfo != null && ( 5238 xpDomainInfo.bestDomainVerificationStatus 5239 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5240 result.add(xpDomainInfo.resolveInfo); 5241 } 5242 includeBrowser = true; 5243 } 5244 5245 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5246 // If there were 'always' entries their preferred order has been set, so we also 5247 // back that off to make the alternatives equivalent 5248 if (alwaysAskList.size() > 0) { 5249 for (ResolveInfo i : result) { 5250 i.preferredOrder = 0; 5251 } 5252 result.addAll(alwaysAskList); 5253 includeBrowser = true; 5254 } 5255 5256 if (includeBrowser) { 5257 // Also add browsers (all of them or only the default one) 5258 if (DEBUG_DOMAIN_VERIFICATION) { 5259 Slog.v(TAG, " ...including browsers in candidate set"); 5260 } 5261 if ((matchFlags & MATCH_ALL) != 0) { 5262 result.addAll(matchAllList); 5263 } else { 5264 // Browser/generic handling case. If there's a default browser, go straight 5265 // to that (but only if there is no other higher-priority match). 5266 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5267 int maxMatchPrio = 0; 5268 ResolveInfo defaultBrowserMatch = null; 5269 final int numCandidates = matchAllList.size(); 5270 for (int n = 0; n < numCandidates; n++) { 5271 ResolveInfo info = matchAllList.get(n); 5272 // track the highest overall match priority... 5273 if (info.priority > maxMatchPrio) { 5274 maxMatchPrio = info.priority; 5275 } 5276 // ...and the highest-priority default browser match 5277 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5278 if (defaultBrowserMatch == null 5279 || (defaultBrowserMatch.priority < info.priority)) { 5280 if (debug) { 5281 Slog.v(TAG, "Considering default browser match " + info); 5282 } 5283 defaultBrowserMatch = info; 5284 } 5285 } 5286 } 5287 if (defaultBrowserMatch != null 5288 && defaultBrowserMatch.priority >= maxMatchPrio 5289 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5290 { 5291 if (debug) { 5292 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5293 } 5294 result.add(defaultBrowserMatch); 5295 } else { 5296 result.addAll(matchAllList); 5297 } 5298 } 5299 5300 // If there is nothing selected, add all candidates and remove the ones that the user 5301 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5302 if (result.size() == 0) { 5303 result.addAll(candidates); 5304 result.removeAll(neverList); 5305 } 5306 } 5307 } 5308 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5309 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5310 result.size()); 5311 for (ResolveInfo info : result) { 5312 Slog.v(TAG, " + " + info.activityInfo); 5313 } 5314 } 5315 return result; 5316 } 5317 5318 // Returns a packed value as a long: 5319 // 5320 // high 'int'-sized word: link status: undefined/ask/never/always. 5321 // low 'int'-sized word: relative priority among 'always' results. 5322 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5323 long result = ps.getDomainVerificationStatusForUser(userId); 5324 // if none available, get the master status 5325 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5326 if (ps.getIntentFilterVerificationInfo() != null) { 5327 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5328 } 5329 } 5330 return result; 5331 } 5332 5333 private ResolveInfo querySkipCurrentProfileIntents( 5334 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5335 int flags, int sourceUserId) { 5336 if (matchingFilters != null) { 5337 int size = matchingFilters.size(); 5338 for (int i = 0; i < size; i ++) { 5339 CrossProfileIntentFilter filter = matchingFilters.get(i); 5340 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5341 // Checking if there are activities in the target user that can handle the 5342 // intent. 5343 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5344 resolvedType, flags, sourceUserId); 5345 if (resolveInfo != null) { 5346 return resolveInfo; 5347 } 5348 } 5349 } 5350 } 5351 return null; 5352 } 5353 5354 // Return matching ResolveInfo in target user if any. 5355 private ResolveInfo queryCrossProfileIntents( 5356 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5357 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5358 if (matchingFilters != null) { 5359 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5360 // match the same intent. For performance reasons, it is better not to 5361 // run queryIntent twice for the same userId 5362 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5363 int size = matchingFilters.size(); 5364 for (int i = 0; i < size; i++) { 5365 CrossProfileIntentFilter filter = matchingFilters.get(i); 5366 int targetUserId = filter.getTargetUserId(); 5367 boolean skipCurrentProfile = 5368 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5369 boolean skipCurrentProfileIfNoMatchFound = 5370 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5371 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5372 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5373 // Checking if there are activities in the target user that can handle the 5374 // intent. 5375 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5376 resolvedType, flags, sourceUserId); 5377 if (resolveInfo != null) return resolveInfo; 5378 alreadyTriedUserIds.put(targetUserId, true); 5379 } 5380 } 5381 } 5382 return null; 5383 } 5384 5385 /** 5386 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5387 * will forward the intent to the filter's target user. 5388 * Otherwise, returns null. 5389 */ 5390 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5391 String resolvedType, int flags, int sourceUserId) { 5392 int targetUserId = filter.getTargetUserId(); 5393 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5394 resolvedType, flags, targetUserId); 5395 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5396 // If all the matches in the target profile are suspended, return null. 5397 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5398 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5399 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5400 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5401 targetUserId); 5402 } 5403 } 5404 } 5405 return null; 5406 } 5407 5408 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5409 int sourceUserId, int targetUserId) { 5410 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5411 long ident = Binder.clearCallingIdentity(); 5412 boolean targetIsProfile; 5413 try { 5414 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5415 } finally { 5416 Binder.restoreCallingIdentity(ident); 5417 } 5418 String className; 5419 if (targetIsProfile) { 5420 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5421 } else { 5422 className = FORWARD_INTENT_TO_PARENT; 5423 } 5424 ComponentName forwardingActivityComponentName = new ComponentName( 5425 mAndroidApplication.packageName, className); 5426 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5427 sourceUserId); 5428 if (!targetIsProfile) { 5429 forwardingActivityInfo.showUserIcon = targetUserId; 5430 forwardingResolveInfo.noResourceId = true; 5431 } 5432 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5433 forwardingResolveInfo.priority = 0; 5434 forwardingResolveInfo.preferredOrder = 0; 5435 forwardingResolveInfo.match = 0; 5436 forwardingResolveInfo.isDefault = true; 5437 forwardingResolveInfo.filter = filter; 5438 forwardingResolveInfo.targetUserId = targetUserId; 5439 return forwardingResolveInfo; 5440 } 5441 5442 @Override 5443 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5444 Intent[] specifics, String[] specificTypes, Intent intent, 5445 String resolvedType, int flags, int userId) { 5446 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5447 flags = updateFlagsForResolve(flags, userId, intent); 5448 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5449 false, "query intent activity options"); 5450 final String resultsAction = intent.getAction(); 5451 5452 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5453 | PackageManager.GET_RESOLVED_FILTER, userId); 5454 5455 if (DEBUG_INTENT_MATCHING) { 5456 Log.v(TAG, "Query " + intent + ": " + results); 5457 } 5458 5459 int specificsPos = 0; 5460 int N; 5461 5462 // todo: note that the algorithm used here is O(N^2). This 5463 // isn't a problem in our current environment, but if we start running 5464 // into situations where we have more than 5 or 10 matches then this 5465 // should probably be changed to something smarter... 5466 5467 // First we go through and resolve each of the specific items 5468 // that were supplied, taking care of removing any corresponding 5469 // duplicate items in the generic resolve list. 5470 if (specifics != null) { 5471 for (int i=0; i<specifics.length; i++) { 5472 final Intent sintent = specifics[i]; 5473 if (sintent == null) { 5474 continue; 5475 } 5476 5477 if (DEBUG_INTENT_MATCHING) { 5478 Log.v(TAG, "Specific #" + i + ": " + sintent); 5479 } 5480 5481 String action = sintent.getAction(); 5482 if (resultsAction != null && resultsAction.equals(action)) { 5483 // If this action was explicitly requested, then don't 5484 // remove things that have it. 5485 action = null; 5486 } 5487 5488 ResolveInfo ri = null; 5489 ActivityInfo ai = null; 5490 5491 ComponentName comp = sintent.getComponent(); 5492 if (comp == null) { 5493 ri = resolveIntent( 5494 sintent, 5495 specificTypes != null ? specificTypes[i] : null, 5496 flags, userId); 5497 if (ri == null) { 5498 continue; 5499 } 5500 if (ri == mResolveInfo) { 5501 // ACK! Must do something better with this. 5502 } 5503 ai = ri.activityInfo; 5504 comp = new ComponentName(ai.applicationInfo.packageName, 5505 ai.name); 5506 } else { 5507 ai = getActivityInfo(comp, flags, userId); 5508 if (ai == null) { 5509 continue; 5510 } 5511 } 5512 5513 // Look for any generic query activities that are duplicates 5514 // of this specific one, and remove them from the results. 5515 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5516 N = results.size(); 5517 int j; 5518 for (j=specificsPos; j<N; j++) { 5519 ResolveInfo sri = results.get(j); 5520 if ((sri.activityInfo.name.equals(comp.getClassName()) 5521 && sri.activityInfo.applicationInfo.packageName.equals( 5522 comp.getPackageName())) 5523 || (action != null && sri.filter.matchAction(action))) { 5524 results.remove(j); 5525 if (DEBUG_INTENT_MATCHING) Log.v( 5526 TAG, "Removing duplicate item from " + j 5527 + " due to specific " + specificsPos); 5528 if (ri == null) { 5529 ri = sri; 5530 } 5531 j--; 5532 N--; 5533 } 5534 } 5535 5536 // Add this specific item to its proper place. 5537 if (ri == null) { 5538 ri = new ResolveInfo(); 5539 ri.activityInfo = ai; 5540 } 5541 results.add(specificsPos, ri); 5542 ri.specificIndex = i; 5543 specificsPos++; 5544 } 5545 } 5546 5547 // Now we go through the remaining generic results and remove any 5548 // duplicate actions that are found here. 5549 N = results.size(); 5550 for (int i=specificsPos; i<N-1; i++) { 5551 final ResolveInfo rii = results.get(i); 5552 if (rii.filter == null) { 5553 continue; 5554 } 5555 5556 // Iterate over all of the actions of this result's intent 5557 // filter... typically this should be just one. 5558 final Iterator<String> it = rii.filter.actionsIterator(); 5559 if (it == null) { 5560 continue; 5561 } 5562 while (it.hasNext()) { 5563 final String action = it.next(); 5564 if (resultsAction != null && resultsAction.equals(action)) { 5565 // If this action was explicitly requested, then don't 5566 // remove things that have it. 5567 continue; 5568 } 5569 for (int j=i+1; j<N; j++) { 5570 final ResolveInfo rij = results.get(j); 5571 if (rij.filter != null && rij.filter.hasAction(action)) { 5572 results.remove(j); 5573 if (DEBUG_INTENT_MATCHING) Log.v( 5574 TAG, "Removing duplicate item from " + j 5575 + " due to action " + action + " at " + i); 5576 j--; 5577 N--; 5578 } 5579 } 5580 } 5581 5582 // If the caller didn't request filter information, drop it now 5583 // so we don't have to marshall/unmarshall it. 5584 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5585 rii.filter = null; 5586 } 5587 } 5588 5589 // Filter out the caller activity if so requested. 5590 if (caller != null) { 5591 N = results.size(); 5592 for (int i=0; i<N; i++) { 5593 ActivityInfo ainfo = results.get(i).activityInfo; 5594 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5595 && caller.getClassName().equals(ainfo.name)) { 5596 results.remove(i); 5597 break; 5598 } 5599 } 5600 } 5601 5602 // If the caller didn't request filter information, 5603 // drop them now so we don't have to 5604 // marshall/unmarshall it. 5605 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5606 N = results.size(); 5607 for (int i=0; i<N; i++) { 5608 results.get(i).filter = null; 5609 } 5610 } 5611 5612 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5613 return results; 5614 } 5615 5616 @Override 5617 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5618 int userId) { 5619 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5620 flags = updateFlagsForResolve(flags, userId, intent); 5621 ComponentName comp = intent.getComponent(); 5622 if (comp == null) { 5623 if (intent.getSelector() != null) { 5624 intent = intent.getSelector(); 5625 comp = intent.getComponent(); 5626 } 5627 } 5628 if (comp != null) { 5629 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5630 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5631 if (ai != null) { 5632 ResolveInfo ri = new ResolveInfo(); 5633 ri.activityInfo = ai; 5634 list.add(ri); 5635 } 5636 return list; 5637 } 5638 5639 // reader 5640 synchronized (mPackages) { 5641 String pkgName = intent.getPackage(); 5642 if (pkgName == null) { 5643 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5644 } 5645 final PackageParser.Package pkg = mPackages.get(pkgName); 5646 if (pkg != null) { 5647 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5648 userId); 5649 } 5650 return null; 5651 } 5652 } 5653 5654 @Override 5655 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5656 if (!sUserManager.exists(userId)) return null; 5657 flags = updateFlagsForResolve(flags, userId, intent); 5658 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5659 if (query != null) { 5660 if (query.size() >= 1) { 5661 // If there is more than one service with the same priority, 5662 // just arbitrarily pick the first one. 5663 return query.get(0); 5664 } 5665 } 5666 return null; 5667 } 5668 5669 @Override 5670 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5671 int userId) { 5672 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5673 flags = updateFlagsForResolve(flags, userId, intent); 5674 ComponentName comp = intent.getComponent(); 5675 if (comp == null) { 5676 if (intent.getSelector() != null) { 5677 intent = intent.getSelector(); 5678 comp = intent.getComponent(); 5679 } 5680 } 5681 if (comp != null) { 5682 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5683 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5684 if (si != null) { 5685 final ResolveInfo ri = new ResolveInfo(); 5686 ri.serviceInfo = si; 5687 list.add(ri); 5688 } 5689 return list; 5690 } 5691 5692 // reader 5693 synchronized (mPackages) { 5694 String pkgName = intent.getPackage(); 5695 if (pkgName == null) { 5696 return mServices.queryIntent(intent, resolvedType, flags, userId); 5697 } 5698 final PackageParser.Package pkg = mPackages.get(pkgName); 5699 if (pkg != null) { 5700 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5701 userId); 5702 } 5703 return null; 5704 } 5705 } 5706 5707 @Override 5708 public List<ResolveInfo> queryIntentContentProviders( 5709 Intent intent, String resolvedType, int flags, int userId) { 5710 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5711 flags = updateFlagsForResolve(flags, userId, intent); 5712 ComponentName comp = intent.getComponent(); 5713 if (comp == null) { 5714 if (intent.getSelector() != null) { 5715 intent = intent.getSelector(); 5716 comp = intent.getComponent(); 5717 } 5718 } 5719 if (comp != null) { 5720 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5721 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5722 if (pi != null) { 5723 final ResolveInfo ri = new ResolveInfo(); 5724 ri.providerInfo = pi; 5725 list.add(ri); 5726 } 5727 return list; 5728 } 5729 5730 // reader 5731 synchronized (mPackages) { 5732 String pkgName = intent.getPackage(); 5733 if (pkgName == null) { 5734 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5735 } 5736 final PackageParser.Package pkg = mPackages.get(pkgName); 5737 if (pkg != null) { 5738 return mProviders.queryIntentForPackage( 5739 intent, resolvedType, flags, pkg.providers, userId); 5740 } 5741 return null; 5742 } 5743 } 5744 5745 @Override 5746 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5747 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5748 flags = updateFlagsForPackage(flags, userId, null); 5749 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5750 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5751 5752 // writer 5753 synchronized (mPackages) { 5754 ArrayList<PackageInfo> list; 5755 if (listUninstalled) { 5756 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5757 for (PackageSetting ps : mSettings.mPackages.values()) { 5758 PackageInfo pi; 5759 if (ps.pkg != null) { 5760 pi = generatePackageInfo(ps.pkg, flags, userId); 5761 } else { 5762 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5763 } 5764 if (pi != null) { 5765 list.add(pi); 5766 } 5767 } 5768 } else { 5769 list = new ArrayList<PackageInfo>(mPackages.size()); 5770 for (PackageParser.Package p : mPackages.values()) { 5771 PackageInfo pi = generatePackageInfo(p, flags, userId); 5772 if (pi != null) { 5773 list.add(pi); 5774 } 5775 } 5776 } 5777 5778 return new ParceledListSlice<PackageInfo>(list); 5779 } 5780 } 5781 5782 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5783 String[] permissions, boolean[] tmp, int flags, int userId) { 5784 int numMatch = 0; 5785 final PermissionsState permissionsState = ps.getPermissionsState(); 5786 for (int i=0; i<permissions.length; i++) { 5787 final String permission = permissions[i]; 5788 if (permissionsState.hasPermission(permission, userId)) { 5789 tmp[i] = true; 5790 numMatch++; 5791 } else { 5792 tmp[i] = false; 5793 } 5794 } 5795 if (numMatch == 0) { 5796 return; 5797 } 5798 PackageInfo pi; 5799 if (ps.pkg != null) { 5800 pi = generatePackageInfo(ps.pkg, flags, userId); 5801 } else { 5802 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5803 } 5804 // The above might return null in cases of uninstalled apps or install-state 5805 // skew across users/profiles. 5806 if (pi != null) { 5807 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5808 if (numMatch == permissions.length) { 5809 pi.requestedPermissions = permissions; 5810 } else { 5811 pi.requestedPermissions = new String[numMatch]; 5812 numMatch = 0; 5813 for (int i=0; i<permissions.length; i++) { 5814 if (tmp[i]) { 5815 pi.requestedPermissions[numMatch] = permissions[i]; 5816 numMatch++; 5817 } 5818 } 5819 } 5820 } 5821 list.add(pi); 5822 } 5823 } 5824 5825 @Override 5826 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5827 String[] permissions, int flags, int userId) { 5828 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5829 flags = updateFlagsForPackage(flags, userId, permissions); 5830 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5831 5832 // writer 5833 synchronized (mPackages) { 5834 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5835 boolean[] tmpBools = new boolean[permissions.length]; 5836 if (listUninstalled) { 5837 for (PackageSetting ps : mSettings.mPackages.values()) { 5838 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5839 } 5840 } else { 5841 for (PackageParser.Package pkg : mPackages.values()) { 5842 PackageSetting ps = (PackageSetting)pkg.mExtras; 5843 if (ps != null) { 5844 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5845 userId); 5846 } 5847 } 5848 } 5849 5850 return new ParceledListSlice<PackageInfo>(list); 5851 } 5852 } 5853 5854 @Override 5855 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5856 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5857 flags = updateFlagsForApplication(flags, userId, null); 5858 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5859 5860 // writer 5861 synchronized (mPackages) { 5862 ArrayList<ApplicationInfo> list; 5863 if (listUninstalled) { 5864 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5865 for (PackageSetting ps : mSettings.mPackages.values()) { 5866 ApplicationInfo ai; 5867 if (ps.pkg != null) { 5868 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5869 ps.readUserState(userId), userId); 5870 } else { 5871 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5872 } 5873 if (ai != null) { 5874 list.add(ai); 5875 } 5876 } 5877 } else { 5878 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5879 for (PackageParser.Package p : mPackages.values()) { 5880 if (p.mExtras != null) { 5881 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5882 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5883 if (ai != null) { 5884 list.add(ai); 5885 } 5886 } 5887 } 5888 } 5889 5890 return new ParceledListSlice<ApplicationInfo>(list); 5891 } 5892 } 5893 5894 @Override 5895 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5896 if (DISABLE_EPHEMERAL_APPS) { 5897 return null; 5898 } 5899 5900 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5901 "getEphemeralApplications"); 5902 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5903 "getEphemeralApplications"); 5904 synchronized (mPackages) { 5905 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5906 .getEphemeralApplicationsLPw(userId); 5907 if (ephemeralApps != null) { 5908 return new ParceledListSlice<>(ephemeralApps); 5909 } 5910 } 5911 return null; 5912 } 5913 5914 @Override 5915 public boolean isEphemeralApplication(String packageName, int userId) { 5916 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5917 "isEphemeral"); 5918 if (DISABLE_EPHEMERAL_APPS) { 5919 return false; 5920 } 5921 5922 if (!isCallerSameApp(packageName)) { 5923 return false; 5924 } 5925 synchronized (mPackages) { 5926 PackageParser.Package pkg = mPackages.get(packageName); 5927 if (pkg != null) { 5928 return pkg.applicationInfo.isEphemeralApp(); 5929 } 5930 } 5931 return false; 5932 } 5933 5934 @Override 5935 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 5936 if (DISABLE_EPHEMERAL_APPS) { 5937 return null; 5938 } 5939 5940 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5941 "getCookie"); 5942 if (!isCallerSameApp(packageName)) { 5943 return null; 5944 } 5945 synchronized (mPackages) { 5946 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 5947 packageName, userId); 5948 } 5949 } 5950 5951 @Override 5952 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 5953 if (DISABLE_EPHEMERAL_APPS) { 5954 return true; 5955 } 5956 5957 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5958 "setCookie"); 5959 if (!isCallerSameApp(packageName)) { 5960 return false; 5961 } 5962 synchronized (mPackages) { 5963 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 5964 packageName, cookie, userId); 5965 } 5966 } 5967 5968 @Override 5969 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 5970 if (DISABLE_EPHEMERAL_APPS) { 5971 return null; 5972 } 5973 5974 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5975 "getEphemeralApplicationIcon"); 5976 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5977 "getEphemeralApplicationIcon"); 5978 synchronized (mPackages) { 5979 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 5980 packageName, userId); 5981 } 5982 } 5983 5984 private boolean isCallerSameApp(String packageName) { 5985 PackageParser.Package pkg = mPackages.get(packageName); 5986 return pkg != null 5987 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 5988 } 5989 5990 public List<ApplicationInfo> getPersistentApplications(int flags) { 5991 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5992 5993 // reader 5994 synchronized (mPackages) { 5995 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5996 final int userId = UserHandle.getCallingUserId(); 5997 while (i.hasNext()) { 5998 final PackageParser.Package p = i.next(); 5999 if (p.applicationInfo != null 6000 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 6001 && (!mSafeMode || isSystemApp(p))) { 6002 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6003 if (ps != null) { 6004 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6005 ps.readUserState(userId), userId); 6006 if (ai != null) { 6007 finalList.add(ai); 6008 } 6009 } 6010 } 6011 } 6012 } 6013 6014 return finalList; 6015 } 6016 6017 @Override 6018 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6019 if (!sUserManager.exists(userId)) return null; 6020 flags = updateFlagsForComponent(flags, userId, name); 6021 // reader 6022 synchronized (mPackages) { 6023 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6024 PackageSetting ps = provider != null 6025 ? mSettings.mPackages.get(provider.owner.packageName) 6026 : null; 6027 return ps != null 6028 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6029 ? PackageParser.generateProviderInfo(provider, flags, 6030 ps.readUserState(userId), userId) 6031 : null; 6032 } 6033 } 6034 6035 /** 6036 * @deprecated 6037 */ 6038 @Deprecated 6039 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6040 // reader 6041 synchronized (mPackages) { 6042 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6043 .entrySet().iterator(); 6044 final int userId = UserHandle.getCallingUserId(); 6045 while (i.hasNext()) { 6046 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6047 PackageParser.Provider p = entry.getValue(); 6048 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6049 6050 if (ps != null && p.syncable 6051 && (!mSafeMode || (p.info.applicationInfo.flags 6052 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6053 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6054 ps.readUserState(userId), userId); 6055 if (info != null) { 6056 outNames.add(entry.getKey()); 6057 outInfo.add(info); 6058 } 6059 } 6060 } 6061 } 6062 } 6063 6064 @Override 6065 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6066 int uid, int flags) { 6067 final int userId = processName != null ? UserHandle.getUserId(uid) 6068 : UserHandle.getCallingUserId(); 6069 if (!sUserManager.exists(userId)) return null; 6070 flags = updateFlagsForComponent(flags, userId, processName); 6071 6072 ArrayList<ProviderInfo> finalList = null; 6073 // reader 6074 synchronized (mPackages) { 6075 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6076 while (i.hasNext()) { 6077 final PackageParser.Provider p = i.next(); 6078 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6079 if (ps != null && p.info.authority != null 6080 && (processName == null 6081 || (p.info.processName.equals(processName) 6082 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6083 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6084 if (finalList == null) { 6085 finalList = new ArrayList<ProviderInfo>(3); 6086 } 6087 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6088 ps.readUserState(userId), userId); 6089 if (info != null) { 6090 finalList.add(info); 6091 } 6092 } 6093 } 6094 } 6095 6096 if (finalList != null) { 6097 Collections.sort(finalList, mProviderInitOrderSorter); 6098 return new ParceledListSlice<ProviderInfo>(finalList); 6099 } 6100 6101 return null; 6102 } 6103 6104 @Override 6105 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6106 // reader 6107 synchronized (mPackages) { 6108 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6109 return PackageParser.generateInstrumentationInfo(i, flags); 6110 } 6111 } 6112 6113 @Override 6114 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6115 int flags) { 6116 ArrayList<InstrumentationInfo> finalList = 6117 new ArrayList<InstrumentationInfo>(); 6118 6119 // reader 6120 synchronized (mPackages) { 6121 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6122 while (i.hasNext()) { 6123 final PackageParser.Instrumentation p = i.next(); 6124 if (targetPackage == null 6125 || targetPackage.equals(p.info.targetPackage)) { 6126 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6127 flags); 6128 if (ii != null) { 6129 finalList.add(ii); 6130 } 6131 } 6132 } 6133 } 6134 6135 return finalList; 6136 } 6137 6138 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6139 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6140 if (overlays == null) { 6141 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6142 return; 6143 } 6144 for (PackageParser.Package opkg : overlays.values()) { 6145 // Not much to do if idmap fails: we already logged the error 6146 // and we certainly don't want to abort installation of pkg simply 6147 // because an overlay didn't fit properly. For these reasons, 6148 // ignore the return value of createIdmapForPackagePairLI. 6149 createIdmapForPackagePairLI(pkg, opkg); 6150 } 6151 } 6152 6153 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6154 PackageParser.Package opkg) { 6155 if (!opkg.mTrustedOverlay) { 6156 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6157 opkg.baseCodePath + ": overlay not trusted"); 6158 return false; 6159 } 6160 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6161 if (overlaySet == null) { 6162 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6163 opkg.baseCodePath + " but target package has no known overlays"); 6164 return false; 6165 } 6166 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6167 // TODO: generate idmap for split APKs 6168 try { 6169 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6170 } catch (InstallerException e) { 6171 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6172 + opkg.baseCodePath); 6173 return false; 6174 } 6175 PackageParser.Package[] overlayArray = 6176 overlaySet.values().toArray(new PackageParser.Package[0]); 6177 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6178 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6179 return p1.mOverlayPriority - p2.mOverlayPriority; 6180 } 6181 }; 6182 Arrays.sort(overlayArray, cmp); 6183 6184 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6185 int i = 0; 6186 for (PackageParser.Package p : overlayArray) { 6187 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6188 } 6189 return true; 6190 } 6191 6192 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6193 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6194 try { 6195 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6196 } finally { 6197 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6198 } 6199 } 6200 6201 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6202 final File[] files = dir.listFiles(); 6203 if (ArrayUtils.isEmpty(files)) { 6204 Log.d(TAG, "No files in app dir " + dir); 6205 return; 6206 } 6207 6208 if (DEBUG_PACKAGE_SCANNING) { 6209 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6210 + " flags=0x" + Integer.toHexString(parseFlags)); 6211 } 6212 6213 for (File file : files) { 6214 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6215 && !PackageInstallerService.isStageName(file.getName()); 6216 if (!isPackage) { 6217 // Ignore entries which are not packages 6218 continue; 6219 } 6220 try { 6221 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6222 scanFlags, currentTime, null); 6223 } catch (PackageManagerException e) { 6224 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6225 6226 // Delete invalid userdata apps 6227 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6228 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6229 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6230 removeCodePathLI(file); 6231 } 6232 } 6233 } 6234 } 6235 6236 private static File getSettingsProblemFile() { 6237 File dataDir = Environment.getDataDirectory(); 6238 File systemDir = new File(dataDir, "system"); 6239 File fname = new File(systemDir, "uiderrors.txt"); 6240 return fname; 6241 } 6242 6243 static void reportSettingsProblem(int priority, String msg) { 6244 logCriticalInfo(priority, msg); 6245 } 6246 6247 static void logCriticalInfo(int priority, String msg) { 6248 Slog.println(priority, TAG, msg); 6249 EventLogTags.writePmCriticalInfo(msg); 6250 try { 6251 File fname = getSettingsProblemFile(); 6252 FileOutputStream out = new FileOutputStream(fname, true); 6253 PrintWriter pw = new FastPrintWriter(out); 6254 SimpleDateFormat formatter = new SimpleDateFormat(); 6255 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6256 pw.println(dateString + ": " + msg); 6257 pw.close(); 6258 FileUtils.setPermissions( 6259 fname.toString(), 6260 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6261 -1, -1); 6262 } catch (java.io.IOException e) { 6263 } 6264 } 6265 6266 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 6267 PackageParser.Package pkg, File srcFile, int parseFlags) 6268 throws PackageManagerException { 6269 if (ps != null 6270 && ps.codePath.equals(srcFile) 6271 && ps.timeStamp == srcFile.lastModified() 6272 && !isCompatSignatureUpdateNeeded(pkg) 6273 && !isRecoverSignatureUpdateNeeded(pkg)) { 6274 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6275 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6276 ArraySet<PublicKey> signingKs; 6277 synchronized (mPackages) { 6278 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6279 } 6280 if (ps.signatures.mSignatures != null 6281 && ps.signatures.mSignatures.length != 0 6282 && signingKs != null) { 6283 // Optimization: reuse the existing cached certificates 6284 // if the package appears to be unchanged. 6285 pkg.mSignatures = ps.signatures.mSignatures; 6286 pkg.mSigningKeys = signingKs; 6287 return; 6288 } 6289 6290 Slog.w(TAG, "PackageSetting for " + ps.name 6291 + " is missing signatures. Collecting certs again to recover them."); 6292 } else { 6293 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6294 } 6295 6296 try { 6297 pp.collectCertificates(pkg, parseFlags); 6298 } catch (PackageParserException e) { 6299 throw PackageManagerException.from(e); 6300 } 6301 } 6302 6303 /** 6304 * Traces a package scan. 6305 * @see #scanPackageLI(File, int, int, long, UserHandle) 6306 */ 6307 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6308 long currentTime, UserHandle user) throws PackageManagerException { 6309 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6310 try { 6311 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6312 } finally { 6313 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6314 } 6315 } 6316 6317 /** 6318 * Scans a package and returns the newly parsed package. 6319 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6320 */ 6321 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6322 long currentTime, UserHandle user) throws PackageManagerException { 6323 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6324 parseFlags |= mDefParseFlags; 6325 PackageParser pp = new PackageParser(); 6326 pp.setSeparateProcesses(mSeparateProcesses); 6327 pp.setOnlyCoreApps(mOnlyCore); 6328 pp.setDisplayMetrics(mMetrics); 6329 6330 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6331 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6332 } 6333 6334 final PackageParser.Package pkg; 6335 try { 6336 pkg = pp.parsePackage(scanFile, parseFlags); 6337 } catch (PackageParserException e) { 6338 throw PackageManagerException.from(e); 6339 } 6340 6341 PackageSetting ps = null; 6342 PackageSetting updatedPkg; 6343 // reader 6344 synchronized (mPackages) { 6345 // Look to see if we already know about this package. 6346 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6347 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6348 // This package has been renamed to its original name. Let's 6349 // use that. 6350 ps = mSettings.peekPackageLPr(oldName); 6351 } 6352 // If there was no original package, see one for the real package name. 6353 if (ps == null) { 6354 ps = mSettings.peekPackageLPr(pkg.packageName); 6355 } 6356 // Check to see if this package could be hiding/updating a system 6357 // package. Must look for it either under the original or real 6358 // package name depending on our state. 6359 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6360 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6361 } 6362 boolean updatedPkgBetter = false; 6363 // First check if this is a system package that may involve an update 6364 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6365 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6366 // it needs to drop FLAG_PRIVILEGED. 6367 if (locationIsPrivileged(scanFile)) { 6368 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6369 } else { 6370 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6371 } 6372 6373 if (ps != null && !ps.codePath.equals(scanFile)) { 6374 // The path has changed from what was last scanned... check the 6375 // version of the new path against what we have stored to determine 6376 // what to do. 6377 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6378 if (pkg.mVersionCode <= ps.versionCode) { 6379 // The system package has been updated and the code path does not match 6380 // Ignore entry. Skip it. 6381 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6382 + " ignored: updated version " + ps.versionCode 6383 + " better than this " + pkg.mVersionCode); 6384 if (!updatedPkg.codePath.equals(scanFile)) { 6385 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6386 + ps.name + " changing from " + updatedPkg.codePathString 6387 + " to " + scanFile); 6388 updatedPkg.codePath = scanFile; 6389 updatedPkg.codePathString = scanFile.toString(); 6390 updatedPkg.resourcePath = scanFile; 6391 updatedPkg.resourcePathString = scanFile.toString(); 6392 } 6393 updatedPkg.pkg = pkg; 6394 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6395 "Package " + ps.name + " at " + scanFile 6396 + " ignored: updated version " + ps.versionCode 6397 + " better than this " + pkg.mVersionCode); 6398 } else { 6399 // The current app on the system partition is better than 6400 // what we have updated to on the data partition; switch 6401 // back to the system partition version. 6402 // At this point, its safely assumed that package installation for 6403 // apps in system partition will go through. If not there won't be a working 6404 // version of the app 6405 // writer 6406 synchronized (mPackages) { 6407 // Just remove the loaded entries from package lists. 6408 mPackages.remove(ps.name); 6409 } 6410 6411 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6412 + " reverting from " + ps.codePathString 6413 + ": new version " + pkg.mVersionCode 6414 + " better than installed " + ps.versionCode); 6415 6416 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6417 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6418 synchronized (mInstallLock) { 6419 args.cleanUpResourcesLI(); 6420 } 6421 synchronized (mPackages) { 6422 mSettings.enableSystemPackageLPw(ps.name); 6423 } 6424 updatedPkgBetter = true; 6425 } 6426 } 6427 } 6428 6429 if (updatedPkg != null) { 6430 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6431 // initially 6432 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6433 6434 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6435 // flag set initially 6436 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6437 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6438 } 6439 } 6440 6441 // Verify certificates against what was last scanned 6442 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 6443 6444 /* 6445 * A new system app appeared, but we already had a non-system one of the 6446 * same name installed earlier. 6447 */ 6448 boolean shouldHideSystemApp = false; 6449 if (updatedPkg == null && ps != null 6450 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6451 /* 6452 * Check to make sure the signatures match first. If they don't, 6453 * wipe the installed application and its data. 6454 */ 6455 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6456 != PackageManager.SIGNATURE_MATCH) { 6457 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6458 + " signatures don't match existing userdata copy; removing"); 6459 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 6460 ps = null; 6461 } else { 6462 /* 6463 * If the newly-added system app is an older version than the 6464 * already installed version, hide it. It will be scanned later 6465 * and re-added like an update. 6466 */ 6467 if (pkg.mVersionCode <= ps.versionCode) { 6468 shouldHideSystemApp = true; 6469 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6470 + " but new version " + pkg.mVersionCode + " better than installed " 6471 + ps.versionCode + "; hiding system"); 6472 } else { 6473 /* 6474 * The newly found system app is a newer version that the 6475 * one previously installed. Simply remove the 6476 * already-installed application and replace it with our own 6477 * while keeping the application data. 6478 */ 6479 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6480 + " reverting from " + ps.codePathString + ": new version " 6481 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6482 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6483 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6484 synchronized (mInstallLock) { 6485 args.cleanUpResourcesLI(); 6486 } 6487 } 6488 } 6489 } 6490 6491 // The apk is forward locked (not public) if its code and resources 6492 // are kept in different files. (except for app in either system or 6493 // vendor path). 6494 // TODO grab this value from PackageSettings 6495 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6496 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6497 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6498 } 6499 } 6500 6501 // TODO: extend to support forward-locked splits 6502 String resourcePath = null; 6503 String baseResourcePath = null; 6504 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6505 if (ps != null && ps.resourcePathString != null) { 6506 resourcePath = ps.resourcePathString; 6507 baseResourcePath = ps.resourcePathString; 6508 } else { 6509 // Should not happen at all. Just log an error. 6510 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6511 } 6512 } else { 6513 resourcePath = pkg.codePath; 6514 baseResourcePath = pkg.baseCodePath; 6515 } 6516 6517 // Set application objects path explicitly. 6518 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6519 pkg.applicationInfo.setCodePath(pkg.codePath); 6520 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6521 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6522 pkg.applicationInfo.setResourcePath(resourcePath); 6523 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6524 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6525 6526 // Note that we invoke the following method only if we are about to unpack an application 6527 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6528 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6529 6530 /* 6531 * If the system app should be overridden by a previously installed 6532 * data, hide the system app now and let the /data/app scan pick it up 6533 * again. 6534 */ 6535 if (shouldHideSystemApp) { 6536 synchronized (mPackages) { 6537 mSettings.disableSystemPackageLPw(pkg.packageName); 6538 } 6539 } 6540 6541 return scannedPkg; 6542 } 6543 6544 private static String fixProcessName(String defProcessName, 6545 String processName, int uid) { 6546 if (processName == null) { 6547 return defProcessName; 6548 } 6549 return processName; 6550 } 6551 6552 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6553 throws PackageManagerException { 6554 if (pkgSetting.signatures.mSignatures != null) { 6555 // Already existing package. Make sure signatures match 6556 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6557 == PackageManager.SIGNATURE_MATCH; 6558 if (!match) { 6559 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6560 == PackageManager.SIGNATURE_MATCH; 6561 } 6562 if (!match) { 6563 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6564 == PackageManager.SIGNATURE_MATCH; 6565 } 6566 if (!match) { 6567 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6568 + pkg.packageName + " signatures do not match the " 6569 + "previously installed version; ignoring!"); 6570 } 6571 } 6572 6573 // Check for shared user signatures 6574 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6575 // Already existing package. Make sure signatures match 6576 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6577 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6578 if (!match) { 6579 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6580 == PackageManager.SIGNATURE_MATCH; 6581 } 6582 if (!match) { 6583 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6584 == PackageManager.SIGNATURE_MATCH; 6585 } 6586 if (!match) { 6587 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6588 "Package " + pkg.packageName 6589 + " has no signatures that match those in shared user " 6590 + pkgSetting.sharedUser.name + "; ignoring!"); 6591 } 6592 } 6593 } 6594 6595 /** 6596 * Enforces that only the system UID or root's UID can call a method exposed 6597 * via Binder. 6598 * 6599 * @param message used as message if SecurityException is thrown 6600 * @throws SecurityException if the caller is not system or root 6601 */ 6602 private static final void enforceSystemOrRoot(String message) { 6603 final int uid = Binder.getCallingUid(); 6604 if (uid != Process.SYSTEM_UID && uid != 0) { 6605 throw new SecurityException(message); 6606 } 6607 } 6608 6609 @Override 6610 public void performFstrimIfNeeded() { 6611 enforceSystemOrRoot("Only the system can request fstrim"); 6612 6613 // Before everything else, see whether we need to fstrim. 6614 try { 6615 IMountService ms = PackageHelper.getMountService(); 6616 if (ms != null) { 6617 final boolean isUpgrade = isUpgrade(); 6618 boolean doTrim = isUpgrade; 6619 if (doTrim) { 6620 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6621 } else { 6622 final long interval = android.provider.Settings.Global.getLong( 6623 mContext.getContentResolver(), 6624 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6625 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6626 if (interval > 0) { 6627 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6628 if (timeSinceLast > interval) { 6629 doTrim = true; 6630 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6631 + "; running immediately"); 6632 } 6633 } 6634 } 6635 if (doTrim) { 6636 if (!isFirstBoot()) { 6637 try { 6638 ActivityManagerNative.getDefault().showBootMessage( 6639 mContext.getResources().getString( 6640 R.string.android_upgrading_fstrim), true); 6641 } catch (RemoteException e) { 6642 } 6643 } 6644 ms.runMaintenance(); 6645 } 6646 } else { 6647 Slog.e(TAG, "Mount service unavailable!"); 6648 } 6649 } catch (RemoteException e) { 6650 // Can't happen; MountService is local 6651 } 6652 } 6653 6654 @Override 6655 public void extractPackagesIfNeeded() { 6656 enforceSystemOrRoot("Only the system can request package extraction"); 6657 6658 // Extract pacakges only if profile-guided compilation is enabled because 6659 // otherwise BackgroundDexOptService will not dexopt them later. 6660 if (mUseJitProfiles) { 6661 ArraySet<String> pkgs = getOptimizablePackages(); 6662 if (pkgs != null) { 6663 for (String pkg : pkgs) { 6664 performDexOpt(pkg, null /* instructionSet */, false /* useProfiles */, 6665 true /* extractOnly */, false /* force */); 6666 } 6667 } 6668 } 6669 } 6670 6671 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6672 List<ResolveInfo> ris = null; 6673 try { 6674 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6675 intent, null, 0, userId); 6676 } catch (RemoteException e) { 6677 } 6678 ArraySet<String> pkgNames = new ArraySet<String>(); 6679 if (ris != null) { 6680 for (ResolveInfo ri : ris) { 6681 pkgNames.add(ri.activityInfo.packageName); 6682 } 6683 } 6684 return pkgNames; 6685 } 6686 6687 @Override 6688 public void notifyPackageUse(String packageName) { 6689 synchronized (mPackages) { 6690 PackageParser.Package p = mPackages.get(packageName); 6691 if (p == null) { 6692 return; 6693 } 6694 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6695 } 6696 } 6697 6698 // TODO: this is not used nor needed. Delete it. 6699 @Override 6700 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6701 return performDexOptTraced(packageName, instructionSet, false /* useProfiles */, 6702 false /* extractOnly */, false /* force */); 6703 } 6704 6705 @Override 6706 public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles, 6707 boolean extractOnly, boolean force) { 6708 return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force); 6709 } 6710 6711 private boolean performDexOptTraced(String packageName, String instructionSet, 6712 boolean useProfiles, boolean extractOnly, boolean force) { 6713 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6714 try { 6715 return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly, 6716 force); 6717 } finally { 6718 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6719 } 6720 } 6721 6722 private boolean performDexOptInternal(String packageName, String instructionSet, 6723 boolean useProfiles, boolean extractOnly, boolean force) { 6724 PackageParser.Package p; 6725 final String targetInstructionSet; 6726 synchronized (mPackages) { 6727 p = mPackages.get(packageName); 6728 if (p == null) { 6729 return false; 6730 } 6731 mPackageUsage.write(false); 6732 6733 targetInstructionSet = instructionSet != null ? instructionSet : 6734 getPrimaryInstructionSet(p.applicationInfo); 6735 if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) { 6736 // Skip only if we do not use profiles since they might trigger a recompilation. 6737 return false; 6738 } 6739 } 6740 long callingId = Binder.clearCallingIdentity(); 6741 try { 6742 synchronized (mInstallLock) { 6743 final String[] instructionSets = new String[] { targetInstructionSet }; 6744 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 6745 useProfiles, extractOnly, force); 6746 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6747 } 6748 } finally { 6749 Binder.restoreCallingIdentity(callingId); 6750 } 6751 } 6752 6753 public ArraySet<String> getOptimizablePackages() { 6754 ArraySet<String> pkgs = new ArraySet<String>(); 6755 synchronized (mPackages) { 6756 for (PackageParser.Package p : mPackages.values()) { 6757 if (PackageDexOptimizer.canOptimizePackage(p)) { 6758 pkgs.add(p.packageName); 6759 } 6760 } 6761 } 6762 return pkgs; 6763 } 6764 6765 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 6766 String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) { 6767 // Select the dex optimizer based on the force parameter. 6768 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 6769 // allocate an object here. 6770 PackageDexOptimizer pdo = force 6771 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 6772 : mPackageDexOptimizer; 6773 6774 // Optimize all dependencies first. Note: we ignore the return value and march on 6775 // on errors. 6776 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 6777 if (!deps.isEmpty()) { 6778 for (PackageParser.Package depPackage : deps) { 6779 // TODO: Analyze and investigate if we (should) profile libraries. 6780 // Currently this will do a full compilation of the library. 6781 pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */, 6782 false /* extractOnly */); 6783 } 6784 } 6785 6786 return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly); 6787 } 6788 6789 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 6790 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 6791 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 6792 Set<String> collectedNames = new HashSet<>(); 6793 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 6794 6795 retValue.remove(p); 6796 6797 return retValue; 6798 } else { 6799 return Collections.emptyList(); 6800 } 6801 } 6802 6803 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 6804 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 6805 if (!collectedNames.contains(p.packageName)) { 6806 collectedNames.add(p.packageName); 6807 collected.add(p); 6808 6809 if (p.usesLibraries != null) { 6810 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 6811 } 6812 if (p.usesOptionalLibraries != null) { 6813 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 6814 collectedNames); 6815 } 6816 } 6817 } 6818 6819 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 6820 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 6821 for (String libName : libs) { 6822 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 6823 if (libPkg != null) { 6824 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 6825 } 6826 } 6827 } 6828 6829 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 6830 synchronized (mPackages) { 6831 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 6832 if (lib != null && lib.apk != null) { 6833 return mPackages.get(lib.apk); 6834 } 6835 } 6836 return null; 6837 } 6838 6839 public void shutdown() { 6840 mPackageUsage.write(true); 6841 } 6842 6843 @Override 6844 public void forceDexOpt(String packageName) { 6845 enforceSystemOrRoot("forceDexOpt"); 6846 6847 PackageParser.Package pkg; 6848 synchronized (mPackages) { 6849 pkg = mPackages.get(packageName); 6850 if (pkg == null) { 6851 throw new IllegalArgumentException("Unknown package: " + packageName); 6852 } 6853 } 6854 6855 synchronized (mInstallLock) { 6856 final String[] instructionSets = new String[] { 6857 getPrimaryInstructionSet(pkg.applicationInfo) }; 6858 6859 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6860 6861 // Whoever is calling forceDexOpt wants a fully compiled package. 6862 // Don't use profiles since that may cause compilation to be skipped. 6863 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 6864 false /* useProfiles */, false /* extractOnly */, true /* force */); 6865 6866 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6867 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6868 throw new IllegalStateException("Failed to dexopt: " + res); 6869 } 6870 } 6871 } 6872 6873 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6874 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6875 Slog.w(TAG, "Unable to update from " + oldPkg.name 6876 + " to " + newPkg.packageName 6877 + ": old package not in system partition"); 6878 return false; 6879 } else if (mPackages.get(oldPkg.name) != null) { 6880 Slog.w(TAG, "Unable to update from " + oldPkg.name 6881 + " to " + newPkg.packageName 6882 + ": old package still exists"); 6883 return false; 6884 } 6885 return true; 6886 } 6887 6888 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 6889 // TODO: triage flags as part of 26466827 6890 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 6891 6892 boolean res = true; 6893 final int[] users = sUserManager.getUserIds(); 6894 for (int user : users) { 6895 try { 6896 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 6897 } catch (InstallerException e) { 6898 Slog.w(TAG, "Failed to delete data directory", e); 6899 res = false; 6900 } 6901 } 6902 return res; 6903 } 6904 6905 void removeCodePathLI(File codePath) { 6906 if (codePath.isDirectory()) { 6907 try { 6908 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 6909 } catch (InstallerException e) { 6910 Slog.w(TAG, "Failed to remove code path", e); 6911 } 6912 } else { 6913 codePath.delete(); 6914 } 6915 } 6916 6917 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 6918 try { 6919 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 6920 } catch (InstallerException e) { 6921 Slog.w(TAG, "Failed to destroy app data", e); 6922 } 6923 } 6924 6925 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 6926 int appId, String seinfo) { 6927 try { 6928 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 6929 } catch (InstallerException e) { 6930 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 6931 } 6932 } 6933 6934 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6935 // TODO: triage flags as part of 26466827 6936 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 6937 6938 final int[] users = sUserManager.getUserIds(); 6939 for (int user : users) { 6940 try { 6941 mInstaller.clearAppData(volumeUuid, packageName, user, 6942 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 6943 } catch (InstallerException e) { 6944 Slog.w(TAG, "Failed to delete code cache directory", e); 6945 } 6946 } 6947 } 6948 6949 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6950 PackageParser.Package changingLib) { 6951 if (file.path != null) { 6952 usesLibraryFiles.add(file.path); 6953 return; 6954 } 6955 PackageParser.Package p = mPackages.get(file.apk); 6956 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6957 // If we are doing this while in the middle of updating a library apk, 6958 // then we need to make sure to use that new apk for determining the 6959 // dependencies here. (We haven't yet finished committing the new apk 6960 // to the package manager state.) 6961 if (p == null || p.packageName.equals(changingLib.packageName)) { 6962 p = changingLib; 6963 } 6964 } 6965 if (p != null) { 6966 usesLibraryFiles.addAll(p.getAllCodePaths()); 6967 } 6968 } 6969 6970 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6971 PackageParser.Package changingLib) throws PackageManagerException { 6972 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6973 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6974 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6975 for (int i=0; i<N; i++) { 6976 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6977 if (file == null) { 6978 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6979 "Package " + pkg.packageName + " requires unavailable shared library " 6980 + pkg.usesLibraries.get(i) + "; failing!"); 6981 } 6982 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6983 } 6984 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6985 for (int i=0; i<N; i++) { 6986 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6987 if (file == null) { 6988 Slog.w(TAG, "Package " + pkg.packageName 6989 + " desires unavailable shared library " 6990 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6991 } else { 6992 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6993 } 6994 } 6995 N = usesLibraryFiles.size(); 6996 if (N > 0) { 6997 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6998 } else { 6999 pkg.usesLibraryFiles = null; 7000 } 7001 } 7002 } 7003 7004 private static boolean hasString(List<String> list, List<String> which) { 7005 if (list == null) { 7006 return false; 7007 } 7008 for (int i=list.size()-1; i>=0; i--) { 7009 for (int j=which.size()-1; j>=0; j--) { 7010 if (which.get(j).equals(list.get(i))) { 7011 return true; 7012 } 7013 } 7014 } 7015 return false; 7016 } 7017 7018 private void updateAllSharedLibrariesLPw() { 7019 for (PackageParser.Package pkg : mPackages.values()) { 7020 try { 7021 updateSharedLibrariesLPw(pkg, null); 7022 } catch (PackageManagerException e) { 7023 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7024 } 7025 } 7026 } 7027 7028 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7029 PackageParser.Package changingPkg) { 7030 ArrayList<PackageParser.Package> res = null; 7031 for (PackageParser.Package pkg : mPackages.values()) { 7032 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7033 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7034 if (res == null) { 7035 res = new ArrayList<PackageParser.Package>(); 7036 } 7037 res.add(pkg); 7038 try { 7039 updateSharedLibrariesLPw(pkg, changingPkg); 7040 } catch (PackageManagerException e) { 7041 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7042 } 7043 } 7044 } 7045 return res; 7046 } 7047 7048 /** 7049 * Derive the value of the {@code cpuAbiOverride} based on the provided 7050 * value and an optional stored value from the package settings. 7051 */ 7052 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7053 String cpuAbiOverride = null; 7054 7055 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7056 cpuAbiOverride = null; 7057 } else if (abiOverride != null) { 7058 cpuAbiOverride = abiOverride; 7059 } else if (settings != null) { 7060 cpuAbiOverride = settings.cpuAbiOverrideString; 7061 } 7062 7063 return cpuAbiOverride; 7064 } 7065 7066 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7067 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7068 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7069 try { 7070 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7071 } finally { 7072 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7073 } 7074 } 7075 7076 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7077 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7078 boolean success = false; 7079 try { 7080 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7081 currentTime, user); 7082 success = true; 7083 return res; 7084 } finally { 7085 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7086 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7087 } 7088 } 7089 } 7090 7091 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7092 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7093 final File scanFile = new File(pkg.codePath); 7094 if (pkg.applicationInfo.getCodePath() == null || 7095 pkg.applicationInfo.getResourcePath() == null) { 7096 // Bail out. The resource and code paths haven't been set. 7097 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7098 "Code and resource paths haven't been set correctly"); 7099 } 7100 7101 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7102 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7103 } else { 7104 // Only allow system apps to be flagged as core apps. 7105 pkg.coreApp = false; 7106 } 7107 7108 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7109 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7110 } 7111 7112 if (mCustomResolverComponentName != null && 7113 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7114 setUpCustomResolverActivity(pkg); 7115 } 7116 7117 if (pkg.packageName.equals("android")) { 7118 synchronized (mPackages) { 7119 if (mAndroidApplication != null) { 7120 Slog.w(TAG, "*************************************************"); 7121 Slog.w(TAG, "Core android package being redefined. Skipping."); 7122 Slog.w(TAG, " file=" + scanFile); 7123 Slog.w(TAG, "*************************************************"); 7124 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7125 "Core android package being redefined. Skipping."); 7126 } 7127 7128 // Set up information for our fall-back user intent resolution activity. 7129 mPlatformPackage = pkg; 7130 pkg.mVersionCode = mSdkVersion; 7131 mAndroidApplication = pkg.applicationInfo; 7132 7133 if (!mResolverReplaced) { 7134 mResolveActivity.applicationInfo = mAndroidApplication; 7135 mResolveActivity.name = ResolverActivity.class.getName(); 7136 mResolveActivity.packageName = mAndroidApplication.packageName; 7137 mResolveActivity.processName = "system:ui"; 7138 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7139 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7140 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7141 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7142 mResolveActivity.exported = true; 7143 mResolveActivity.enabled = true; 7144 mResolveInfo.activityInfo = mResolveActivity; 7145 mResolveInfo.priority = 0; 7146 mResolveInfo.preferredOrder = 0; 7147 mResolveInfo.match = 0; 7148 mResolveComponentName = new ComponentName( 7149 mAndroidApplication.packageName, mResolveActivity.name); 7150 } 7151 } 7152 } 7153 7154 if (DEBUG_PACKAGE_SCANNING) { 7155 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7156 Log.d(TAG, "Scanning package " + pkg.packageName); 7157 } 7158 7159 if (mPackages.containsKey(pkg.packageName) 7160 || mSharedLibraries.containsKey(pkg.packageName)) { 7161 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7162 "Application package " + pkg.packageName 7163 + " already installed. Skipping duplicate."); 7164 } 7165 7166 // If we're only installing presumed-existing packages, require that the 7167 // scanned APK is both already known and at the path previously established 7168 // for it. Previously unknown packages we pick up normally, but if we have an 7169 // a priori expectation about this package's install presence, enforce it. 7170 // With a singular exception for new system packages. When an OTA contains 7171 // a new system package, we allow the codepath to change from a system location 7172 // to the user-installed location. If we don't allow this change, any newer, 7173 // user-installed version of the application will be ignored. 7174 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7175 if (mExpectingBetter.containsKey(pkg.packageName)) { 7176 logCriticalInfo(Log.WARN, 7177 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7178 } else { 7179 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7180 if (known != null) { 7181 if (DEBUG_PACKAGE_SCANNING) { 7182 Log.d(TAG, "Examining " + pkg.codePath 7183 + " and requiring known paths " + known.codePathString 7184 + " & " + known.resourcePathString); 7185 } 7186 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7187 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 7188 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7189 "Application package " + pkg.packageName 7190 + " found at " + pkg.applicationInfo.getCodePath() 7191 + " but expected at " + known.codePathString + "; ignoring."); 7192 } 7193 } 7194 } 7195 } 7196 7197 // Initialize package source and resource directories 7198 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7199 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7200 7201 SharedUserSetting suid = null; 7202 PackageSetting pkgSetting = null; 7203 7204 if (!isSystemApp(pkg)) { 7205 // Only system apps can use these features. 7206 pkg.mOriginalPackages = null; 7207 pkg.mRealPackage = null; 7208 pkg.mAdoptPermissions = null; 7209 } 7210 7211 // writer 7212 synchronized (mPackages) { 7213 if (pkg.mSharedUserId != null) { 7214 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7215 if (suid == null) { 7216 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7217 "Creating application package " + pkg.packageName 7218 + " for shared user failed"); 7219 } 7220 if (DEBUG_PACKAGE_SCANNING) { 7221 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7222 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7223 + "): packages=" + suid.packages); 7224 } 7225 } 7226 7227 // Check if we are renaming from an original package name. 7228 PackageSetting origPackage = null; 7229 String realName = null; 7230 if (pkg.mOriginalPackages != null) { 7231 // This package may need to be renamed to a previously 7232 // installed name. Let's check on that... 7233 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7234 if (pkg.mOriginalPackages.contains(renamed)) { 7235 // This package had originally been installed as the 7236 // original name, and we have already taken care of 7237 // transitioning to the new one. Just update the new 7238 // one to continue using the old name. 7239 realName = pkg.mRealPackage; 7240 if (!pkg.packageName.equals(renamed)) { 7241 // Callers into this function may have already taken 7242 // care of renaming the package; only do it here if 7243 // it is not already done. 7244 pkg.setPackageName(renamed); 7245 } 7246 7247 } else { 7248 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7249 if ((origPackage = mSettings.peekPackageLPr( 7250 pkg.mOriginalPackages.get(i))) != null) { 7251 // We do have the package already installed under its 7252 // original name... should we use it? 7253 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7254 // New package is not compatible with original. 7255 origPackage = null; 7256 continue; 7257 } else if (origPackage.sharedUser != null) { 7258 // Make sure uid is compatible between packages. 7259 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7260 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7261 + " to " + pkg.packageName + ": old uid " 7262 + origPackage.sharedUser.name 7263 + " differs from " + pkg.mSharedUserId); 7264 origPackage = null; 7265 continue; 7266 } 7267 } else { 7268 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7269 + pkg.packageName + " to old name " + origPackage.name); 7270 } 7271 break; 7272 } 7273 } 7274 } 7275 } 7276 7277 if (mTransferedPackages.contains(pkg.packageName)) { 7278 Slog.w(TAG, "Package " + pkg.packageName 7279 + " was transferred to another, but its .apk remains"); 7280 } 7281 7282 // Just create the setting, don't add it yet. For already existing packages 7283 // the PkgSetting exists already and doesn't have to be created. 7284 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7285 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7286 pkg.applicationInfo.primaryCpuAbi, 7287 pkg.applicationInfo.secondaryCpuAbi, 7288 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7289 user, false); 7290 if (pkgSetting == null) { 7291 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7292 "Creating application package " + pkg.packageName + " failed"); 7293 } 7294 7295 if (pkgSetting.origPackage != null) { 7296 // If we are first transitioning from an original package, 7297 // fix up the new package's name now. We need to do this after 7298 // looking up the package under its new name, so getPackageLP 7299 // can take care of fiddling things correctly. 7300 pkg.setPackageName(origPackage.name); 7301 7302 // File a report about this. 7303 String msg = "New package " + pkgSetting.realName 7304 + " renamed to replace old package " + pkgSetting.name; 7305 reportSettingsProblem(Log.WARN, msg); 7306 7307 // Make a note of it. 7308 mTransferedPackages.add(origPackage.name); 7309 7310 // No longer need to retain this. 7311 pkgSetting.origPackage = null; 7312 } 7313 7314 if (realName != null) { 7315 // Make a note of it. 7316 mTransferedPackages.add(pkg.packageName); 7317 } 7318 7319 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7320 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7321 } 7322 7323 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7324 // Check all shared libraries and map to their actual file path. 7325 // We only do this here for apps not on a system dir, because those 7326 // are the only ones that can fail an install due to this. We 7327 // will take care of the system apps by updating all of their 7328 // library paths after the scan is done. 7329 updateSharedLibrariesLPw(pkg, null); 7330 } 7331 7332 if (mFoundPolicyFile) { 7333 SELinuxMMAC.assignSeinfoValue(pkg); 7334 } 7335 7336 pkg.applicationInfo.uid = pkgSetting.appId; 7337 pkg.mExtras = pkgSetting; 7338 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7339 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7340 // We just determined the app is signed correctly, so bring 7341 // over the latest parsed certs. 7342 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7343 } else { 7344 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7345 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7346 "Package " + pkg.packageName + " upgrade keys do not match the " 7347 + "previously installed version"); 7348 } else { 7349 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7350 String msg = "System package " + pkg.packageName 7351 + " signature changed; retaining data."; 7352 reportSettingsProblem(Log.WARN, msg); 7353 } 7354 } 7355 } else { 7356 try { 7357 verifySignaturesLP(pkgSetting, pkg); 7358 // We just determined the app is signed correctly, so bring 7359 // over the latest parsed certs. 7360 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7361 } catch (PackageManagerException e) { 7362 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7363 throw e; 7364 } 7365 // The signature has changed, but this package is in the system 7366 // image... let's recover! 7367 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7368 // However... if this package is part of a shared user, but it 7369 // doesn't match the signature of the shared user, let's fail. 7370 // What this means is that you can't change the signatures 7371 // associated with an overall shared user, which doesn't seem all 7372 // that unreasonable. 7373 if (pkgSetting.sharedUser != null) { 7374 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7375 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7376 throw new PackageManagerException( 7377 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7378 "Signature mismatch for shared user: " 7379 + pkgSetting.sharedUser); 7380 } 7381 } 7382 // File a report about this. 7383 String msg = "System package " + pkg.packageName 7384 + " signature changed; retaining data."; 7385 reportSettingsProblem(Log.WARN, msg); 7386 } 7387 } 7388 // Verify that this new package doesn't have any content providers 7389 // that conflict with existing packages. Only do this if the 7390 // package isn't already installed, since we don't want to break 7391 // things that are installed. 7392 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7393 final int N = pkg.providers.size(); 7394 int i; 7395 for (i=0; i<N; i++) { 7396 PackageParser.Provider p = pkg.providers.get(i); 7397 if (p.info.authority != null) { 7398 String names[] = p.info.authority.split(";"); 7399 for (int j = 0; j < names.length; j++) { 7400 if (mProvidersByAuthority.containsKey(names[j])) { 7401 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7402 final String otherPackageName = 7403 ((other != null && other.getComponentName() != null) ? 7404 other.getComponentName().getPackageName() : "?"); 7405 throw new PackageManagerException( 7406 INSTALL_FAILED_CONFLICTING_PROVIDER, 7407 "Can't install because provider name " + names[j] 7408 + " (in package " + pkg.applicationInfo.packageName 7409 + ") is already used by " + otherPackageName); 7410 } 7411 } 7412 } 7413 } 7414 } 7415 7416 if (pkg.mAdoptPermissions != null) { 7417 // This package wants to adopt ownership of permissions from 7418 // another package. 7419 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7420 final String origName = pkg.mAdoptPermissions.get(i); 7421 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7422 if (orig != null) { 7423 if (verifyPackageUpdateLPr(orig, pkg)) { 7424 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7425 + pkg.packageName); 7426 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7427 } 7428 } 7429 } 7430 } 7431 } 7432 7433 final String pkgName = pkg.packageName; 7434 7435 final long scanFileTime = scanFile.lastModified(); 7436 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7437 pkg.applicationInfo.processName = fixProcessName( 7438 pkg.applicationInfo.packageName, 7439 pkg.applicationInfo.processName, 7440 pkg.applicationInfo.uid); 7441 7442 if (pkg != mPlatformPackage) { 7443 // Get all of our default paths setup 7444 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7445 } 7446 7447 final String path = scanFile.getPath(); 7448 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7449 7450 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7451 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7452 7453 // Some system apps still use directory structure for native libraries 7454 // in which case we might end up not detecting abi solely based on apk 7455 // structure. Try to detect abi based on directory structure. 7456 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7457 pkg.applicationInfo.primaryCpuAbi == null) { 7458 setBundledAppAbisAndRoots(pkg, pkgSetting); 7459 setNativeLibraryPaths(pkg); 7460 } 7461 7462 } else { 7463 if ((scanFlags & SCAN_MOVE) != 0) { 7464 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7465 // but we already have this packages package info in the PackageSetting. We just 7466 // use that and derive the native library path based on the new codepath. 7467 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7468 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7469 } 7470 7471 // Set native library paths again. For moves, the path will be updated based on the 7472 // ABIs we've determined above. For non-moves, the path will be updated based on the 7473 // ABIs we determined during compilation, but the path will depend on the final 7474 // package path (after the rename away from the stage path). 7475 setNativeLibraryPaths(pkg); 7476 } 7477 7478 // This is a special case for the "system" package, where the ABI is 7479 // dictated by the zygote configuration (and init.rc). We should keep track 7480 // of this ABI so that we can deal with "normal" applications that run under 7481 // the same UID correctly. 7482 if (mPlatformPackage == pkg) { 7483 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7484 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7485 } 7486 7487 // If there's a mismatch between the abi-override in the package setting 7488 // and the abiOverride specified for the install. Warn about this because we 7489 // would've already compiled the app without taking the package setting into 7490 // account. 7491 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7492 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7493 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7494 " for package " + pkg.packageName); 7495 } 7496 } 7497 7498 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7499 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7500 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7501 7502 // Copy the derived override back to the parsed package, so that we can 7503 // update the package settings accordingly. 7504 pkg.cpuAbiOverride = cpuAbiOverride; 7505 7506 if (DEBUG_ABI_SELECTION) { 7507 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7508 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7509 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7510 } 7511 7512 // Push the derived path down into PackageSettings so we know what to 7513 // clean up at uninstall time. 7514 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7515 7516 if (DEBUG_ABI_SELECTION) { 7517 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7518 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7519 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7520 } 7521 7522 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7523 // We don't do this here during boot because we can do it all 7524 // at once after scanning all existing packages. 7525 // 7526 // We also do this *before* we perform dexopt on this package, so that 7527 // we can avoid redundant dexopts, and also to make sure we've got the 7528 // code and package path correct. 7529 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7530 pkg, true /* boot complete */); 7531 } 7532 7533 if (mFactoryTest && pkg.requestedPermissions.contains( 7534 android.Manifest.permission.FACTORY_TEST)) { 7535 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7536 } 7537 7538 ArrayList<PackageParser.Package> clientLibPkgs = null; 7539 7540 // writer 7541 synchronized (mPackages) { 7542 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7543 // Only system apps can add new shared libraries. 7544 if (pkg.libraryNames != null) { 7545 for (int i=0; i<pkg.libraryNames.size(); i++) { 7546 String name = pkg.libraryNames.get(i); 7547 boolean allowed = false; 7548 if (pkg.isUpdatedSystemApp()) { 7549 // New library entries can only be added through the 7550 // system image. This is important to get rid of a lot 7551 // of nasty edge cases: for example if we allowed a non- 7552 // system update of the app to add a library, then uninstalling 7553 // the update would make the library go away, and assumptions 7554 // we made such as through app install filtering would now 7555 // have allowed apps on the device which aren't compatible 7556 // with it. Better to just have the restriction here, be 7557 // conservative, and create many fewer cases that can negatively 7558 // impact the user experience. 7559 final PackageSetting sysPs = mSettings 7560 .getDisabledSystemPkgLPr(pkg.packageName); 7561 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7562 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7563 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7564 allowed = true; 7565 break; 7566 } 7567 } 7568 } 7569 } else { 7570 allowed = true; 7571 } 7572 if (allowed) { 7573 if (!mSharedLibraries.containsKey(name)) { 7574 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7575 } else if (!name.equals(pkg.packageName)) { 7576 Slog.w(TAG, "Package " + pkg.packageName + " library " 7577 + name + " already exists; skipping"); 7578 } 7579 } else { 7580 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7581 + name + " that is not declared on system image; skipping"); 7582 } 7583 } 7584 if ((scanFlags & SCAN_BOOTING) == 0) { 7585 // If we are not booting, we need to update any applications 7586 // that are clients of our shared library. If we are booting, 7587 // this will all be done once the scan is complete. 7588 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7589 } 7590 } 7591 } 7592 } 7593 7594 // Request the ActivityManager to kill the process(only for existing packages) 7595 // so that we do not end up in a confused state while the user is still using the older 7596 // version of the application while the new one gets installed. 7597 if ((scanFlags & SCAN_REPLACING) != 0) { 7598 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7599 7600 killApplication(pkg.applicationInfo.packageName, 7601 pkg.applicationInfo.uid, "replace pkg"); 7602 7603 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7604 } 7605 7606 // Also need to kill any apps that are dependent on the library. 7607 if (clientLibPkgs != null) { 7608 for (int i=0; i<clientLibPkgs.size(); i++) { 7609 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7610 killApplication(clientPkg.applicationInfo.packageName, 7611 clientPkg.applicationInfo.uid, "update lib"); 7612 } 7613 } 7614 7615 // Make sure we're not adding any bogus keyset info 7616 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7617 ksms.assertScannedPackageValid(pkg); 7618 7619 // writer 7620 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7621 7622 boolean createIdmapFailed = false; 7623 synchronized (mPackages) { 7624 // We don't expect installation to fail beyond this point 7625 7626 // Add the new setting to mSettings 7627 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7628 // Add the new setting to mPackages 7629 mPackages.put(pkg.applicationInfo.packageName, pkg); 7630 // Make sure we don't accidentally delete its data. 7631 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7632 while (iter.hasNext()) { 7633 PackageCleanItem item = iter.next(); 7634 if (pkgName.equals(item.packageName)) { 7635 iter.remove(); 7636 } 7637 } 7638 7639 // Take care of first install / last update times. 7640 if (currentTime != 0) { 7641 if (pkgSetting.firstInstallTime == 0) { 7642 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7643 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7644 pkgSetting.lastUpdateTime = currentTime; 7645 } 7646 } else if (pkgSetting.firstInstallTime == 0) { 7647 // We need *something*. Take time time stamp of the file. 7648 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7649 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7650 if (scanFileTime != pkgSetting.timeStamp) { 7651 // A package on the system image has changed; consider this 7652 // to be an update. 7653 pkgSetting.lastUpdateTime = scanFileTime; 7654 } 7655 } 7656 7657 // Add the package's KeySets to the global KeySetManagerService 7658 ksms.addScannedPackageLPw(pkg); 7659 7660 int N = pkg.providers.size(); 7661 StringBuilder r = null; 7662 int i; 7663 for (i=0; i<N; i++) { 7664 PackageParser.Provider p = pkg.providers.get(i); 7665 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7666 p.info.processName, pkg.applicationInfo.uid); 7667 mProviders.addProvider(p); 7668 p.syncable = p.info.isSyncable; 7669 if (p.info.authority != null) { 7670 String names[] = p.info.authority.split(";"); 7671 p.info.authority = null; 7672 for (int j = 0; j < names.length; j++) { 7673 if (j == 1 && p.syncable) { 7674 // We only want the first authority for a provider to possibly be 7675 // syncable, so if we already added this provider using a different 7676 // authority clear the syncable flag. We copy the provider before 7677 // changing it because the mProviders object contains a reference 7678 // to a provider that we don't want to change. 7679 // Only do this for the second authority since the resulting provider 7680 // object can be the same for all future authorities for this provider. 7681 p = new PackageParser.Provider(p); 7682 p.syncable = false; 7683 } 7684 if (!mProvidersByAuthority.containsKey(names[j])) { 7685 mProvidersByAuthority.put(names[j], p); 7686 if (p.info.authority == null) { 7687 p.info.authority = names[j]; 7688 } else { 7689 p.info.authority = p.info.authority + ";" + names[j]; 7690 } 7691 if (DEBUG_PACKAGE_SCANNING) { 7692 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7693 Log.d(TAG, "Registered content provider: " + names[j] 7694 + ", className = " + p.info.name + ", isSyncable = " 7695 + p.info.isSyncable); 7696 } 7697 } else { 7698 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7699 Slog.w(TAG, "Skipping provider name " + names[j] + 7700 " (in package " + pkg.applicationInfo.packageName + 7701 "): name already used by " 7702 + ((other != null && other.getComponentName() != null) 7703 ? other.getComponentName().getPackageName() : "?")); 7704 } 7705 } 7706 } 7707 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7708 if (r == null) { 7709 r = new StringBuilder(256); 7710 } else { 7711 r.append(' '); 7712 } 7713 r.append(p.info.name); 7714 } 7715 } 7716 if (r != null) { 7717 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7718 } 7719 7720 N = pkg.services.size(); 7721 r = null; 7722 for (i=0; i<N; i++) { 7723 PackageParser.Service s = pkg.services.get(i); 7724 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7725 s.info.processName, pkg.applicationInfo.uid); 7726 mServices.addService(s); 7727 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7728 if (r == null) { 7729 r = new StringBuilder(256); 7730 } else { 7731 r.append(' '); 7732 } 7733 r.append(s.info.name); 7734 } 7735 } 7736 if (r != null) { 7737 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7738 } 7739 7740 N = pkg.receivers.size(); 7741 r = null; 7742 for (i=0; i<N; i++) { 7743 PackageParser.Activity a = pkg.receivers.get(i); 7744 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7745 a.info.processName, pkg.applicationInfo.uid); 7746 mReceivers.addActivity(a, "receiver"); 7747 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7748 if (r == null) { 7749 r = new StringBuilder(256); 7750 } else { 7751 r.append(' '); 7752 } 7753 r.append(a.info.name); 7754 } 7755 } 7756 if (r != null) { 7757 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7758 } 7759 7760 N = pkg.activities.size(); 7761 r = null; 7762 for (i=0; i<N; i++) { 7763 PackageParser.Activity a = pkg.activities.get(i); 7764 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7765 a.info.processName, pkg.applicationInfo.uid); 7766 mActivities.addActivity(a, "activity"); 7767 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7768 if (r == null) { 7769 r = new StringBuilder(256); 7770 } else { 7771 r.append(' '); 7772 } 7773 r.append(a.info.name); 7774 } 7775 } 7776 if (r != null) { 7777 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7778 } 7779 7780 N = pkg.permissionGroups.size(); 7781 r = null; 7782 for (i=0; i<N; i++) { 7783 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7784 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7785 if (cur == null) { 7786 mPermissionGroups.put(pg.info.name, pg); 7787 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7788 if (r == null) { 7789 r = new StringBuilder(256); 7790 } else { 7791 r.append(' '); 7792 } 7793 r.append(pg.info.name); 7794 } 7795 } else { 7796 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7797 + pg.info.packageName + " ignored: original from " 7798 + cur.info.packageName); 7799 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7800 if (r == null) { 7801 r = new StringBuilder(256); 7802 } else { 7803 r.append(' '); 7804 } 7805 r.append("DUP:"); 7806 r.append(pg.info.name); 7807 } 7808 } 7809 } 7810 if (r != null) { 7811 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7812 } 7813 7814 N = pkg.permissions.size(); 7815 r = null; 7816 for (i=0; i<N; i++) { 7817 PackageParser.Permission p = pkg.permissions.get(i); 7818 7819 // Assume by default that we did not install this permission into the system. 7820 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7821 7822 // Now that permission groups have a special meaning, we ignore permission 7823 // groups for legacy apps to prevent unexpected behavior. In particular, 7824 // permissions for one app being granted to someone just becuase they happen 7825 // to be in a group defined by another app (before this had no implications). 7826 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7827 p.group = mPermissionGroups.get(p.info.group); 7828 // Warn for a permission in an unknown group. 7829 if (p.info.group != null && p.group == null) { 7830 Slog.w(TAG, "Permission " + p.info.name + " from package " 7831 + p.info.packageName + " in an unknown group " + p.info.group); 7832 } 7833 } 7834 7835 ArrayMap<String, BasePermission> permissionMap = 7836 p.tree ? mSettings.mPermissionTrees 7837 : mSettings.mPermissions; 7838 BasePermission bp = permissionMap.get(p.info.name); 7839 7840 // Allow system apps to redefine non-system permissions 7841 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7842 final boolean currentOwnerIsSystem = (bp.perm != null 7843 && isSystemApp(bp.perm.owner)); 7844 if (isSystemApp(p.owner)) { 7845 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7846 // It's a built-in permission and no owner, take ownership now 7847 bp.packageSetting = pkgSetting; 7848 bp.perm = p; 7849 bp.uid = pkg.applicationInfo.uid; 7850 bp.sourcePackage = p.info.packageName; 7851 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7852 } else if (!currentOwnerIsSystem) { 7853 String msg = "New decl " + p.owner + " of permission " 7854 + p.info.name + " is system; overriding " + bp.sourcePackage; 7855 reportSettingsProblem(Log.WARN, msg); 7856 bp = null; 7857 } 7858 } 7859 } 7860 7861 if (bp == null) { 7862 bp = new BasePermission(p.info.name, p.info.packageName, 7863 BasePermission.TYPE_NORMAL); 7864 permissionMap.put(p.info.name, bp); 7865 } 7866 7867 if (bp.perm == null) { 7868 if (bp.sourcePackage == null 7869 || bp.sourcePackage.equals(p.info.packageName)) { 7870 BasePermission tree = findPermissionTreeLP(p.info.name); 7871 if (tree == null 7872 || tree.sourcePackage.equals(p.info.packageName)) { 7873 bp.packageSetting = pkgSetting; 7874 bp.perm = p; 7875 bp.uid = pkg.applicationInfo.uid; 7876 bp.sourcePackage = p.info.packageName; 7877 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7878 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7879 if (r == null) { 7880 r = new StringBuilder(256); 7881 } else { 7882 r.append(' '); 7883 } 7884 r.append(p.info.name); 7885 } 7886 } else { 7887 Slog.w(TAG, "Permission " + p.info.name + " from package " 7888 + p.info.packageName + " ignored: base tree " 7889 + tree.name + " is from package " 7890 + tree.sourcePackage); 7891 } 7892 } else { 7893 Slog.w(TAG, "Permission " + p.info.name + " from package " 7894 + p.info.packageName + " ignored: original from " 7895 + bp.sourcePackage); 7896 } 7897 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7898 if (r == null) { 7899 r = new StringBuilder(256); 7900 } else { 7901 r.append(' '); 7902 } 7903 r.append("DUP:"); 7904 r.append(p.info.name); 7905 } 7906 if (bp.perm == p) { 7907 bp.protectionLevel = p.info.protectionLevel; 7908 } 7909 } 7910 7911 if (r != null) { 7912 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7913 } 7914 7915 N = pkg.instrumentation.size(); 7916 r = null; 7917 for (i=0; i<N; i++) { 7918 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7919 a.info.packageName = pkg.applicationInfo.packageName; 7920 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7921 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7922 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7923 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7924 a.info.dataDir = pkg.applicationInfo.dataDir; 7925 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7926 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7927 7928 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7929 // need other information about the application, like the ABI and what not ? 7930 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7931 mInstrumentation.put(a.getComponentName(), a); 7932 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7933 if (r == null) { 7934 r = new StringBuilder(256); 7935 } else { 7936 r.append(' '); 7937 } 7938 r.append(a.info.name); 7939 } 7940 } 7941 if (r != null) { 7942 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7943 } 7944 7945 if (pkg.protectedBroadcasts != null) { 7946 N = pkg.protectedBroadcasts.size(); 7947 for (i=0; i<N; i++) { 7948 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7949 } 7950 } 7951 7952 pkgSetting.setTimeStamp(scanFileTime); 7953 7954 // Create idmap files for pairs of (packages, overlay packages). 7955 // Note: "android", ie framework-res.apk, is handled by native layers. 7956 if (pkg.mOverlayTarget != null) { 7957 // This is an overlay package. 7958 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7959 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7960 mOverlays.put(pkg.mOverlayTarget, 7961 new ArrayMap<String, PackageParser.Package>()); 7962 } 7963 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7964 map.put(pkg.packageName, pkg); 7965 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7966 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7967 createIdmapFailed = true; 7968 } 7969 } 7970 } else if (mOverlays.containsKey(pkg.packageName) && 7971 !pkg.packageName.equals("android")) { 7972 // This is a regular package, with one or more known overlay packages. 7973 createIdmapsForPackageLI(pkg); 7974 } 7975 } 7976 7977 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7978 7979 if (createIdmapFailed) { 7980 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7981 "scanPackageLI failed to createIdmap"); 7982 } 7983 return pkg; 7984 } 7985 7986 /** 7987 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7988 * is derived purely on the basis of the contents of {@code scanFile} and 7989 * {@code cpuAbiOverride}. 7990 * 7991 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7992 */ 7993 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7994 String cpuAbiOverride, boolean extractLibs) 7995 throws PackageManagerException { 7996 // TODO: We can probably be smarter about this stuff. For installed apps, 7997 // we can calculate this information at install time once and for all. For 7998 // system apps, we can probably assume that this information doesn't change 7999 // after the first boot scan. As things stand, we do lots of unnecessary work. 8000 8001 // Give ourselves some initial paths; we'll come back for another 8002 // pass once we've determined ABI below. 8003 setNativeLibraryPaths(pkg); 8004 8005 // We would never need to extract libs for forward-locked and external packages, 8006 // since the container service will do it for us. We shouldn't attempt to 8007 // extract libs from system app when it was not updated. 8008 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8009 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8010 extractLibs = false; 8011 } 8012 8013 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8014 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8015 8016 NativeLibraryHelper.Handle handle = null; 8017 try { 8018 handle = NativeLibraryHelper.Handle.create(pkg); 8019 // TODO(multiArch): This can be null for apps that didn't go through the 8020 // usual installation process. We can calculate it again, like we 8021 // do during install time. 8022 // 8023 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8024 // unnecessary. 8025 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8026 8027 // Null out the abis so that they can be recalculated. 8028 pkg.applicationInfo.primaryCpuAbi = null; 8029 pkg.applicationInfo.secondaryCpuAbi = null; 8030 if (isMultiArch(pkg.applicationInfo)) { 8031 // Warn if we've set an abiOverride for multi-lib packages.. 8032 // By definition, we need to copy both 32 and 64 bit libraries for 8033 // such packages. 8034 if (pkg.cpuAbiOverride != null 8035 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8036 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8037 } 8038 8039 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8040 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8041 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8042 if (extractLibs) { 8043 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8044 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8045 useIsaSpecificSubdirs); 8046 } else { 8047 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8048 } 8049 } 8050 8051 maybeThrowExceptionForMultiArchCopy( 8052 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8053 8054 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8055 if (extractLibs) { 8056 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8057 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8058 useIsaSpecificSubdirs); 8059 } else { 8060 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8061 } 8062 } 8063 8064 maybeThrowExceptionForMultiArchCopy( 8065 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8066 8067 if (abi64 >= 0) { 8068 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8069 } 8070 8071 if (abi32 >= 0) { 8072 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8073 if (abi64 >= 0) { 8074 pkg.applicationInfo.secondaryCpuAbi = abi; 8075 } else { 8076 pkg.applicationInfo.primaryCpuAbi = abi; 8077 } 8078 } 8079 if (cpuAbiOverride != null && 8080 cpuAbiOverride.equals(pkg.applicationInfo.secondaryCpuAbi)) { 8081 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8082 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8083 } 8084 } else { 8085 String[] abiList = (cpuAbiOverride != null) ? 8086 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8087 8088 // Enable gross and lame hacks for apps that are built with old 8089 // SDK tools. We must scan their APKs for renderscript bitcode and 8090 // not launch them if it's present. Don't bother checking on devices 8091 // that don't have 64 bit support. 8092 boolean needsRenderScriptOverride = false; 8093 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8094 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8095 abiList = Build.SUPPORTED_32_BIT_ABIS; 8096 needsRenderScriptOverride = true; 8097 } 8098 8099 final int copyRet; 8100 if (extractLibs) { 8101 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8102 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8103 } else { 8104 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8105 } 8106 8107 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8108 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8109 "Error unpackaging native libs for app, errorCode=" + copyRet); 8110 } 8111 8112 if (copyRet >= 0) { 8113 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8114 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8115 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8116 } else if (needsRenderScriptOverride) { 8117 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8118 } 8119 } 8120 } catch (IOException ioe) { 8121 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8122 } finally { 8123 IoUtils.closeQuietly(handle); 8124 } 8125 8126 // Now that we've calculated the ABIs and determined if it's an internal app, 8127 // we will go ahead and populate the nativeLibraryPath. 8128 setNativeLibraryPaths(pkg); 8129 } 8130 8131 /** 8132 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8133 * i.e, so that all packages can be run inside a single process if required. 8134 * 8135 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8136 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8137 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8138 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8139 * updating a package that belongs to a shared user. 8140 * 8141 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8142 * adds unnecessary complexity. 8143 */ 8144 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8145 PackageParser.Package scannedPackage, boolean bootComplete) { 8146 String requiredInstructionSet = null; 8147 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8148 requiredInstructionSet = VMRuntime.getInstructionSet( 8149 scannedPackage.applicationInfo.primaryCpuAbi); 8150 } 8151 8152 PackageSetting requirer = null; 8153 for (PackageSetting ps : packagesForUser) { 8154 // If packagesForUser contains scannedPackage, we skip it. This will happen 8155 // when scannedPackage is an update of an existing package. Without this check, 8156 // we will never be able to change the ABI of any package belonging to a shared 8157 // user, even if it's compatible with other packages. 8158 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8159 if (ps.primaryCpuAbiString == null) { 8160 continue; 8161 } 8162 8163 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8164 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8165 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8166 // this but there's not much we can do. 8167 String errorMessage = "Instruction set mismatch, " 8168 + ((requirer == null) ? "[caller]" : requirer) 8169 + " requires " + requiredInstructionSet + " whereas " + ps 8170 + " requires " + instructionSet; 8171 Slog.w(TAG, errorMessage); 8172 } 8173 8174 if (requiredInstructionSet == null) { 8175 requiredInstructionSet = instructionSet; 8176 requirer = ps; 8177 } 8178 } 8179 } 8180 8181 if (requiredInstructionSet != null) { 8182 String adjustedAbi; 8183 if (requirer != null) { 8184 // requirer != null implies that either scannedPackage was null or that scannedPackage 8185 // did not require an ABI, in which case we have to adjust scannedPackage to match 8186 // the ABI of the set (which is the same as requirer's ABI) 8187 adjustedAbi = requirer.primaryCpuAbiString; 8188 if (scannedPackage != null) { 8189 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8190 } 8191 } else { 8192 // requirer == null implies that we're updating all ABIs in the set to 8193 // match scannedPackage. 8194 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8195 } 8196 8197 for (PackageSetting ps : packagesForUser) { 8198 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8199 if (ps.primaryCpuAbiString != null) { 8200 continue; 8201 } 8202 8203 ps.primaryCpuAbiString = adjustedAbi; 8204 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8205 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8206 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8207 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8208 + " (requirer=" 8209 + (requirer == null ? "null" : requirer.pkg.packageName) 8210 + ", scannedPackage=" 8211 + (scannedPackage != null ? scannedPackage.packageName : "null") 8212 + ")"); 8213 try { 8214 mInstaller.rmdex(ps.codePathString, 8215 getDexCodeInstructionSet(getPreferredInstructionSet())); 8216 } catch (InstallerException ignored) { 8217 } 8218 } 8219 } 8220 } 8221 } 8222 } 8223 8224 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8225 synchronized (mPackages) { 8226 mResolverReplaced = true; 8227 // Set up information for custom user intent resolution activity. 8228 mResolveActivity.applicationInfo = pkg.applicationInfo; 8229 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8230 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8231 mResolveActivity.processName = pkg.applicationInfo.packageName; 8232 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8233 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8234 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8235 mResolveActivity.theme = 0; 8236 mResolveActivity.exported = true; 8237 mResolveActivity.enabled = true; 8238 mResolveInfo.activityInfo = mResolveActivity; 8239 mResolveInfo.priority = 0; 8240 mResolveInfo.preferredOrder = 0; 8241 mResolveInfo.match = 0; 8242 mResolveComponentName = mCustomResolverComponentName; 8243 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8244 mResolveComponentName); 8245 } 8246 } 8247 8248 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8249 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8250 8251 // Set up information for ephemeral installer activity 8252 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8253 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8254 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8255 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8256 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8257 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8258 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8259 mEphemeralInstallerActivity.theme = 0; 8260 mEphemeralInstallerActivity.exported = true; 8261 mEphemeralInstallerActivity.enabled = true; 8262 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8263 mEphemeralInstallerInfo.priority = 0; 8264 mEphemeralInstallerInfo.preferredOrder = 0; 8265 mEphemeralInstallerInfo.match = 0; 8266 8267 if (DEBUG_EPHEMERAL) { 8268 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8269 } 8270 } 8271 8272 private static String calculateBundledApkRoot(final String codePathString) { 8273 final File codePath = new File(codePathString); 8274 final File codeRoot; 8275 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8276 codeRoot = Environment.getRootDirectory(); 8277 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8278 codeRoot = Environment.getOemDirectory(); 8279 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8280 codeRoot = Environment.getVendorDirectory(); 8281 } else { 8282 // Unrecognized code path; take its top real segment as the apk root: 8283 // e.g. /something/app/blah.apk => /something 8284 try { 8285 File f = codePath.getCanonicalFile(); 8286 File parent = f.getParentFile(); // non-null because codePath is a file 8287 File tmp; 8288 while ((tmp = parent.getParentFile()) != null) { 8289 f = parent; 8290 parent = tmp; 8291 } 8292 codeRoot = f; 8293 Slog.w(TAG, "Unrecognized code path " 8294 + codePath + " - using " + codeRoot); 8295 } catch (IOException e) { 8296 // Can't canonicalize the code path -- shenanigans? 8297 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8298 return Environment.getRootDirectory().getPath(); 8299 } 8300 } 8301 return codeRoot.getPath(); 8302 } 8303 8304 /** 8305 * Derive and set the location of native libraries for the given package, 8306 * which varies depending on where and how the package was installed. 8307 */ 8308 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8309 final ApplicationInfo info = pkg.applicationInfo; 8310 final String codePath = pkg.codePath; 8311 final File codeFile = new File(codePath); 8312 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8313 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8314 8315 info.nativeLibraryRootDir = null; 8316 info.nativeLibraryRootRequiresIsa = false; 8317 info.nativeLibraryDir = null; 8318 info.secondaryNativeLibraryDir = null; 8319 8320 if (isApkFile(codeFile)) { 8321 // Monolithic install 8322 if (bundledApp) { 8323 // If "/system/lib64/apkname" exists, assume that is the per-package 8324 // native library directory to use; otherwise use "/system/lib/apkname". 8325 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8326 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8327 getPrimaryInstructionSet(info)); 8328 8329 // This is a bundled system app so choose the path based on the ABI. 8330 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8331 // is just the default path. 8332 final String apkName = deriveCodePathName(codePath); 8333 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8334 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8335 apkName).getAbsolutePath(); 8336 8337 if (info.secondaryCpuAbi != null) { 8338 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8339 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8340 secondaryLibDir, apkName).getAbsolutePath(); 8341 } 8342 } else if (asecApp) { 8343 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8344 .getAbsolutePath(); 8345 } else { 8346 final String apkName = deriveCodePathName(codePath); 8347 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8348 .getAbsolutePath(); 8349 } 8350 8351 info.nativeLibraryRootRequiresIsa = false; 8352 info.nativeLibraryDir = info.nativeLibraryRootDir; 8353 } else { 8354 // Cluster install 8355 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8356 info.nativeLibraryRootRequiresIsa = true; 8357 8358 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8359 getPrimaryInstructionSet(info)).getAbsolutePath(); 8360 8361 if (info.secondaryCpuAbi != null) { 8362 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8363 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8364 } 8365 } 8366 } 8367 8368 /** 8369 * Calculate the abis and roots for a bundled app. These can uniquely 8370 * be determined from the contents of the system partition, i.e whether 8371 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8372 * of this information, and instead assume that the system was built 8373 * sensibly. 8374 */ 8375 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8376 PackageSetting pkgSetting) { 8377 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8378 8379 // If "/system/lib64/apkname" exists, assume that is the per-package 8380 // native library directory to use; otherwise use "/system/lib/apkname". 8381 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8382 setBundledAppAbi(pkg, apkRoot, apkName); 8383 // pkgSetting might be null during rescan following uninstall of updates 8384 // to a bundled app, so accommodate that possibility. The settings in 8385 // that case will be established later from the parsed package. 8386 // 8387 // If the settings aren't null, sync them up with what we've just derived. 8388 // note that apkRoot isn't stored in the package settings. 8389 if (pkgSetting != null) { 8390 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8391 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8392 } 8393 } 8394 8395 /** 8396 * Deduces the ABI of a bundled app and sets the relevant fields on the 8397 * parsed pkg object. 8398 * 8399 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8400 * under which system libraries are installed. 8401 * @param apkName the name of the installed package. 8402 */ 8403 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8404 final File codeFile = new File(pkg.codePath); 8405 8406 final boolean has64BitLibs; 8407 final boolean has32BitLibs; 8408 if (isApkFile(codeFile)) { 8409 // Monolithic install 8410 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8411 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8412 } else { 8413 // Cluster install 8414 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8415 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8416 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8417 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8418 has64BitLibs = (new File(rootDir, isa)).exists(); 8419 } else { 8420 has64BitLibs = false; 8421 } 8422 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8423 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8424 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8425 has32BitLibs = (new File(rootDir, isa)).exists(); 8426 } else { 8427 has32BitLibs = false; 8428 } 8429 } 8430 8431 if (has64BitLibs && !has32BitLibs) { 8432 // The package has 64 bit libs, but not 32 bit libs. Its primary 8433 // ABI should be 64 bit. We can safely assume here that the bundled 8434 // native libraries correspond to the most preferred ABI in the list. 8435 8436 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8437 pkg.applicationInfo.secondaryCpuAbi = null; 8438 } else if (has32BitLibs && !has64BitLibs) { 8439 // The package has 32 bit libs but not 64 bit libs. Its primary 8440 // ABI should be 32 bit. 8441 8442 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8443 pkg.applicationInfo.secondaryCpuAbi = null; 8444 } else if (has32BitLibs && has64BitLibs) { 8445 // The application has both 64 and 32 bit bundled libraries. We check 8446 // here that the app declares multiArch support, and warn if it doesn't. 8447 // 8448 // We will be lenient here and record both ABIs. The primary will be the 8449 // ABI that's higher on the list, i.e, a device that's configured to prefer 8450 // 64 bit apps will see a 64 bit primary ABI, 8451 8452 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8453 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8454 } 8455 8456 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8457 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8458 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8459 } else { 8460 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8461 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8462 } 8463 } else { 8464 pkg.applicationInfo.primaryCpuAbi = null; 8465 pkg.applicationInfo.secondaryCpuAbi = null; 8466 } 8467 } 8468 8469 private void killApplication(String pkgName, int appId, String reason) { 8470 // Request the ActivityManager to kill the process(only for existing packages) 8471 // so that we do not end up in a confused state while the user is still using the older 8472 // version of the application while the new one gets installed. 8473 IActivityManager am = ActivityManagerNative.getDefault(); 8474 if (am != null) { 8475 try { 8476 am.killApplicationWithAppId(pkgName, appId, reason); 8477 } catch (RemoteException e) { 8478 } 8479 } 8480 } 8481 8482 void removePackageLI(PackageSetting ps, boolean chatty) { 8483 if (DEBUG_INSTALL) { 8484 if (chatty) 8485 Log.d(TAG, "Removing package " + ps.name); 8486 } 8487 8488 // writer 8489 synchronized (mPackages) { 8490 mPackages.remove(ps.name); 8491 final PackageParser.Package pkg = ps.pkg; 8492 if (pkg != null) { 8493 cleanPackageDataStructuresLILPw(pkg, chatty); 8494 } 8495 } 8496 } 8497 8498 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8499 if (DEBUG_INSTALL) { 8500 if (chatty) 8501 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8502 } 8503 8504 // writer 8505 synchronized (mPackages) { 8506 mPackages.remove(pkg.applicationInfo.packageName); 8507 cleanPackageDataStructuresLILPw(pkg, chatty); 8508 } 8509 } 8510 8511 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8512 int N = pkg.providers.size(); 8513 StringBuilder r = null; 8514 int i; 8515 for (i=0; i<N; i++) { 8516 PackageParser.Provider p = pkg.providers.get(i); 8517 mProviders.removeProvider(p); 8518 if (p.info.authority == null) { 8519 8520 /* There was another ContentProvider with this authority when 8521 * this app was installed so this authority is null, 8522 * Ignore it as we don't have to unregister the provider. 8523 */ 8524 continue; 8525 } 8526 String names[] = p.info.authority.split(";"); 8527 for (int j = 0; j < names.length; j++) { 8528 if (mProvidersByAuthority.get(names[j]) == p) { 8529 mProvidersByAuthority.remove(names[j]); 8530 if (DEBUG_REMOVE) { 8531 if (chatty) 8532 Log.d(TAG, "Unregistered content provider: " + names[j] 8533 + ", className = " + p.info.name + ", isSyncable = " 8534 + p.info.isSyncable); 8535 } 8536 } 8537 } 8538 if (DEBUG_REMOVE && chatty) { 8539 if (r == null) { 8540 r = new StringBuilder(256); 8541 } else { 8542 r.append(' '); 8543 } 8544 r.append(p.info.name); 8545 } 8546 } 8547 if (r != null) { 8548 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8549 } 8550 8551 N = pkg.services.size(); 8552 r = null; 8553 for (i=0; i<N; i++) { 8554 PackageParser.Service s = pkg.services.get(i); 8555 mServices.removeService(s); 8556 if (chatty) { 8557 if (r == null) { 8558 r = new StringBuilder(256); 8559 } else { 8560 r.append(' '); 8561 } 8562 r.append(s.info.name); 8563 } 8564 } 8565 if (r != null) { 8566 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8567 } 8568 8569 N = pkg.receivers.size(); 8570 r = null; 8571 for (i=0; i<N; i++) { 8572 PackageParser.Activity a = pkg.receivers.get(i); 8573 mReceivers.removeActivity(a, "receiver"); 8574 if (DEBUG_REMOVE && chatty) { 8575 if (r == null) { 8576 r = new StringBuilder(256); 8577 } else { 8578 r.append(' '); 8579 } 8580 r.append(a.info.name); 8581 } 8582 } 8583 if (r != null) { 8584 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8585 } 8586 8587 N = pkg.activities.size(); 8588 r = null; 8589 for (i=0; i<N; i++) { 8590 PackageParser.Activity a = pkg.activities.get(i); 8591 mActivities.removeActivity(a, "activity"); 8592 if (DEBUG_REMOVE && chatty) { 8593 if (r == null) { 8594 r = new StringBuilder(256); 8595 } else { 8596 r.append(' '); 8597 } 8598 r.append(a.info.name); 8599 } 8600 } 8601 if (r != null) { 8602 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8603 } 8604 8605 N = pkg.permissions.size(); 8606 r = null; 8607 for (i=0; i<N; i++) { 8608 PackageParser.Permission p = pkg.permissions.get(i); 8609 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8610 if (bp == null) { 8611 bp = mSettings.mPermissionTrees.get(p.info.name); 8612 } 8613 if (bp != null && bp.perm == p) { 8614 bp.perm = null; 8615 if (DEBUG_REMOVE && chatty) { 8616 if (r == null) { 8617 r = new StringBuilder(256); 8618 } else { 8619 r.append(' '); 8620 } 8621 r.append(p.info.name); 8622 } 8623 } 8624 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8625 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8626 if (appOpPkgs != null) { 8627 appOpPkgs.remove(pkg.packageName); 8628 } 8629 } 8630 } 8631 if (r != null) { 8632 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8633 } 8634 8635 N = pkg.requestedPermissions.size(); 8636 r = null; 8637 for (i=0; i<N; i++) { 8638 String perm = pkg.requestedPermissions.get(i); 8639 BasePermission bp = mSettings.mPermissions.get(perm); 8640 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8641 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8642 if (appOpPkgs != null) { 8643 appOpPkgs.remove(pkg.packageName); 8644 if (appOpPkgs.isEmpty()) { 8645 mAppOpPermissionPackages.remove(perm); 8646 } 8647 } 8648 } 8649 } 8650 if (r != null) { 8651 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8652 } 8653 8654 N = pkg.instrumentation.size(); 8655 r = null; 8656 for (i=0; i<N; i++) { 8657 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8658 mInstrumentation.remove(a.getComponentName()); 8659 if (DEBUG_REMOVE && chatty) { 8660 if (r == null) { 8661 r = new StringBuilder(256); 8662 } else { 8663 r.append(' '); 8664 } 8665 r.append(a.info.name); 8666 } 8667 } 8668 if (r != null) { 8669 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8670 } 8671 8672 r = null; 8673 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8674 // Only system apps can hold shared libraries. 8675 if (pkg.libraryNames != null) { 8676 for (i=0; i<pkg.libraryNames.size(); i++) { 8677 String name = pkg.libraryNames.get(i); 8678 SharedLibraryEntry cur = mSharedLibraries.get(name); 8679 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8680 mSharedLibraries.remove(name); 8681 if (DEBUG_REMOVE && chatty) { 8682 if (r == null) { 8683 r = new StringBuilder(256); 8684 } else { 8685 r.append(' '); 8686 } 8687 r.append(name); 8688 } 8689 } 8690 } 8691 } 8692 } 8693 if (r != null) { 8694 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8695 } 8696 } 8697 8698 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8699 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8700 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8701 return true; 8702 } 8703 } 8704 return false; 8705 } 8706 8707 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8708 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8709 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8710 8711 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8712 int flags) { 8713 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8714 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8715 } 8716 8717 private void updatePermissionsLPw(String changingPkg, 8718 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8719 // Make sure there are no dangling permission trees. 8720 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8721 while (it.hasNext()) { 8722 final BasePermission bp = it.next(); 8723 if (bp.packageSetting == null) { 8724 // We may not yet have parsed the package, so just see if 8725 // we still know about its settings. 8726 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8727 } 8728 if (bp.packageSetting == null) { 8729 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8730 + " from package " + bp.sourcePackage); 8731 it.remove(); 8732 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8733 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8734 Slog.i(TAG, "Removing old permission tree: " + bp.name 8735 + " from package " + bp.sourcePackage); 8736 flags |= UPDATE_PERMISSIONS_ALL; 8737 it.remove(); 8738 } 8739 } 8740 } 8741 8742 // Make sure all dynamic permissions have been assigned to a package, 8743 // and make sure there are no dangling permissions. 8744 it = mSettings.mPermissions.values().iterator(); 8745 while (it.hasNext()) { 8746 final BasePermission bp = it.next(); 8747 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8748 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8749 + bp.name + " pkg=" + bp.sourcePackage 8750 + " info=" + bp.pendingInfo); 8751 if (bp.packageSetting == null && bp.pendingInfo != null) { 8752 final BasePermission tree = findPermissionTreeLP(bp.name); 8753 if (tree != null && tree.perm != null) { 8754 bp.packageSetting = tree.packageSetting; 8755 bp.perm = new PackageParser.Permission(tree.perm.owner, 8756 new PermissionInfo(bp.pendingInfo)); 8757 bp.perm.info.packageName = tree.perm.info.packageName; 8758 bp.perm.info.name = bp.name; 8759 bp.uid = tree.uid; 8760 } 8761 } 8762 } 8763 if (bp.packageSetting == null) { 8764 // We may not yet have parsed the package, so just see if 8765 // we still know about its settings. 8766 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8767 } 8768 if (bp.packageSetting == null) { 8769 Slog.w(TAG, "Removing dangling permission: " + bp.name 8770 + " from package " + bp.sourcePackage); 8771 it.remove(); 8772 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8773 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8774 Slog.i(TAG, "Removing old permission: " + bp.name 8775 + " from package " + bp.sourcePackage); 8776 flags |= UPDATE_PERMISSIONS_ALL; 8777 it.remove(); 8778 } 8779 } 8780 } 8781 8782 // Now update the permissions for all packages, in particular 8783 // replace the granted permissions of the system packages. 8784 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8785 for (PackageParser.Package pkg : mPackages.values()) { 8786 if (pkg != pkgInfo) { 8787 // Only replace for packages on requested volume 8788 final String volumeUuid = getVolumeUuidForPackage(pkg); 8789 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8790 && Objects.equals(replaceVolumeUuid, volumeUuid); 8791 grantPermissionsLPw(pkg, replace, changingPkg); 8792 } 8793 } 8794 } 8795 8796 if (pkgInfo != null) { 8797 // Only replace for packages on requested volume 8798 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8799 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8800 && Objects.equals(replaceVolumeUuid, volumeUuid); 8801 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8802 } 8803 } 8804 8805 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8806 String packageOfInterest) { 8807 // IMPORTANT: There are two types of permissions: install and runtime. 8808 // Install time permissions are granted when the app is installed to 8809 // all device users and users added in the future. Runtime permissions 8810 // are granted at runtime explicitly to specific users. Normal and signature 8811 // protected permissions are install time permissions. Dangerous permissions 8812 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8813 // otherwise they are runtime permissions. This function does not manage 8814 // runtime permissions except for the case an app targeting Lollipop MR1 8815 // being upgraded to target a newer SDK, in which case dangerous permissions 8816 // are transformed from install time to runtime ones. 8817 8818 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8819 if (ps == null) { 8820 return; 8821 } 8822 8823 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8824 8825 PermissionsState permissionsState = ps.getPermissionsState(); 8826 PermissionsState origPermissions = permissionsState; 8827 8828 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8829 8830 boolean runtimePermissionsRevoked = false; 8831 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8832 8833 boolean changedInstallPermission = false; 8834 8835 if (replace) { 8836 ps.installPermissionsFixed = false; 8837 if (!ps.isSharedUser()) { 8838 origPermissions = new PermissionsState(permissionsState); 8839 permissionsState.reset(); 8840 } else { 8841 // We need to know only about runtime permission changes since the 8842 // calling code always writes the install permissions state but 8843 // the runtime ones are written only if changed. The only cases of 8844 // changed runtime permissions here are promotion of an install to 8845 // runtime and revocation of a runtime from a shared user. 8846 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8847 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8848 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8849 runtimePermissionsRevoked = true; 8850 } 8851 } 8852 } 8853 8854 permissionsState.setGlobalGids(mGlobalGids); 8855 8856 final int N = pkg.requestedPermissions.size(); 8857 for (int i=0; i<N; i++) { 8858 final String name = pkg.requestedPermissions.get(i); 8859 final BasePermission bp = mSettings.mPermissions.get(name); 8860 8861 if (DEBUG_INSTALL) { 8862 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8863 } 8864 8865 if (bp == null || bp.packageSetting == null) { 8866 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8867 Slog.w(TAG, "Unknown permission " + name 8868 + " in package " + pkg.packageName); 8869 } 8870 continue; 8871 } 8872 8873 final String perm = bp.name; 8874 boolean allowedSig = false; 8875 int grant = GRANT_DENIED; 8876 8877 // Keep track of app op permissions. 8878 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8879 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8880 if (pkgs == null) { 8881 pkgs = new ArraySet<>(); 8882 mAppOpPermissionPackages.put(bp.name, pkgs); 8883 } 8884 pkgs.add(pkg.packageName); 8885 } 8886 8887 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8888 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 8889 >= Build.VERSION_CODES.M; 8890 switch (level) { 8891 case PermissionInfo.PROTECTION_NORMAL: { 8892 // For all apps normal permissions are install time ones. 8893 grant = GRANT_INSTALL; 8894 } break; 8895 8896 case PermissionInfo.PROTECTION_DANGEROUS: { 8897 // If a permission review is required for legacy apps we represent 8898 // their permissions as always granted runtime ones since we need 8899 // to keep the review required permission flag per user while an 8900 // install permission's state is shared across all users. 8901 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 8902 // For legacy apps dangerous permissions are install time ones. 8903 grant = GRANT_INSTALL; 8904 } else if (origPermissions.hasInstallPermission(bp.name)) { 8905 // For legacy apps that became modern, install becomes runtime. 8906 grant = GRANT_UPGRADE; 8907 } else if (mPromoteSystemApps 8908 && isSystemApp(ps) 8909 && mExistingSystemPackages.contains(ps.name)) { 8910 // For legacy system apps, install becomes runtime. 8911 // We cannot check hasInstallPermission() for system apps since those 8912 // permissions were granted implicitly and not persisted pre-M. 8913 grant = GRANT_UPGRADE; 8914 } else { 8915 // For modern apps keep runtime permissions unchanged. 8916 grant = GRANT_RUNTIME; 8917 } 8918 } break; 8919 8920 case PermissionInfo.PROTECTION_SIGNATURE: { 8921 // For all apps signature permissions are install time ones. 8922 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8923 if (allowedSig) { 8924 grant = GRANT_INSTALL; 8925 } 8926 } break; 8927 } 8928 8929 if (DEBUG_INSTALL) { 8930 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8931 } 8932 8933 if (grant != GRANT_DENIED) { 8934 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8935 // If this is an existing, non-system package, then 8936 // we can't add any new permissions to it. 8937 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8938 // Except... if this is a permission that was added 8939 // to the platform (note: need to only do this when 8940 // updating the platform). 8941 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8942 grant = GRANT_DENIED; 8943 } 8944 } 8945 } 8946 8947 switch (grant) { 8948 case GRANT_INSTALL: { 8949 // Revoke this as runtime permission to handle the case of 8950 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 8951 for (int userId : UserManagerService.getInstance().getUserIds()) { 8952 if (origPermissions.getRuntimePermissionState( 8953 bp.name, userId) != null) { 8954 // Revoke the runtime permission and clear the flags. 8955 origPermissions.revokeRuntimePermission(bp, userId); 8956 origPermissions.updatePermissionFlags(bp, userId, 8957 PackageManager.MASK_PERMISSION_FLAGS, 0); 8958 // If we revoked a permission permission, we have to write. 8959 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8960 changedRuntimePermissionUserIds, userId); 8961 } 8962 } 8963 // Grant an install permission. 8964 if (permissionsState.grantInstallPermission(bp) != 8965 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8966 changedInstallPermission = true; 8967 } 8968 } break; 8969 8970 case GRANT_RUNTIME: { 8971 // Grant previously granted runtime permissions. 8972 for (int userId : UserManagerService.getInstance().getUserIds()) { 8973 PermissionState permissionState = origPermissions 8974 .getRuntimePermissionState(bp.name, userId); 8975 int flags = permissionState != null 8976 ? permissionState.getFlags() : 0; 8977 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8978 if (permissionsState.grantRuntimePermission(bp, userId) == 8979 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8980 // If we cannot put the permission as it was, we have to write. 8981 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8982 changedRuntimePermissionUserIds, userId); 8983 } 8984 // If the app supports runtime permissions no need for a review. 8985 if (Build.PERMISSIONS_REVIEW_REQUIRED 8986 && appSupportsRuntimePermissions 8987 && (flags & PackageManager 8988 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 8989 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 8990 // Since we changed the flags, we have to write. 8991 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8992 changedRuntimePermissionUserIds, userId); 8993 } 8994 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 8995 && !appSupportsRuntimePermissions) { 8996 // For legacy apps that need a permission review, every new 8997 // runtime permission is granted but it is pending a review. 8998 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 8999 permissionsState.grantRuntimePermission(bp, userId); 9000 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9001 // We changed the permission and flags, hence have to write. 9002 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9003 changedRuntimePermissionUserIds, userId); 9004 } 9005 } 9006 // Propagate the permission flags. 9007 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9008 } 9009 } break; 9010 9011 case GRANT_UPGRADE: { 9012 // Grant runtime permissions for a previously held install permission. 9013 PermissionState permissionState = origPermissions 9014 .getInstallPermissionState(bp.name); 9015 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9016 9017 if (origPermissions.revokeInstallPermission(bp) 9018 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9019 // We will be transferring the permission flags, so clear them. 9020 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9021 PackageManager.MASK_PERMISSION_FLAGS, 0); 9022 changedInstallPermission = true; 9023 } 9024 9025 // If the permission is not to be promoted to runtime we ignore it and 9026 // also its other flags as they are not applicable to install permissions. 9027 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9028 for (int userId : currentUserIds) { 9029 if (permissionsState.grantRuntimePermission(bp, userId) != 9030 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9031 // Transfer the permission flags. 9032 permissionsState.updatePermissionFlags(bp, userId, 9033 flags, flags); 9034 // If we granted the permission, we have to write. 9035 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9036 changedRuntimePermissionUserIds, userId); 9037 } 9038 } 9039 } 9040 } break; 9041 9042 default: { 9043 if (packageOfInterest == null 9044 || packageOfInterest.equals(pkg.packageName)) { 9045 Slog.w(TAG, "Not granting permission " + perm 9046 + " to package " + pkg.packageName 9047 + " because it was previously installed without"); 9048 } 9049 } break; 9050 } 9051 } else { 9052 if (permissionsState.revokeInstallPermission(bp) != 9053 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9054 // Also drop the permission flags. 9055 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9056 PackageManager.MASK_PERMISSION_FLAGS, 0); 9057 changedInstallPermission = true; 9058 Slog.i(TAG, "Un-granting permission " + perm 9059 + " from package " + pkg.packageName 9060 + " (protectionLevel=" + bp.protectionLevel 9061 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9062 + ")"); 9063 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9064 // Don't print warning for app op permissions, since it is fine for them 9065 // not to be granted, there is a UI for the user to decide. 9066 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9067 Slog.w(TAG, "Not granting permission " + perm 9068 + " to package " + pkg.packageName 9069 + " (protectionLevel=" + bp.protectionLevel 9070 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9071 + ")"); 9072 } 9073 } 9074 } 9075 } 9076 9077 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9078 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9079 // This is the first that we have heard about this package, so the 9080 // permissions we have now selected are fixed until explicitly 9081 // changed. 9082 ps.installPermissionsFixed = true; 9083 } 9084 9085 // Persist the runtime permissions state for users with changes. If permissions 9086 // were revoked because no app in the shared user declares them we have to 9087 // write synchronously to avoid losing runtime permissions state. 9088 for (int userId : changedRuntimePermissionUserIds) { 9089 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9090 } 9091 9092 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9093 } 9094 9095 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9096 boolean allowed = false; 9097 final int NP = PackageParser.NEW_PERMISSIONS.length; 9098 for (int ip=0; ip<NP; ip++) { 9099 final PackageParser.NewPermissionInfo npi 9100 = PackageParser.NEW_PERMISSIONS[ip]; 9101 if (npi.name.equals(perm) 9102 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9103 allowed = true; 9104 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9105 + pkg.packageName); 9106 break; 9107 } 9108 } 9109 return allowed; 9110 } 9111 9112 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9113 BasePermission bp, PermissionsState origPermissions) { 9114 boolean allowed; 9115 allowed = (compareSignatures( 9116 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9117 == PackageManager.SIGNATURE_MATCH) 9118 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9119 == PackageManager.SIGNATURE_MATCH); 9120 if (!allowed && (bp.protectionLevel 9121 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9122 if (isSystemApp(pkg)) { 9123 // For updated system applications, a system permission 9124 // is granted only if it had been defined by the original application. 9125 if (pkg.isUpdatedSystemApp()) { 9126 final PackageSetting sysPs = mSettings 9127 .getDisabledSystemPkgLPr(pkg.packageName); 9128 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 9129 // If the original was granted this permission, we take 9130 // that grant decision as read and propagate it to the 9131 // update. 9132 if (sysPs.isPrivileged()) { 9133 allowed = true; 9134 } 9135 } else { 9136 // The system apk may have been updated with an older 9137 // version of the one on the data partition, but which 9138 // granted a new system permission that it didn't have 9139 // before. In this case we do want to allow the app to 9140 // now get the new permission if the ancestral apk is 9141 // privileged to get it. 9142 if (sysPs.pkg != null && sysPs.isPrivileged()) { 9143 for (int j=0; 9144 j<sysPs.pkg.requestedPermissions.size(); j++) { 9145 if (perm.equals( 9146 sysPs.pkg.requestedPermissions.get(j))) { 9147 allowed = true; 9148 break; 9149 } 9150 } 9151 } 9152 } 9153 } else { 9154 allowed = isPrivilegedApp(pkg); 9155 } 9156 } 9157 } 9158 if (!allowed) { 9159 if (!allowed && (bp.protectionLevel 9160 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9161 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9162 // If this was a previously normal/dangerous permission that got moved 9163 // to a system permission as part of the runtime permission redesign, then 9164 // we still want to blindly grant it to old apps. 9165 allowed = true; 9166 } 9167 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9168 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9169 // If this permission is to be granted to the system installer and 9170 // this app is an installer, then it gets the permission. 9171 allowed = true; 9172 } 9173 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9174 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9175 // If this permission is to be granted to the system verifier and 9176 // this app is a verifier, then it gets the permission. 9177 allowed = true; 9178 } 9179 if (!allowed && (bp.protectionLevel 9180 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9181 && isSystemApp(pkg)) { 9182 // Any pre-installed system app is allowed to get this permission. 9183 allowed = true; 9184 } 9185 if (!allowed && (bp.protectionLevel 9186 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9187 // For development permissions, a development permission 9188 // is granted only if it was already granted. 9189 allowed = origPermissions.hasInstallPermission(perm); 9190 } 9191 } 9192 return allowed; 9193 } 9194 9195 final class ActivityIntentResolver 9196 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9197 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9198 boolean defaultOnly, int userId) { 9199 if (!sUserManager.exists(userId)) return null; 9200 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9201 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9202 } 9203 9204 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9205 int userId) { 9206 if (!sUserManager.exists(userId)) return null; 9207 mFlags = flags; 9208 return super.queryIntent(intent, resolvedType, 9209 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9210 } 9211 9212 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9213 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9214 if (!sUserManager.exists(userId)) return null; 9215 if (packageActivities == null) { 9216 return null; 9217 } 9218 mFlags = flags; 9219 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9220 final int N = packageActivities.size(); 9221 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9222 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9223 9224 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9225 for (int i = 0; i < N; ++i) { 9226 intentFilters = packageActivities.get(i).intents; 9227 if (intentFilters != null && intentFilters.size() > 0) { 9228 PackageParser.ActivityIntentInfo[] array = 9229 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9230 intentFilters.toArray(array); 9231 listCut.add(array); 9232 } 9233 } 9234 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9235 } 9236 9237 public final void addActivity(PackageParser.Activity a, String type) { 9238 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9239 mActivities.put(a.getComponentName(), a); 9240 if (DEBUG_SHOW_INFO) 9241 Log.v( 9242 TAG, " " + type + " " + 9243 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9244 if (DEBUG_SHOW_INFO) 9245 Log.v(TAG, " Class=" + a.info.name); 9246 final int NI = a.intents.size(); 9247 for (int j=0; j<NI; j++) { 9248 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9249 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9250 intent.setPriority(0); 9251 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9252 + a.className + " with priority > 0, forcing to 0"); 9253 } 9254 if (DEBUG_SHOW_INFO) { 9255 Log.v(TAG, " IntentFilter:"); 9256 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9257 } 9258 if (!intent.debugCheck()) { 9259 Log.w(TAG, "==> For Activity " + a.info.name); 9260 } 9261 addFilter(intent); 9262 } 9263 } 9264 9265 public final void removeActivity(PackageParser.Activity a, String type) { 9266 mActivities.remove(a.getComponentName()); 9267 if (DEBUG_SHOW_INFO) { 9268 Log.v(TAG, " " + type + " " 9269 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9270 : a.info.name) + ":"); 9271 Log.v(TAG, " Class=" + a.info.name); 9272 } 9273 final int NI = a.intents.size(); 9274 for (int j=0; j<NI; j++) { 9275 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9276 if (DEBUG_SHOW_INFO) { 9277 Log.v(TAG, " IntentFilter:"); 9278 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9279 } 9280 removeFilter(intent); 9281 } 9282 } 9283 9284 @Override 9285 protected boolean allowFilterResult( 9286 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9287 ActivityInfo filterAi = filter.activity.info; 9288 for (int i=dest.size()-1; i>=0; i--) { 9289 ActivityInfo destAi = dest.get(i).activityInfo; 9290 if (destAi.name == filterAi.name 9291 && destAi.packageName == filterAi.packageName) { 9292 return false; 9293 } 9294 } 9295 return true; 9296 } 9297 9298 @Override 9299 protected ActivityIntentInfo[] newArray(int size) { 9300 return new ActivityIntentInfo[size]; 9301 } 9302 9303 @Override 9304 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9305 if (!sUserManager.exists(userId)) return true; 9306 PackageParser.Package p = filter.activity.owner; 9307 if (p != null) { 9308 PackageSetting ps = (PackageSetting)p.mExtras; 9309 if (ps != null) { 9310 // System apps are never considered stopped for purposes of 9311 // filtering, because there may be no way for the user to 9312 // actually re-launch them. 9313 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9314 && ps.getStopped(userId); 9315 } 9316 } 9317 return false; 9318 } 9319 9320 @Override 9321 protected boolean isPackageForFilter(String packageName, 9322 PackageParser.ActivityIntentInfo info) { 9323 return packageName.equals(info.activity.owner.packageName); 9324 } 9325 9326 @Override 9327 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9328 int match, int userId) { 9329 if (!sUserManager.exists(userId)) return null; 9330 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9331 return null; 9332 } 9333 final PackageParser.Activity activity = info.activity; 9334 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9335 if (ps == null) { 9336 return null; 9337 } 9338 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9339 ps.readUserState(userId), userId); 9340 if (ai == null) { 9341 return null; 9342 } 9343 final ResolveInfo res = new ResolveInfo(); 9344 res.activityInfo = ai; 9345 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9346 res.filter = info; 9347 } 9348 if (info != null) { 9349 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9350 } 9351 res.priority = info.getPriority(); 9352 res.preferredOrder = activity.owner.mPreferredOrder; 9353 //System.out.println("Result: " + res.activityInfo.className + 9354 // " = " + res.priority); 9355 res.match = match; 9356 res.isDefault = info.hasDefault; 9357 res.labelRes = info.labelRes; 9358 res.nonLocalizedLabel = info.nonLocalizedLabel; 9359 if (userNeedsBadging(userId)) { 9360 res.noResourceId = true; 9361 } else { 9362 res.icon = info.icon; 9363 } 9364 res.iconResourceId = info.icon; 9365 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9366 return res; 9367 } 9368 9369 @Override 9370 protected void sortResults(List<ResolveInfo> results) { 9371 Collections.sort(results, mResolvePrioritySorter); 9372 } 9373 9374 @Override 9375 protected void dumpFilter(PrintWriter out, String prefix, 9376 PackageParser.ActivityIntentInfo filter) { 9377 out.print(prefix); out.print( 9378 Integer.toHexString(System.identityHashCode(filter.activity))); 9379 out.print(' '); 9380 filter.activity.printComponentShortName(out); 9381 out.print(" filter "); 9382 out.println(Integer.toHexString(System.identityHashCode(filter))); 9383 } 9384 9385 @Override 9386 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9387 return filter.activity; 9388 } 9389 9390 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9391 PackageParser.Activity activity = (PackageParser.Activity)label; 9392 out.print(prefix); out.print( 9393 Integer.toHexString(System.identityHashCode(activity))); 9394 out.print(' '); 9395 activity.printComponentShortName(out); 9396 if (count > 1) { 9397 out.print(" ("); out.print(count); out.print(" filters)"); 9398 } 9399 out.println(); 9400 } 9401 9402// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9403// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9404// final List<ResolveInfo> retList = Lists.newArrayList(); 9405// while (i.hasNext()) { 9406// final ResolveInfo resolveInfo = i.next(); 9407// if (isEnabledLP(resolveInfo.activityInfo)) { 9408// retList.add(resolveInfo); 9409// } 9410// } 9411// return retList; 9412// } 9413 9414 // Keys are String (activity class name), values are Activity. 9415 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9416 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9417 private int mFlags; 9418 } 9419 9420 private final class ServiceIntentResolver 9421 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9422 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9423 boolean defaultOnly, int userId) { 9424 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9425 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9426 } 9427 9428 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9429 int userId) { 9430 if (!sUserManager.exists(userId)) return null; 9431 mFlags = flags; 9432 return super.queryIntent(intent, resolvedType, 9433 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9434 } 9435 9436 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9437 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9438 if (!sUserManager.exists(userId)) return null; 9439 if (packageServices == null) { 9440 return null; 9441 } 9442 mFlags = flags; 9443 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9444 final int N = packageServices.size(); 9445 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9446 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9447 9448 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9449 for (int i = 0; i < N; ++i) { 9450 intentFilters = packageServices.get(i).intents; 9451 if (intentFilters != null && intentFilters.size() > 0) { 9452 PackageParser.ServiceIntentInfo[] array = 9453 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9454 intentFilters.toArray(array); 9455 listCut.add(array); 9456 } 9457 } 9458 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9459 } 9460 9461 public final void addService(PackageParser.Service s) { 9462 mServices.put(s.getComponentName(), s); 9463 if (DEBUG_SHOW_INFO) { 9464 Log.v(TAG, " " 9465 + (s.info.nonLocalizedLabel != null 9466 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9467 Log.v(TAG, " Class=" + s.info.name); 9468 } 9469 final int NI = s.intents.size(); 9470 int j; 9471 for (j=0; j<NI; j++) { 9472 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9473 if (DEBUG_SHOW_INFO) { 9474 Log.v(TAG, " IntentFilter:"); 9475 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9476 } 9477 if (!intent.debugCheck()) { 9478 Log.w(TAG, "==> For Service " + s.info.name); 9479 } 9480 addFilter(intent); 9481 } 9482 } 9483 9484 public final void removeService(PackageParser.Service s) { 9485 mServices.remove(s.getComponentName()); 9486 if (DEBUG_SHOW_INFO) { 9487 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9488 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9489 Log.v(TAG, " Class=" + s.info.name); 9490 } 9491 final int NI = s.intents.size(); 9492 int j; 9493 for (j=0; j<NI; j++) { 9494 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9495 if (DEBUG_SHOW_INFO) { 9496 Log.v(TAG, " IntentFilter:"); 9497 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9498 } 9499 removeFilter(intent); 9500 } 9501 } 9502 9503 @Override 9504 protected boolean allowFilterResult( 9505 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9506 ServiceInfo filterSi = filter.service.info; 9507 for (int i=dest.size()-1; i>=0; i--) { 9508 ServiceInfo destAi = dest.get(i).serviceInfo; 9509 if (destAi.name == filterSi.name 9510 && destAi.packageName == filterSi.packageName) { 9511 return false; 9512 } 9513 } 9514 return true; 9515 } 9516 9517 @Override 9518 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9519 return new PackageParser.ServiceIntentInfo[size]; 9520 } 9521 9522 @Override 9523 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9524 if (!sUserManager.exists(userId)) return true; 9525 PackageParser.Package p = filter.service.owner; 9526 if (p != null) { 9527 PackageSetting ps = (PackageSetting)p.mExtras; 9528 if (ps != null) { 9529 // System apps are never considered stopped for purposes of 9530 // filtering, because there may be no way for the user to 9531 // actually re-launch them. 9532 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9533 && ps.getStopped(userId); 9534 } 9535 } 9536 return false; 9537 } 9538 9539 @Override 9540 protected boolean isPackageForFilter(String packageName, 9541 PackageParser.ServiceIntentInfo info) { 9542 return packageName.equals(info.service.owner.packageName); 9543 } 9544 9545 @Override 9546 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9547 int match, int userId) { 9548 if (!sUserManager.exists(userId)) return null; 9549 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9550 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9551 return null; 9552 } 9553 final PackageParser.Service service = info.service; 9554 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9555 if (ps == null) { 9556 return null; 9557 } 9558 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9559 ps.readUserState(userId), userId); 9560 if (si == null) { 9561 return null; 9562 } 9563 final ResolveInfo res = new ResolveInfo(); 9564 res.serviceInfo = si; 9565 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9566 res.filter = filter; 9567 } 9568 res.priority = info.getPriority(); 9569 res.preferredOrder = service.owner.mPreferredOrder; 9570 res.match = match; 9571 res.isDefault = info.hasDefault; 9572 res.labelRes = info.labelRes; 9573 res.nonLocalizedLabel = info.nonLocalizedLabel; 9574 res.icon = info.icon; 9575 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9576 return res; 9577 } 9578 9579 @Override 9580 protected void sortResults(List<ResolveInfo> results) { 9581 Collections.sort(results, mResolvePrioritySorter); 9582 } 9583 9584 @Override 9585 protected void dumpFilter(PrintWriter out, String prefix, 9586 PackageParser.ServiceIntentInfo filter) { 9587 out.print(prefix); out.print( 9588 Integer.toHexString(System.identityHashCode(filter.service))); 9589 out.print(' '); 9590 filter.service.printComponentShortName(out); 9591 out.print(" filter "); 9592 out.println(Integer.toHexString(System.identityHashCode(filter))); 9593 } 9594 9595 @Override 9596 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9597 return filter.service; 9598 } 9599 9600 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9601 PackageParser.Service service = (PackageParser.Service)label; 9602 out.print(prefix); out.print( 9603 Integer.toHexString(System.identityHashCode(service))); 9604 out.print(' '); 9605 service.printComponentShortName(out); 9606 if (count > 1) { 9607 out.print(" ("); out.print(count); out.print(" filters)"); 9608 } 9609 out.println(); 9610 } 9611 9612// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9613// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9614// final List<ResolveInfo> retList = Lists.newArrayList(); 9615// while (i.hasNext()) { 9616// final ResolveInfo resolveInfo = (ResolveInfo) i; 9617// if (isEnabledLP(resolveInfo.serviceInfo)) { 9618// retList.add(resolveInfo); 9619// } 9620// } 9621// return retList; 9622// } 9623 9624 // Keys are String (activity class name), values are Activity. 9625 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9626 = new ArrayMap<ComponentName, PackageParser.Service>(); 9627 private int mFlags; 9628 }; 9629 9630 private final class ProviderIntentResolver 9631 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9632 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9633 boolean defaultOnly, int userId) { 9634 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9635 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9636 } 9637 9638 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9639 int userId) { 9640 if (!sUserManager.exists(userId)) 9641 return null; 9642 mFlags = flags; 9643 return super.queryIntent(intent, resolvedType, 9644 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9645 } 9646 9647 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9648 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9649 if (!sUserManager.exists(userId)) 9650 return null; 9651 if (packageProviders == null) { 9652 return null; 9653 } 9654 mFlags = flags; 9655 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9656 final int N = packageProviders.size(); 9657 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9658 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9659 9660 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9661 for (int i = 0; i < N; ++i) { 9662 intentFilters = packageProviders.get(i).intents; 9663 if (intentFilters != null && intentFilters.size() > 0) { 9664 PackageParser.ProviderIntentInfo[] array = 9665 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9666 intentFilters.toArray(array); 9667 listCut.add(array); 9668 } 9669 } 9670 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9671 } 9672 9673 public final void addProvider(PackageParser.Provider p) { 9674 if (mProviders.containsKey(p.getComponentName())) { 9675 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9676 return; 9677 } 9678 9679 mProviders.put(p.getComponentName(), p); 9680 if (DEBUG_SHOW_INFO) { 9681 Log.v(TAG, " " 9682 + (p.info.nonLocalizedLabel != null 9683 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9684 Log.v(TAG, " Class=" + p.info.name); 9685 } 9686 final int NI = p.intents.size(); 9687 int j; 9688 for (j = 0; j < NI; j++) { 9689 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9690 if (DEBUG_SHOW_INFO) { 9691 Log.v(TAG, " IntentFilter:"); 9692 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9693 } 9694 if (!intent.debugCheck()) { 9695 Log.w(TAG, "==> For Provider " + p.info.name); 9696 } 9697 addFilter(intent); 9698 } 9699 } 9700 9701 public final void removeProvider(PackageParser.Provider p) { 9702 mProviders.remove(p.getComponentName()); 9703 if (DEBUG_SHOW_INFO) { 9704 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9705 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9706 Log.v(TAG, " Class=" + p.info.name); 9707 } 9708 final int NI = p.intents.size(); 9709 int j; 9710 for (j = 0; j < NI; j++) { 9711 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9712 if (DEBUG_SHOW_INFO) { 9713 Log.v(TAG, " IntentFilter:"); 9714 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9715 } 9716 removeFilter(intent); 9717 } 9718 } 9719 9720 @Override 9721 protected boolean allowFilterResult( 9722 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9723 ProviderInfo filterPi = filter.provider.info; 9724 for (int i = dest.size() - 1; i >= 0; i--) { 9725 ProviderInfo destPi = dest.get(i).providerInfo; 9726 if (destPi.name == filterPi.name 9727 && destPi.packageName == filterPi.packageName) { 9728 return false; 9729 } 9730 } 9731 return true; 9732 } 9733 9734 @Override 9735 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9736 return new PackageParser.ProviderIntentInfo[size]; 9737 } 9738 9739 @Override 9740 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9741 if (!sUserManager.exists(userId)) 9742 return true; 9743 PackageParser.Package p = filter.provider.owner; 9744 if (p != null) { 9745 PackageSetting ps = (PackageSetting) p.mExtras; 9746 if (ps != null) { 9747 // System apps are never considered stopped for purposes of 9748 // filtering, because there may be no way for the user to 9749 // actually re-launch them. 9750 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9751 && ps.getStopped(userId); 9752 } 9753 } 9754 return false; 9755 } 9756 9757 @Override 9758 protected boolean isPackageForFilter(String packageName, 9759 PackageParser.ProviderIntentInfo info) { 9760 return packageName.equals(info.provider.owner.packageName); 9761 } 9762 9763 @Override 9764 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9765 int match, int userId) { 9766 if (!sUserManager.exists(userId)) 9767 return null; 9768 final PackageParser.ProviderIntentInfo info = filter; 9769 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 9770 return null; 9771 } 9772 final PackageParser.Provider provider = info.provider; 9773 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9774 if (ps == null) { 9775 return null; 9776 } 9777 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9778 ps.readUserState(userId), userId); 9779 if (pi == null) { 9780 return null; 9781 } 9782 final ResolveInfo res = new ResolveInfo(); 9783 res.providerInfo = pi; 9784 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9785 res.filter = filter; 9786 } 9787 res.priority = info.getPriority(); 9788 res.preferredOrder = provider.owner.mPreferredOrder; 9789 res.match = match; 9790 res.isDefault = info.hasDefault; 9791 res.labelRes = info.labelRes; 9792 res.nonLocalizedLabel = info.nonLocalizedLabel; 9793 res.icon = info.icon; 9794 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9795 return res; 9796 } 9797 9798 @Override 9799 protected void sortResults(List<ResolveInfo> results) { 9800 Collections.sort(results, mResolvePrioritySorter); 9801 } 9802 9803 @Override 9804 protected void dumpFilter(PrintWriter out, String prefix, 9805 PackageParser.ProviderIntentInfo filter) { 9806 out.print(prefix); 9807 out.print( 9808 Integer.toHexString(System.identityHashCode(filter.provider))); 9809 out.print(' '); 9810 filter.provider.printComponentShortName(out); 9811 out.print(" filter "); 9812 out.println(Integer.toHexString(System.identityHashCode(filter))); 9813 } 9814 9815 @Override 9816 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9817 return filter.provider; 9818 } 9819 9820 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9821 PackageParser.Provider provider = (PackageParser.Provider)label; 9822 out.print(prefix); out.print( 9823 Integer.toHexString(System.identityHashCode(provider))); 9824 out.print(' '); 9825 provider.printComponentShortName(out); 9826 if (count > 1) { 9827 out.print(" ("); out.print(count); out.print(" filters)"); 9828 } 9829 out.println(); 9830 } 9831 9832 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9833 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9834 private int mFlags; 9835 } 9836 9837 private static final class EphemeralIntentResolver 9838 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 9839 @Override 9840 protected EphemeralResolveIntentInfo[] newArray(int size) { 9841 return new EphemeralResolveIntentInfo[size]; 9842 } 9843 9844 @Override 9845 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 9846 return true; 9847 } 9848 9849 @Override 9850 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 9851 int userId) { 9852 if (!sUserManager.exists(userId)) { 9853 return null; 9854 } 9855 return info.getEphemeralResolveInfo(); 9856 } 9857 } 9858 9859 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9860 new Comparator<ResolveInfo>() { 9861 public int compare(ResolveInfo r1, ResolveInfo r2) { 9862 int v1 = r1.priority; 9863 int v2 = r2.priority; 9864 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9865 if (v1 != v2) { 9866 return (v1 > v2) ? -1 : 1; 9867 } 9868 v1 = r1.preferredOrder; 9869 v2 = r2.preferredOrder; 9870 if (v1 != v2) { 9871 return (v1 > v2) ? -1 : 1; 9872 } 9873 if (r1.isDefault != r2.isDefault) { 9874 return r1.isDefault ? -1 : 1; 9875 } 9876 v1 = r1.match; 9877 v2 = r2.match; 9878 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9879 if (v1 != v2) { 9880 return (v1 > v2) ? -1 : 1; 9881 } 9882 if (r1.system != r2.system) { 9883 return r1.system ? -1 : 1; 9884 } 9885 if (r1.activityInfo != null) { 9886 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 9887 } 9888 if (r1.serviceInfo != null) { 9889 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 9890 } 9891 if (r1.providerInfo != null) { 9892 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 9893 } 9894 return 0; 9895 } 9896 }; 9897 9898 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9899 new Comparator<ProviderInfo>() { 9900 public int compare(ProviderInfo p1, ProviderInfo p2) { 9901 final int v1 = p1.initOrder; 9902 final int v2 = p2.initOrder; 9903 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9904 } 9905 }; 9906 9907 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 9908 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 9909 final int[] userIds) { 9910 mHandler.post(new Runnable() { 9911 @Override 9912 public void run() { 9913 try { 9914 final IActivityManager am = ActivityManagerNative.getDefault(); 9915 if (am == null) return; 9916 final int[] resolvedUserIds; 9917 if (userIds == null) { 9918 resolvedUserIds = am.getRunningUserIds(); 9919 } else { 9920 resolvedUserIds = userIds; 9921 } 9922 for (int id : resolvedUserIds) { 9923 final Intent intent = new Intent(action, 9924 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9925 if (extras != null) { 9926 intent.putExtras(extras); 9927 } 9928 if (targetPkg != null) { 9929 intent.setPackage(targetPkg); 9930 } 9931 // Modify the UID when posting to other users 9932 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9933 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9934 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9935 intent.putExtra(Intent.EXTRA_UID, uid); 9936 } 9937 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9938 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 9939 if (DEBUG_BROADCASTS) { 9940 RuntimeException here = new RuntimeException("here"); 9941 here.fillInStackTrace(); 9942 Slog.d(TAG, "Sending to user " + id + ": " 9943 + intent.toShortString(false, true, false, false) 9944 + " " + intent.getExtras(), here); 9945 } 9946 am.broadcastIntent(null, intent, null, finishedReceiver, 9947 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9948 null, finishedReceiver != null, false, id); 9949 } 9950 } catch (RemoteException ex) { 9951 } 9952 } 9953 }); 9954 } 9955 9956 /** 9957 * Check if the external storage media is available. This is true if there 9958 * is a mounted external storage medium or if the external storage is 9959 * emulated. 9960 */ 9961 private boolean isExternalMediaAvailable() { 9962 return mMediaMounted || Environment.isExternalStorageEmulated(); 9963 } 9964 9965 @Override 9966 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9967 // writer 9968 synchronized (mPackages) { 9969 if (!isExternalMediaAvailable()) { 9970 // If the external storage is no longer mounted at this point, 9971 // the caller may not have been able to delete all of this 9972 // packages files and can not delete any more. Bail. 9973 return null; 9974 } 9975 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9976 if (lastPackage != null) { 9977 pkgs.remove(lastPackage); 9978 } 9979 if (pkgs.size() > 0) { 9980 return pkgs.get(0); 9981 } 9982 } 9983 return null; 9984 } 9985 9986 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9987 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9988 userId, andCode ? 1 : 0, packageName); 9989 if (mSystemReady) { 9990 msg.sendToTarget(); 9991 } else { 9992 if (mPostSystemReadyMessages == null) { 9993 mPostSystemReadyMessages = new ArrayList<>(); 9994 } 9995 mPostSystemReadyMessages.add(msg); 9996 } 9997 } 9998 9999 void startCleaningPackages() { 10000 // reader 10001 synchronized (mPackages) { 10002 if (!isExternalMediaAvailable()) { 10003 return; 10004 } 10005 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10006 return; 10007 } 10008 } 10009 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10010 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10011 IActivityManager am = ActivityManagerNative.getDefault(); 10012 if (am != null) { 10013 try { 10014 am.startService(null, intent, null, mContext.getOpPackageName(), 10015 UserHandle.USER_SYSTEM); 10016 } catch (RemoteException e) { 10017 } 10018 } 10019 } 10020 10021 @Override 10022 public void installPackage(String originPath, IPackageInstallObserver2 observer, 10023 int installFlags, String installerPackageName, VerificationParams verificationParams, 10024 String packageAbiOverride) { 10025 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 10026 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 10027 } 10028 10029 @Override 10030 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10031 int installFlags, String installerPackageName, VerificationParams verificationParams, 10032 String packageAbiOverride, int userId) { 10033 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10034 10035 final int callingUid = Binder.getCallingUid(); 10036 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 10037 10038 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10039 try { 10040 if (observer != null) { 10041 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10042 } 10043 } catch (RemoteException re) { 10044 } 10045 return; 10046 } 10047 10048 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10049 installFlags |= PackageManager.INSTALL_FROM_ADB; 10050 10051 } else { 10052 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10053 // about installerPackageName. 10054 10055 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10056 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10057 } 10058 10059 UserHandle user; 10060 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10061 user = UserHandle.ALL; 10062 } else { 10063 user = new UserHandle(userId); 10064 } 10065 10066 // Only system components can circumvent runtime permissions when installing. 10067 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10068 && mContext.checkCallingOrSelfPermission(Manifest.permission 10069 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10070 throw new SecurityException("You need the " 10071 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10072 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10073 } 10074 10075 verificationParams.setInstallerUid(callingUid); 10076 10077 final File originFile = new File(originPath); 10078 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10079 10080 final Message msg = mHandler.obtainMessage(INIT_COPY); 10081 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 10082 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 10083 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10084 msg.obj = params; 10085 10086 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10087 System.identityHashCode(msg.obj)); 10088 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10089 System.identityHashCode(msg.obj)); 10090 10091 mHandler.sendMessage(msg); 10092 } 10093 10094 void installStage(String packageName, File stagedDir, String stagedCid, 10095 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10096 String installerPackageName, int installerUid, UserHandle user) { 10097 if (DEBUG_EPHEMERAL) { 10098 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10099 Slog.d(TAG, "Ephemeral install of " + packageName); 10100 } 10101 } 10102 final VerificationParams verifParams = new VerificationParams( 10103 null, sessionParams.originatingUri, sessionParams.referrerUri, 10104 sessionParams.originatingUid); 10105 verifParams.setInstallerUid(installerUid); 10106 10107 final OriginInfo origin; 10108 if (stagedDir != null) { 10109 origin = OriginInfo.fromStagedFile(stagedDir); 10110 } else { 10111 origin = OriginInfo.fromStagedContainer(stagedCid); 10112 } 10113 10114 final Message msg = mHandler.obtainMessage(INIT_COPY); 10115 final InstallParams params = new InstallParams(origin, null, observer, 10116 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10117 verifParams, user, sessionParams.abiOverride, 10118 sessionParams.grantedRuntimePermissions); 10119 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10120 msg.obj = params; 10121 10122 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10123 System.identityHashCode(msg.obj)); 10124 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10125 System.identityHashCode(msg.obj)); 10126 10127 mHandler.sendMessage(msg); 10128 } 10129 10130 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 10131 Bundle extras = new Bundle(1); 10132 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 10133 10134 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10135 packageName, extras, 0, null, null, new int[] {userId}); 10136 try { 10137 IActivityManager am = ActivityManagerNative.getDefault(); 10138 final boolean isSystem = 10139 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10140 if (isSystem && am.isUserRunning(userId, 0)) { 10141 // The just-installed/enabled app is bundled on the system, so presumed 10142 // to be able to run automatically without needing an explicit launch. 10143 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10144 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10145 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10146 .setPackage(packageName); 10147 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10148 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10149 } 10150 } catch (RemoteException e) { 10151 // shouldn't happen 10152 Slog.w(TAG, "Unable to bootstrap installed package", e); 10153 } 10154 } 10155 10156 @Override 10157 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10158 int userId) { 10159 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10160 PackageSetting pkgSetting; 10161 final int uid = Binder.getCallingUid(); 10162 enforceCrossUserPermission(uid, userId, true, true, 10163 "setApplicationHiddenSetting for user " + userId); 10164 10165 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10166 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10167 return false; 10168 } 10169 10170 long callingId = Binder.clearCallingIdentity(); 10171 try { 10172 boolean sendAdded = false; 10173 boolean sendRemoved = false; 10174 // writer 10175 synchronized (mPackages) { 10176 pkgSetting = mSettings.mPackages.get(packageName); 10177 if (pkgSetting == null) { 10178 return false; 10179 } 10180 if (pkgSetting.getHidden(userId) != hidden) { 10181 pkgSetting.setHidden(hidden, userId); 10182 mSettings.writePackageRestrictionsLPr(userId); 10183 if (hidden) { 10184 sendRemoved = true; 10185 } else { 10186 sendAdded = true; 10187 } 10188 } 10189 } 10190 if (sendAdded) { 10191 sendPackageAddedForUser(packageName, pkgSetting, userId); 10192 return true; 10193 } 10194 if (sendRemoved) { 10195 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10196 "hiding pkg"); 10197 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10198 return true; 10199 } 10200 } finally { 10201 Binder.restoreCallingIdentity(callingId); 10202 } 10203 return false; 10204 } 10205 10206 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10207 int userId) { 10208 final PackageRemovedInfo info = new PackageRemovedInfo(); 10209 info.removedPackage = packageName; 10210 info.removedUsers = new int[] {userId}; 10211 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10212 info.sendBroadcast(false, false, false); 10213 } 10214 10215 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10216 if (pkgList.length > 0) { 10217 Bundle extras = new Bundle(1); 10218 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10219 10220 sendPackageBroadcast( 10221 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10222 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10223 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10224 new int[] {userId}); 10225 } 10226 } 10227 10228 /** 10229 * Returns true if application is not found or there was an error. Otherwise it returns 10230 * the hidden state of the package for the given user. 10231 */ 10232 @Override 10233 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10234 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10235 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10236 false, "getApplicationHidden for user " + userId); 10237 PackageSetting pkgSetting; 10238 long callingId = Binder.clearCallingIdentity(); 10239 try { 10240 // writer 10241 synchronized (mPackages) { 10242 pkgSetting = mSettings.mPackages.get(packageName); 10243 if (pkgSetting == null) { 10244 return true; 10245 } 10246 return pkgSetting.getHidden(userId); 10247 } 10248 } finally { 10249 Binder.restoreCallingIdentity(callingId); 10250 } 10251 } 10252 10253 /** 10254 * @hide 10255 */ 10256 @Override 10257 public int installExistingPackageAsUser(String packageName, int userId) { 10258 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10259 null); 10260 PackageSetting pkgSetting; 10261 final int uid = Binder.getCallingUid(); 10262 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10263 + userId); 10264 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10265 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10266 } 10267 10268 long callingId = Binder.clearCallingIdentity(); 10269 try { 10270 boolean installed = false; 10271 10272 // writer 10273 synchronized (mPackages) { 10274 pkgSetting = mSettings.mPackages.get(packageName); 10275 if (pkgSetting == null) { 10276 return PackageManager.INSTALL_FAILED_INVALID_URI; 10277 } 10278 if (!pkgSetting.getInstalled(userId)) { 10279 pkgSetting.setInstalled(true, userId); 10280 pkgSetting.setHidden(false, userId); 10281 mSettings.writePackageRestrictionsLPr(userId); 10282 if (pkgSetting.pkg != null) { 10283 prepareAppDataAfterInstall(pkgSetting.pkg); 10284 } 10285 installed = true; 10286 } 10287 } 10288 10289 if (installed) { 10290 sendPackageAddedForUser(packageName, pkgSetting, userId); 10291 } 10292 } finally { 10293 Binder.restoreCallingIdentity(callingId); 10294 } 10295 10296 return PackageManager.INSTALL_SUCCEEDED; 10297 } 10298 10299 boolean isUserRestricted(int userId, String restrictionKey) { 10300 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10301 if (restrictions.getBoolean(restrictionKey, false)) { 10302 Log.w(TAG, "User is restricted: " + restrictionKey); 10303 return true; 10304 } 10305 return false; 10306 } 10307 10308 @Override 10309 public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) { 10310 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10311 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true, 10312 "setPackageSuspended for user " + userId); 10313 10314 // TODO: investigate and add more restrictions for suspending crucial packages. 10315 if (isPackageDeviceAdmin(packageName, userId)) { 10316 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10317 + "\": has active device admin"); 10318 return false; 10319 } 10320 10321 long callingId = Binder.clearCallingIdentity(); 10322 try { 10323 boolean changed = false; 10324 boolean success = false; 10325 int appId = -1; 10326 synchronized (mPackages) { 10327 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10328 if (pkgSetting != null) { 10329 if (pkgSetting.getSuspended(userId) != suspended) { 10330 pkgSetting.setSuspended(suspended, userId); 10331 mSettings.writePackageRestrictionsLPr(userId); 10332 appId = pkgSetting.appId; 10333 changed = true; 10334 } 10335 success = true; 10336 } 10337 } 10338 10339 if (changed) { 10340 sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended); 10341 if (suspended) { 10342 killApplication(packageName, UserHandle.getUid(userId, appId), 10343 "suspending package"); 10344 } 10345 } 10346 return success; 10347 } finally { 10348 Binder.restoreCallingIdentity(callingId); 10349 } 10350 } 10351 10352 @Override 10353 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10354 mContext.enforceCallingOrSelfPermission( 10355 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10356 "Only package verification agents can verify applications"); 10357 10358 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10359 final PackageVerificationResponse response = new PackageVerificationResponse( 10360 verificationCode, Binder.getCallingUid()); 10361 msg.arg1 = id; 10362 msg.obj = response; 10363 mHandler.sendMessage(msg); 10364 } 10365 10366 @Override 10367 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10368 long millisecondsToDelay) { 10369 mContext.enforceCallingOrSelfPermission( 10370 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10371 "Only package verification agents can extend verification timeouts"); 10372 10373 final PackageVerificationState state = mPendingVerification.get(id); 10374 final PackageVerificationResponse response = new PackageVerificationResponse( 10375 verificationCodeAtTimeout, Binder.getCallingUid()); 10376 10377 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10378 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10379 } 10380 if (millisecondsToDelay < 0) { 10381 millisecondsToDelay = 0; 10382 } 10383 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10384 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10385 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10386 } 10387 10388 if ((state != null) && !state.timeoutExtended()) { 10389 state.extendTimeout(); 10390 10391 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10392 msg.arg1 = id; 10393 msg.obj = response; 10394 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10395 } 10396 } 10397 10398 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10399 int verificationCode, UserHandle user) { 10400 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10401 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10402 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10403 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10404 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10405 10406 mContext.sendBroadcastAsUser(intent, user, 10407 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10408 } 10409 10410 private ComponentName matchComponentForVerifier(String packageName, 10411 List<ResolveInfo> receivers) { 10412 ActivityInfo targetReceiver = null; 10413 10414 final int NR = receivers.size(); 10415 for (int i = 0; i < NR; i++) { 10416 final ResolveInfo info = receivers.get(i); 10417 if (info.activityInfo == null) { 10418 continue; 10419 } 10420 10421 if (packageName.equals(info.activityInfo.packageName)) { 10422 targetReceiver = info.activityInfo; 10423 break; 10424 } 10425 } 10426 10427 if (targetReceiver == null) { 10428 return null; 10429 } 10430 10431 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10432 } 10433 10434 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10435 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10436 if (pkgInfo.verifiers.length == 0) { 10437 return null; 10438 } 10439 10440 final int N = pkgInfo.verifiers.length; 10441 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10442 for (int i = 0; i < N; i++) { 10443 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10444 10445 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10446 receivers); 10447 if (comp == null) { 10448 continue; 10449 } 10450 10451 final int verifierUid = getUidForVerifier(verifierInfo); 10452 if (verifierUid == -1) { 10453 continue; 10454 } 10455 10456 if (DEBUG_VERIFY) { 10457 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10458 + " with the correct signature"); 10459 } 10460 sufficientVerifiers.add(comp); 10461 verificationState.addSufficientVerifier(verifierUid); 10462 } 10463 10464 return sufficientVerifiers; 10465 } 10466 10467 private int getUidForVerifier(VerifierInfo verifierInfo) { 10468 synchronized (mPackages) { 10469 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10470 if (pkg == null) { 10471 return -1; 10472 } else if (pkg.mSignatures.length != 1) { 10473 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10474 + " has more than one signature; ignoring"); 10475 return -1; 10476 } 10477 10478 /* 10479 * If the public key of the package's signature does not match 10480 * our expected public key, then this is a different package and 10481 * we should skip. 10482 */ 10483 10484 final byte[] expectedPublicKey; 10485 try { 10486 final Signature verifierSig = pkg.mSignatures[0]; 10487 final PublicKey publicKey = verifierSig.getPublicKey(); 10488 expectedPublicKey = publicKey.getEncoded(); 10489 } catch (CertificateException e) { 10490 return -1; 10491 } 10492 10493 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10494 10495 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10496 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10497 + " does not have the expected public key; ignoring"); 10498 return -1; 10499 } 10500 10501 return pkg.applicationInfo.uid; 10502 } 10503 } 10504 10505 @Override 10506 public void finishPackageInstall(int token) { 10507 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10508 10509 if (DEBUG_INSTALL) { 10510 Slog.v(TAG, "BM finishing package install for " + token); 10511 } 10512 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10513 10514 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10515 mHandler.sendMessage(msg); 10516 } 10517 10518 /** 10519 * Get the verification agent timeout. 10520 * 10521 * @return verification timeout in milliseconds 10522 */ 10523 private long getVerificationTimeout() { 10524 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10525 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10526 DEFAULT_VERIFICATION_TIMEOUT); 10527 } 10528 10529 /** 10530 * Get the default verification agent response code. 10531 * 10532 * @return default verification response code 10533 */ 10534 private int getDefaultVerificationResponse() { 10535 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10536 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10537 DEFAULT_VERIFICATION_RESPONSE); 10538 } 10539 10540 /** 10541 * Check whether or not package verification has been enabled. 10542 * 10543 * @return true if verification should be performed 10544 */ 10545 private boolean isVerificationEnabled(int userId, int installFlags) { 10546 if (!DEFAULT_VERIFY_ENABLE) { 10547 return false; 10548 } 10549 // Ephemeral apps don't get the full verification treatment 10550 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10551 if (DEBUG_EPHEMERAL) { 10552 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10553 } 10554 return false; 10555 } 10556 10557 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10558 10559 // Check if installing from ADB 10560 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10561 // Do not run verification in a test harness environment 10562 if (ActivityManager.isRunningInTestHarness()) { 10563 return false; 10564 } 10565 if (ensureVerifyAppsEnabled) { 10566 return true; 10567 } 10568 // Check if the developer does not want package verification for ADB installs 10569 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10570 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10571 return false; 10572 } 10573 } 10574 10575 if (ensureVerifyAppsEnabled) { 10576 return true; 10577 } 10578 10579 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10580 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10581 } 10582 10583 @Override 10584 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10585 throws RemoteException { 10586 mContext.enforceCallingOrSelfPermission( 10587 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10588 "Only intentfilter verification agents can verify applications"); 10589 10590 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10591 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10592 Binder.getCallingUid(), verificationCode, failedDomains); 10593 msg.arg1 = id; 10594 msg.obj = response; 10595 mHandler.sendMessage(msg); 10596 } 10597 10598 @Override 10599 public int getIntentVerificationStatus(String packageName, int userId) { 10600 synchronized (mPackages) { 10601 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10602 } 10603 } 10604 10605 @Override 10606 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10607 mContext.enforceCallingOrSelfPermission( 10608 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10609 10610 boolean result = false; 10611 synchronized (mPackages) { 10612 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10613 } 10614 if (result) { 10615 scheduleWritePackageRestrictionsLocked(userId); 10616 } 10617 return result; 10618 } 10619 10620 @Override 10621 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10622 synchronized (mPackages) { 10623 return mSettings.getIntentFilterVerificationsLPr(packageName); 10624 } 10625 } 10626 10627 @Override 10628 public List<IntentFilter> getAllIntentFilters(String packageName) { 10629 if (TextUtils.isEmpty(packageName)) { 10630 return Collections.<IntentFilter>emptyList(); 10631 } 10632 synchronized (mPackages) { 10633 PackageParser.Package pkg = mPackages.get(packageName); 10634 if (pkg == null || pkg.activities == null) { 10635 return Collections.<IntentFilter>emptyList(); 10636 } 10637 final int count = pkg.activities.size(); 10638 ArrayList<IntentFilter> result = new ArrayList<>(); 10639 for (int n=0; n<count; n++) { 10640 PackageParser.Activity activity = pkg.activities.get(n); 10641 if (activity.intents != null && activity.intents.size() > 0) { 10642 result.addAll(activity.intents); 10643 } 10644 } 10645 return result; 10646 } 10647 } 10648 10649 @Override 10650 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10651 mContext.enforceCallingOrSelfPermission( 10652 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10653 10654 synchronized (mPackages) { 10655 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10656 if (packageName != null) { 10657 result |= updateIntentVerificationStatus(packageName, 10658 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10659 userId); 10660 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10661 packageName, userId); 10662 } 10663 return result; 10664 } 10665 } 10666 10667 @Override 10668 public String getDefaultBrowserPackageName(int userId) { 10669 synchronized (mPackages) { 10670 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10671 } 10672 } 10673 10674 /** 10675 * Get the "allow unknown sources" setting. 10676 * 10677 * @return the current "allow unknown sources" setting 10678 */ 10679 private int getUnknownSourcesSettings() { 10680 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10681 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10682 -1); 10683 } 10684 10685 @Override 10686 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10687 final int uid = Binder.getCallingUid(); 10688 // writer 10689 synchronized (mPackages) { 10690 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10691 if (targetPackageSetting == null) { 10692 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10693 } 10694 10695 PackageSetting installerPackageSetting; 10696 if (installerPackageName != null) { 10697 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10698 if (installerPackageSetting == null) { 10699 throw new IllegalArgumentException("Unknown installer package: " 10700 + installerPackageName); 10701 } 10702 } else { 10703 installerPackageSetting = null; 10704 } 10705 10706 Signature[] callerSignature; 10707 Object obj = mSettings.getUserIdLPr(uid); 10708 if (obj != null) { 10709 if (obj instanceof SharedUserSetting) { 10710 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10711 } else if (obj instanceof PackageSetting) { 10712 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10713 } else { 10714 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10715 } 10716 } else { 10717 throw new SecurityException("Unknown calling UID: " + uid); 10718 } 10719 10720 // Verify: can't set installerPackageName to a package that is 10721 // not signed with the same cert as the caller. 10722 if (installerPackageSetting != null) { 10723 if (compareSignatures(callerSignature, 10724 installerPackageSetting.signatures.mSignatures) 10725 != PackageManager.SIGNATURE_MATCH) { 10726 throw new SecurityException( 10727 "Caller does not have same cert as new installer package " 10728 + installerPackageName); 10729 } 10730 } 10731 10732 // Verify: if target already has an installer package, it must 10733 // be signed with the same cert as the caller. 10734 if (targetPackageSetting.installerPackageName != null) { 10735 PackageSetting setting = mSettings.mPackages.get( 10736 targetPackageSetting.installerPackageName); 10737 // If the currently set package isn't valid, then it's always 10738 // okay to change it. 10739 if (setting != null) { 10740 if (compareSignatures(callerSignature, 10741 setting.signatures.mSignatures) 10742 != PackageManager.SIGNATURE_MATCH) { 10743 throw new SecurityException( 10744 "Caller does not have same cert as old installer package " 10745 + targetPackageSetting.installerPackageName); 10746 } 10747 } 10748 } 10749 10750 // Okay! 10751 targetPackageSetting.installerPackageName = installerPackageName; 10752 scheduleWriteSettingsLocked(); 10753 } 10754 } 10755 10756 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10757 // Queue up an async operation since the package installation may take a little while. 10758 mHandler.post(new Runnable() { 10759 public void run() { 10760 mHandler.removeCallbacks(this); 10761 // Result object to be returned 10762 PackageInstalledInfo res = new PackageInstalledInfo(); 10763 res.returnCode = currentStatus; 10764 res.uid = -1; 10765 res.pkg = null; 10766 res.removedInfo = new PackageRemovedInfo(); 10767 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10768 args.doPreInstall(res.returnCode); 10769 synchronized (mInstallLock) { 10770 installPackageTracedLI(args, res); 10771 } 10772 args.doPostInstall(res.returnCode, res.uid); 10773 } 10774 10775 // A restore should be performed at this point if (a) the install 10776 // succeeded, (b) the operation is not an update, and (c) the new 10777 // package has not opted out of backup participation. 10778 final boolean update = res.removedInfo.removedPackage != null; 10779 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10780 boolean doRestore = !update 10781 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10782 10783 // Set up the post-install work request bookkeeping. This will be used 10784 // and cleaned up by the post-install event handling regardless of whether 10785 // there's a restore pass performed. Token values are >= 1. 10786 int token; 10787 if (mNextInstallToken < 0) mNextInstallToken = 1; 10788 token = mNextInstallToken++; 10789 10790 PostInstallData data = new PostInstallData(args, res); 10791 mRunningInstalls.put(token, data); 10792 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10793 10794 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10795 // Pass responsibility to the Backup Manager. It will perform a 10796 // restore if appropriate, then pass responsibility back to the 10797 // Package Manager to run the post-install observer callbacks 10798 // and broadcasts. 10799 IBackupManager bm = IBackupManager.Stub.asInterface( 10800 ServiceManager.getService(Context.BACKUP_SERVICE)); 10801 if (bm != null) { 10802 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10803 + " to BM for possible restore"); 10804 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10805 try { 10806 // TODO: http://b/22388012 10807 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10808 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10809 } else { 10810 doRestore = false; 10811 } 10812 } catch (RemoteException e) { 10813 // can't happen; the backup manager is local 10814 } catch (Exception e) { 10815 Slog.e(TAG, "Exception trying to enqueue restore", e); 10816 doRestore = false; 10817 } 10818 } else { 10819 Slog.e(TAG, "Backup Manager not found!"); 10820 doRestore = false; 10821 } 10822 } 10823 10824 if (!doRestore) { 10825 // No restore possible, or the Backup Manager was mysteriously not 10826 // available -- just fire the post-install work request directly. 10827 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10828 10829 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10830 10831 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10832 mHandler.sendMessage(msg); 10833 } 10834 } 10835 }); 10836 } 10837 10838 private abstract class HandlerParams { 10839 private static final int MAX_RETRIES = 4; 10840 10841 /** 10842 * Number of times startCopy() has been attempted and had a non-fatal 10843 * error. 10844 */ 10845 private int mRetries = 0; 10846 10847 /** User handle for the user requesting the information or installation. */ 10848 private final UserHandle mUser; 10849 String traceMethod; 10850 int traceCookie; 10851 10852 HandlerParams(UserHandle user) { 10853 mUser = user; 10854 } 10855 10856 UserHandle getUser() { 10857 return mUser; 10858 } 10859 10860 HandlerParams setTraceMethod(String traceMethod) { 10861 this.traceMethod = traceMethod; 10862 return this; 10863 } 10864 10865 HandlerParams setTraceCookie(int traceCookie) { 10866 this.traceCookie = traceCookie; 10867 return this; 10868 } 10869 10870 final boolean startCopy() { 10871 boolean res; 10872 try { 10873 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10874 10875 if (++mRetries > MAX_RETRIES) { 10876 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10877 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10878 handleServiceError(); 10879 return false; 10880 } else { 10881 handleStartCopy(); 10882 res = true; 10883 } 10884 } catch (RemoteException e) { 10885 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10886 mHandler.sendEmptyMessage(MCS_RECONNECT); 10887 res = false; 10888 } 10889 handleReturnCode(); 10890 return res; 10891 } 10892 10893 final void serviceError() { 10894 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10895 handleServiceError(); 10896 handleReturnCode(); 10897 } 10898 10899 abstract void handleStartCopy() throws RemoteException; 10900 abstract void handleServiceError(); 10901 abstract void handleReturnCode(); 10902 } 10903 10904 class MeasureParams extends HandlerParams { 10905 private final PackageStats mStats; 10906 private boolean mSuccess; 10907 10908 private final IPackageStatsObserver mObserver; 10909 10910 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10911 super(new UserHandle(stats.userHandle)); 10912 mObserver = observer; 10913 mStats = stats; 10914 } 10915 10916 @Override 10917 public String toString() { 10918 return "MeasureParams{" 10919 + Integer.toHexString(System.identityHashCode(this)) 10920 + " " + mStats.packageName + "}"; 10921 } 10922 10923 @Override 10924 void handleStartCopy() throws RemoteException { 10925 synchronized (mInstallLock) { 10926 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10927 } 10928 10929 if (mSuccess) { 10930 final boolean mounted; 10931 if (Environment.isExternalStorageEmulated()) { 10932 mounted = true; 10933 } else { 10934 final String status = Environment.getExternalStorageState(); 10935 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10936 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10937 } 10938 10939 if (mounted) { 10940 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10941 10942 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10943 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10944 10945 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10946 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10947 10948 // Always subtract cache size, since it's a subdirectory 10949 mStats.externalDataSize -= mStats.externalCacheSize; 10950 10951 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10952 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10953 10954 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10955 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10956 } 10957 } 10958 } 10959 10960 @Override 10961 void handleReturnCode() { 10962 if (mObserver != null) { 10963 try { 10964 mObserver.onGetStatsCompleted(mStats, mSuccess); 10965 } catch (RemoteException e) { 10966 Slog.i(TAG, "Observer no longer exists."); 10967 } 10968 } 10969 } 10970 10971 @Override 10972 void handleServiceError() { 10973 Slog.e(TAG, "Could not measure application " + mStats.packageName 10974 + " external storage"); 10975 } 10976 } 10977 10978 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10979 throws RemoteException { 10980 long result = 0; 10981 for (File path : paths) { 10982 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10983 } 10984 return result; 10985 } 10986 10987 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10988 for (File path : paths) { 10989 try { 10990 mcs.clearDirectory(path.getAbsolutePath()); 10991 } catch (RemoteException e) { 10992 } 10993 } 10994 } 10995 10996 static class OriginInfo { 10997 /** 10998 * Location where install is coming from, before it has been 10999 * copied/renamed into place. This could be a single monolithic APK 11000 * file, or a cluster directory. This location may be untrusted. 11001 */ 11002 final File file; 11003 final String cid; 11004 11005 /** 11006 * Flag indicating that {@link #file} or {@link #cid} has already been 11007 * staged, meaning downstream users don't need to defensively copy the 11008 * contents. 11009 */ 11010 final boolean staged; 11011 11012 /** 11013 * Flag indicating that {@link #file} or {@link #cid} is an already 11014 * installed app that is being moved. 11015 */ 11016 final boolean existing; 11017 11018 final String resolvedPath; 11019 final File resolvedFile; 11020 11021 static OriginInfo fromNothing() { 11022 return new OriginInfo(null, null, false, false); 11023 } 11024 11025 static OriginInfo fromUntrustedFile(File file) { 11026 return new OriginInfo(file, null, false, false); 11027 } 11028 11029 static OriginInfo fromExistingFile(File file) { 11030 return new OriginInfo(file, null, false, true); 11031 } 11032 11033 static OriginInfo fromStagedFile(File file) { 11034 return new OriginInfo(file, null, true, false); 11035 } 11036 11037 static OriginInfo fromStagedContainer(String cid) { 11038 return new OriginInfo(null, cid, true, false); 11039 } 11040 11041 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 11042 this.file = file; 11043 this.cid = cid; 11044 this.staged = staged; 11045 this.existing = existing; 11046 11047 if (cid != null) { 11048 resolvedPath = PackageHelper.getSdDir(cid); 11049 resolvedFile = new File(resolvedPath); 11050 } else if (file != null) { 11051 resolvedPath = file.getAbsolutePath(); 11052 resolvedFile = file; 11053 } else { 11054 resolvedPath = null; 11055 resolvedFile = null; 11056 } 11057 } 11058 } 11059 11060 static class MoveInfo { 11061 final int moveId; 11062 final String fromUuid; 11063 final String toUuid; 11064 final String packageName; 11065 final String dataAppName; 11066 final int appId; 11067 final String seinfo; 11068 final int targetSdkVersion; 11069 11070 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 11071 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 11072 this.moveId = moveId; 11073 this.fromUuid = fromUuid; 11074 this.toUuid = toUuid; 11075 this.packageName = packageName; 11076 this.dataAppName = dataAppName; 11077 this.appId = appId; 11078 this.seinfo = seinfo; 11079 this.targetSdkVersion = targetSdkVersion; 11080 } 11081 } 11082 11083 class InstallParams extends HandlerParams { 11084 final OriginInfo origin; 11085 final MoveInfo move; 11086 final IPackageInstallObserver2 observer; 11087 int installFlags; 11088 final String installerPackageName; 11089 final String volumeUuid; 11090 final VerificationParams verificationParams; 11091 private InstallArgs mArgs; 11092 private int mRet; 11093 final String packageAbiOverride; 11094 final String[] grantedRuntimePermissions; 11095 11096 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11097 int installFlags, String installerPackageName, String volumeUuid, 11098 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 11099 String[] grantedPermissions) { 11100 super(user); 11101 this.origin = origin; 11102 this.move = move; 11103 this.observer = observer; 11104 this.installFlags = installFlags; 11105 this.installerPackageName = installerPackageName; 11106 this.volumeUuid = volumeUuid; 11107 this.verificationParams = verificationParams; 11108 this.packageAbiOverride = packageAbiOverride; 11109 this.grantedRuntimePermissions = grantedPermissions; 11110 } 11111 11112 @Override 11113 public String toString() { 11114 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11115 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11116 } 11117 11118 private int installLocationPolicy(PackageInfoLite pkgLite) { 11119 String packageName = pkgLite.packageName; 11120 int installLocation = pkgLite.installLocation; 11121 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11122 // reader 11123 synchronized (mPackages) { 11124 PackageParser.Package pkg = mPackages.get(packageName); 11125 if (pkg != null) { 11126 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11127 // Check for downgrading. 11128 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 11129 try { 11130 checkDowngrade(pkg, pkgLite); 11131 } catch (PackageManagerException e) { 11132 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11133 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11134 } 11135 } 11136 // Check for updated system application. 11137 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11138 if (onSd) { 11139 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11140 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11141 } 11142 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11143 } else { 11144 if (onSd) { 11145 // Install flag overrides everything. 11146 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11147 } 11148 // If current upgrade specifies particular preference 11149 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11150 // Application explicitly specified internal. 11151 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11152 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11153 // App explictly prefers external. Let policy decide 11154 } else { 11155 // Prefer previous location 11156 if (isExternal(pkg)) { 11157 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11158 } 11159 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11160 } 11161 } 11162 } else { 11163 // Invalid install. Return error code 11164 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11165 } 11166 } 11167 } 11168 // All the special cases have been taken care of. 11169 // Return result based on recommended install location. 11170 if (onSd) { 11171 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11172 } 11173 return pkgLite.recommendedInstallLocation; 11174 } 11175 11176 /* 11177 * Invoke remote method to get package information and install 11178 * location values. Override install location based on default 11179 * policy if needed and then create install arguments based 11180 * on the install location. 11181 */ 11182 public void handleStartCopy() throws RemoteException { 11183 int ret = PackageManager.INSTALL_SUCCEEDED; 11184 11185 // If we're already staged, we've firmly committed to an install location 11186 if (origin.staged) { 11187 if (origin.file != null) { 11188 installFlags |= PackageManager.INSTALL_INTERNAL; 11189 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11190 } else if (origin.cid != null) { 11191 installFlags |= PackageManager.INSTALL_EXTERNAL; 11192 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11193 } else { 11194 throw new IllegalStateException("Invalid stage location"); 11195 } 11196 } 11197 11198 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11199 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11200 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11201 PackageInfoLite pkgLite = null; 11202 11203 if (onInt && onSd) { 11204 // Check if both bits are set. 11205 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11206 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11207 } else if (onSd && ephemeral) { 11208 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11209 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11210 } else { 11211 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11212 packageAbiOverride); 11213 11214 if (DEBUG_EPHEMERAL && ephemeral) { 11215 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11216 } 11217 11218 /* 11219 * If we have too little free space, try to free cache 11220 * before giving up. 11221 */ 11222 if (!origin.staged && pkgLite.recommendedInstallLocation 11223 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11224 // TODO: focus freeing disk space on the target device 11225 final StorageManager storage = StorageManager.from(mContext); 11226 final long lowThreshold = storage.getStorageLowBytes( 11227 Environment.getDataDirectory()); 11228 11229 final long sizeBytes = mContainerService.calculateInstalledSize( 11230 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11231 11232 try { 11233 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11234 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11235 installFlags, packageAbiOverride); 11236 } catch (InstallerException e) { 11237 Slog.w(TAG, "Failed to free cache", e); 11238 } 11239 11240 /* 11241 * The cache free must have deleted the file we 11242 * downloaded to install. 11243 * 11244 * TODO: fix the "freeCache" call to not delete 11245 * the file we care about. 11246 */ 11247 if (pkgLite.recommendedInstallLocation 11248 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11249 pkgLite.recommendedInstallLocation 11250 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11251 } 11252 } 11253 } 11254 11255 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11256 int loc = pkgLite.recommendedInstallLocation; 11257 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11258 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11259 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11260 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11261 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11262 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11263 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11264 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11265 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11266 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11267 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11268 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11269 } else { 11270 // Override with defaults if needed. 11271 loc = installLocationPolicy(pkgLite); 11272 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11273 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11274 } else if (!onSd && !onInt) { 11275 // Override install location with flags 11276 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11277 // Set the flag to install on external media. 11278 installFlags |= PackageManager.INSTALL_EXTERNAL; 11279 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11280 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11281 if (DEBUG_EPHEMERAL) { 11282 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11283 } 11284 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11285 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11286 |PackageManager.INSTALL_INTERNAL); 11287 } else { 11288 // Make sure the flag for installing on external 11289 // media is unset 11290 installFlags |= PackageManager.INSTALL_INTERNAL; 11291 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11292 } 11293 } 11294 } 11295 } 11296 11297 final InstallArgs args = createInstallArgs(this); 11298 mArgs = args; 11299 11300 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11301 // TODO: http://b/22976637 11302 // Apps installed for "all" users use the device owner to verify the app 11303 UserHandle verifierUser = getUser(); 11304 if (verifierUser == UserHandle.ALL) { 11305 verifierUser = UserHandle.SYSTEM; 11306 } 11307 11308 /* 11309 * Determine if we have any installed package verifiers. If we 11310 * do, then we'll defer to them to verify the packages. 11311 */ 11312 final int requiredUid = mRequiredVerifierPackage == null ? -1 11313 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11314 verifierUser.getIdentifier()); 11315 if (!origin.existing && requiredUid != -1 11316 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11317 final Intent verification = new Intent( 11318 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11319 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11320 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11321 PACKAGE_MIME_TYPE); 11322 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11323 11324 // Query all live verifiers based on current user state 11325 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11326 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11327 11328 if (DEBUG_VERIFY) { 11329 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11330 + verification.toString() + " with " + pkgLite.verifiers.length 11331 + " optional verifiers"); 11332 } 11333 11334 final int verificationId = mPendingVerificationToken++; 11335 11336 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11337 11338 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11339 installerPackageName); 11340 11341 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11342 installFlags); 11343 11344 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11345 pkgLite.packageName); 11346 11347 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11348 pkgLite.versionCode); 11349 11350 if (verificationParams != null) { 11351 if (verificationParams.getVerificationURI() != null) { 11352 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11353 verificationParams.getVerificationURI()); 11354 } 11355 if (verificationParams.getOriginatingURI() != null) { 11356 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11357 verificationParams.getOriginatingURI()); 11358 } 11359 if (verificationParams.getReferrer() != null) { 11360 verification.putExtra(Intent.EXTRA_REFERRER, 11361 verificationParams.getReferrer()); 11362 } 11363 if (verificationParams.getOriginatingUid() >= 0) { 11364 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11365 verificationParams.getOriginatingUid()); 11366 } 11367 if (verificationParams.getInstallerUid() >= 0) { 11368 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11369 verificationParams.getInstallerUid()); 11370 } 11371 } 11372 11373 final PackageVerificationState verificationState = new PackageVerificationState( 11374 requiredUid, args); 11375 11376 mPendingVerification.append(verificationId, verificationState); 11377 11378 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11379 receivers, verificationState); 11380 11381 /* 11382 * If any sufficient verifiers were listed in the package 11383 * manifest, attempt to ask them. 11384 */ 11385 if (sufficientVerifiers != null) { 11386 final int N = sufficientVerifiers.size(); 11387 if (N == 0) { 11388 Slog.i(TAG, "Additional verifiers required, but none installed."); 11389 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11390 } else { 11391 for (int i = 0; i < N; i++) { 11392 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11393 11394 final Intent sufficientIntent = new Intent(verification); 11395 sufficientIntent.setComponent(verifierComponent); 11396 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11397 } 11398 } 11399 } 11400 11401 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11402 mRequiredVerifierPackage, receivers); 11403 if (ret == PackageManager.INSTALL_SUCCEEDED 11404 && mRequiredVerifierPackage != null) { 11405 Trace.asyncTraceBegin( 11406 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11407 /* 11408 * Send the intent to the required verification agent, 11409 * but only start the verification timeout after the 11410 * target BroadcastReceivers have run. 11411 */ 11412 verification.setComponent(requiredVerifierComponent); 11413 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11414 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11415 new BroadcastReceiver() { 11416 @Override 11417 public void onReceive(Context context, Intent intent) { 11418 final Message msg = mHandler 11419 .obtainMessage(CHECK_PENDING_VERIFICATION); 11420 msg.arg1 = verificationId; 11421 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11422 } 11423 }, null, 0, null, null); 11424 11425 /* 11426 * We don't want the copy to proceed until verification 11427 * succeeds, so null out this field. 11428 */ 11429 mArgs = null; 11430 } 11431 } else { 11432 /* 11433 * No package verification is enabled, so immediately start 11434 * the remote call to initiate copy using temporary file. 11435 */ 11436 ret = args.copyApk(mContainerService, true); 11437 } 11438 } 11439 11440 mRet = ret; 11441 } 11442 11443 @Override 11444 void handleReturnCode() { 11445 // If mArgs is null, then MCS couldn't be reached. When it 11446 // reconnects, it will try again to install. At that point, this 11447 // will succeed. 11448 if (mArgs != null) { 11449 processPendingInstall(mArgs, mRet); 11450 } 11451 } 11452 11453 @Override 11454 void handleServiceError() { 11455 mArgs = createInstallArgs(this); 11456 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11457 } 11458 11459 public boolean isForwardLocked() { 11460 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11461 } 11462 } 11463 11464 /** 11465 * Used during creation of InstallArgs 11466 * 11467 * @param installFlags package installation flags 11468 * @return true if should be installed on external storage 11469 */ 11470 private static boolean installOnExternalAsec(int installFlags) { 11471 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11472 return false; 11473 } 11474 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11475 return true; 11476 } 11477 return false; 11478 } 11479 11480 /** 11481 * Used during creation of InstallArgs 11482 * 11483 * @param installFlags package installation flags 11484 * @return true if should be installed as forward locked 11485 */ 11486 private static boolean installForwardLocked(int installFlags) { 11487 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11488 } 11489 11490 private InstallArgs createInstallArgs(InstallParams params) { 11491 if (params.move != null) { 11492 return new MoveInstallArgs(params); 11493 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11494 return new AsecInstallArgs(params); 11495 } else { 11496 return new FileInstallArgs(params); 11497 } 11498 } 11499 11500 /** 11501 * Create args that describe an existing installed package. Typically used 11502 * when cleaning up old installs, or used as a move source. 11503 */ 11504 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11505 String resourcePath, String[] instructionSets) { 11506 final boolean isInAsec; 11507 if (installOnExternalAsec(installFlags)) { 11508 /* Apps on SD card are always in ASEC containers. */ 11509 isInAsec = true; 11510 } else if (installForwardLocked(installFlags) 11511 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11512 /* 11513 * Forward-locked apps are only in ASEC containers if they're the 11514 * new style 11515 */ 11516 isInAsec = true; 11517 } else { 11518 isInAsec = false; 11519 } 11520 11521 if (isInAsec) { 11522 return new AsecInstallArgs(codePath, instructionSets, 11523 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11524 } else { 11525 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11526 } 11527 } 11528 11529 static abstract class InstallArgs { 11530 /** @see InstallParams#origin */ 11531 final OriginInfo origin; 11532 /** @see InstallParams#move */ 11533 final MoveInfo move; 11534 11535 final IPackageInstallObserver2 observer; 11536 // Always refers to PackageManager flags only 11537 final int installFlags; 11538 final String installerPackageName; 11539 final String volumeUuid; 11540 final UserHandle user; 11541 final String abiOverride; 11542 final String[] installGrantPermissions; 11543 /** If non-null, drop an async trace when the install completes */ 11544 final String traceMethod; 11545 final int traceCookie; 11546 11547 // The list of instruction sets supported by this app. This is currently 11548 // only used during the rmdex() phase to clean up resources. We can get rid of this 11549 // if we move dex files under the common app path. 11550 /* nullable */ String[] instructionSets; 11551 11552 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11553 int installFlags, String installerPackageName, String volumeUuid, 11554 UserHandle user, String[] instructionSets, 11555 String abiOverride, String[] installGrantPermissions, 11556 String traceMethod, int traceCookie) { 11557 this.origin = origin; 11558 this.move = move; 11559 this.installFlags = installFlags; 11560 this.observer = observer; 11561 this.installerPackageName = installerPackageName; 11562 this.volumeUuid = volumeUuid; 11563 this.user = user; 11564 this.instructionSets = instructionSets; 11565 this.abiOverride = abiOverride; 11566 this.installGrantPermissions = installGrantPermissions; 11567 this.traceMethod = traceMethod; 11568 this.traceCookie = traceCookie; 11569 } 11570 11571 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11572 abstract int doPreInstall(int status); 11573 11574 /** 11575 * Rename package into final resting place. All paths on the given 11576 * scanned package should be updated to reflect the rename. 11577 */ 11578 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11579 abstract int doPostInstall(int status, int uid); 11580 11581 /** @see PackageSettingBase#codePathString */ 11582 abstract String getCodePath(); 11583 /** @see PackageSettingBase#resourcePathString */ 11584 abstract String getResourcePath(); 11585 11586 // Need installer lock especially for dex file removal. 11587 abstract void cleanUpResourcesLI(); 11588 abstract boolean doPostDeleteLI(boolean delete); 11589 11590 /** 11591 * Called before the source arguments are copied. This is used mostly 11592 * for MoveParams when it needs to read the source file to put it in the 11593 * destination. 11594 */ 11595 int doPreCopy() { 11596 return PackageManager.INSTALL_SUCCEEDED; 11597 } 11598 11599 /** 11600 * Called after the source arguments are copied. This is used mostly for 11601 * MoveParams when it needs to read the source file to put it in the 11602 * destination. 11603 * 11604 * @return 11605 */ 11606 int doPostCopy(int uid) { 11607 return PackageManager.INSTALL_SUCCEEDED; 11608 } 11609 11610 protected boolean isFwdLocked() { 11611 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11612 } 11613 11614 protected boolean isExternalAsec() { 11615 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11616 } 11617 11618 protected boolean isEphemeral() { 11619 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11620 } 11621 11622 UserHandle getUser() { 11623 return user; 11624 } 11625 } 11626 11627 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11628 if (!allCodePaths.isEmpty()) { 11629 if (instructionSets == null) { 11630 throw new IllegalStateException("instructionSet == null"); 11631 } 11632 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11633 for (String codePath : allCodePaths) { 11634 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11635 try { 11636 mInstaller.rmdex(codePath, dexCodeInstructionSet); 11637 } catch (InstallerException ignored) { 11638 } 11639 } 11640 } 11641 } 11642 } 11643 11644 /** 11645 * Logic to handle installation of non-ASEC applications, including copying 11646 * and renaming logic. 11647 */ 11648 class FileInstallArgs extends InstallArgs { 11649 private File codeFile; 11650 private File resourceFile; 11651 11652 // Example topology: 11653 // /data/app/com.example/base.apk 11654 // /data/app/com.example/split_foo.apk 11655 // /data/app/com.example/lib/arm/libfoo.so 11656 // /data/app/com.example/lib/arm64/libfoo.so 11657 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11658 11659 /** New install */ 11660 FileInstallArgs(InstallParams params) { 11661 super(params.origin, params.move, params.observer, params.installFlags, 11662 params.installerPackageName, params.volumeUuid, 11663 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11664 params.grantedRuntimePermissions, 11665 params.traceMethod, params.traceCookie); 11666 if (isFwdLocked()) { 11667 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11668 } 11669 } 11670 11671 /** Existing install */ 11672 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11673 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 11674 null, null, null, 0); 11675 this.codeFile = (codePath != null) ? new File(codePath) : null; 11676 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11677 } 11678 11679 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11680 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11681 try { 11682 return doCopyApk(imcs, temp); 11683 } finally { 11684 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11685 } 11686 } 11687 11688 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11689 if (origin.staged) { 11690 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11691 codeFile = origin.file; 11692 resourceFile = origin.file; 11693 return PackageManager.INSTALL_SUCCEEDED; 11694 } 11695 11696 try { 11697 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11698 final File tempDir = 11699 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 11700 codeFile = tempDir; 11701 resourceFile = tempDir; 11702 } catch (IOException e) { 11703 Slog.w(TAG, "Failed to create copy file: " + e); 11704 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11705 } 11706 11707 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11708 @Override 11709 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11710 if (!FileUtils.isValidExtFilename(name)) { 11711 throw new IllegalArgumentException("Invalid filename: " + name); 11712 } 11713 try { 11714 final File file = new File(codeFile, name); 11715 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11716 O_RDWR | O_CREAT, 0644); 11717 Os.chmod(file.getAbsolutePath(), 0644); 11718 return new ParcelFileDescriptor(fd); 11719 } catch (ErrnoException e) { 11720 throw new RemoteException("Failed to open: " + e.getMessage()); 11721 } 11722 } 11723 }; 11724 11725 int ret = PackageManager.INSTALL_SUCCEEDED; 11726 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11727 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11728 Slog.e(TAG, "Failed to copy package"); 11729 return ret; 11730 } 11731 11732 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11733 NativeLibraryHelper.Handle handle = null; 11734 try { 11735 handle = NativeLibraryHelper.Handle.create(codeFile); 11736 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11737 abiOverride); 11738 } catch (IOException e) { 11739 Slog.e(TAG, "Copying native libraries failed", e); 11740 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11741 } finally { 11742 IoUtils.closeQuietly(handle); 11743 } 11744 11745 return ret; 11746 } 11747 11748 int doPreInstall(int status) { 11749 if (status != PackageManager.INSTALL_SUCCEEDED) { 11750 cleanUp(); 11751 } 11752 return status; 11753 } 11754 11755 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11756 if (status != PackageManager.INSTALL_SUCCEEDED) { 11757 cleanUp(); 11758 return false; 11759 } 11760 11761 final File targetDir = codeFile.getParentFile(); 11762 final File beforeCodeFile = codeFile; 11763 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11764 11765 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11766 try { 11767 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11768 } catch (ErrnoException e) { 11769 Slog.w(TAG, "Failed to rename", e); 11770 return false; 11771 } 11772 11773 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11774 Slog.w(TAG, "Failed to restorecon"); 11775 return false; 11776 } 11777 11778 // Reflect the rename internally 11779 codeFile = afterCodeFile; 11780 resourceFile = afterCodeFile; 11781 11782 // Reflect the rename in scanned details 11783 pkg.codePath = afterCodeFile.getAbsolutePath(); 11784 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11785 pkg.baseCodePath); 11786 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11787 pkg.splitCodePaths); 11788 11789 // Reflect the rename in app info 11790 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11791 pkg.applicationInfo.setCodePath(pkg.codePath); 11792 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11793 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11794 pkg.applicationInfo.setResourcePath(pkg.codePath); 11795 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11796 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11797 11798 return true; 11799 } 11800 11801 int doPostInstall(int status, int uid) { 11802 if (status != PackageManager.INSTALL_SUCCEEDED) { 11803 cleanUp(); 11804 } 11805 return status; 11806 } 11807 11808 @Override 11809 String getCodePath() { 11810 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11811 } 11812 11813 @Override 11814 String getResourcePath() { 11815 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11816 } 11817 11818 private boolean cleanUp() { 11819 if (codeFile == null || !codeFile.exists()) { 11820 return false; 11821 } 11822 11823 removeCodePathLI(codeFile); 11824 11825 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11826 resourceFile.delete(); 11827 } 11828 11829 return true; 11830 } 11831 11832 void cleanUpResourcesLI() { 11833 // Try enumerating all code paths before deleting 11834 List<String> allCodePaths = Collections.EMPTY_LIST; 11835 if (codeFile != null && codeFile.exists()) { 11836 try { 11837 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11838 allCodePaths = pkg.getAllCodePaths(); 11839 } catch (PackageParserException e) { 11840 // Ignored; we tried our best 11841 } 11842 } 11843 11844 cleanUp(); 11845 removeDexFiles(allCodePaths, instructionSets); 11846 } 11847 11848 boolean doPostDeleteLI(boolean delete) { 11849 // XXX err, shouldn't we respect the delete flag? 11850 cleanUpResourcesLI(); 11851 return true; 11852 } 11853 } 11854 11855 private boolean isAsecExternal(String cid) { 11856 final String asecPath = PackageHelper.getSdFilesystem(cid); 11857 return !asecPath.startsWith(mAsecInternalPath); 11858 } 11859 11860 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11861 PackageManagerException { 11862 if (copyRet < 0) { 11863 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11864 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11865 throw new PackageManagerException(copyRet, message); 11866 } 11867 } 11868 } 11869 11870 /** 11871 * Extract the MountService "container ID" from the full code path of an 11872 * .apk. 11873 */ 11874 static String cidFromCodePath(String fullCodePath) { 11875 int eidx = fullCodePath.lastIndexOf("/"); 11876 String subStr1 = fullCodePath.substring(0, eidx); 11877 int sidx = subStr1.lastIndexOf("/"); 11878 return subStr1.substring(sidx+1, eidx); 11879 } 11880 11881 /** 11882 * Logic to handle installation of ASEC applications, including copying and 11883 * renaming logic. 11884 */ 11885 class AsecInstallArgs extends InstallArgs { 11886 static final String RES_FILE_NAME = "pkg.apk"; 11887 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11888 11889 String cid; 11890 String packagePath; 11891 String resourcePath; 11892 11893 /** New install */ 11894 AsecInstallArgs(InstallParams params) { 11895 super(params.origin, params.move, params.observer, params.installFlags, 11896 params.installerPackageName, params.volumeUuid, 11897 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11898 params.grantedRuntimePermissions, 11899 params.traceMethod, params.traceCookie); 11900 } 11901 11902 /** Existing install */ 11903 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11904 boolean isExternal, boolean isForwardLocked) { 11905 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11906 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11907 instructionSets, null, null, null, 0); 11908 // Hackily pretend we're still looking at a full code path 11909 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11910 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11911 } 11912 11913 // Extract cid from fullCodePath 11914 int eidx = fullCodePath.lastIndexOf("/"); 11915 String subStr1 = fullCodePath.substring(0, eidx); 11916 int sidx = subStr1.lastIndexOf("/"); 11917 cid = subStr1.substring(sidx+1, eidx); 11918 setMountPath(subStr1); 11919 } 11920 11921 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11922 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11923 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11924 instructionSets, null, null, null, 0); 11925 this.cid = cid; 11926 setMountPath(PackageHelper.getSdDir(cid)); 11927 } 11928 11929 void createCopyFile() { 11930 cid = mInstallerService.allocateExternalStageCidLegacy(); 11931 } 11932 11933 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11934 if (origin.staged && origin.cid != null) { 11935 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11936 cid = origin.cid; 11937 setMountPath(PackageHelper.getSdDir(cid)); 11938 return PackageManager.INSTALL_SUCCEEDED; 11939 } 11940 11941 if (temp) { 11942 createCopyFile(); 11943 } else { 11944 /* 11945 * Pre-emptively destroy the container since it's destroyed if 11946 * copying fails due to it existing anyway. 11947 */ 11948 PackageHelper.destroySdDir(cid); 11949 } 11950 11951 final String newMountPath = imcs.copyPackageToContainer( 11952 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11953 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11954 11955 if (newMountPath != null) { 11956 setMountPath(newMountPath); 11957 return PackageManager.INSTALL_SUCCEEDED; 11958 } else { 11959 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11960 } 11961 } 11962 11963 @Override 11964 String getCodePath() { 11965 return packagePath; 11966 } 11967 11968 @Override 11969 String getResourcePath() { 11970 return resourcePath; 11971 } 11972 11973 int doPreInstall(int status) { 11974 if (status != PackageManager.INSTALL_SUCCEEDED) { 11975 // Destroy container 11976 PackageHelper.destroySdDir(cid); 11977 } else { 11978 boolean mounted = PackageHelper.isContainerMounted(cid); 11979 if (!mounted) { 11980 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11981 Process.SYSTEM_UID); 11982 if (newMountPath != null) { 11983 setMountPath(newMountPath); 11984 } else { 11985 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11986 } 11987 } 11988 } 11989 return status; 11990 } 11991 11992 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11993 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11994 String newMountPath = null; 11995 if (PackageHelper.isContainerMounted(cid)) { 11996 // Unmount the container 11997 if (!PackageHelper.unMountSdDir(cid)) { 11998 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11999 return false; 12000 } 12001 } 12002 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12003 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 12004 " which might be stale. Will try to clean up."); 12005 // Clean up the stale container and proceed to recreate. 12006 if (!PackageHelper.destroySdDir(newCacheId)) { 12007 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 12008 return false; 12009 } 12010 // Successfully cleaned up stale container. Try to rename again. 12011 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12012 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 12013 + " inspite of cleaning it up."); 12014 return false; 12015 } 12016 } 12017 if (!PackageHelper.isContainerMounted(newCacheId)) { 12018 Slog.w(TAG, "Mounting container " + newCacheId); 12019 newMountPath = PackageHelper.mountSdDir(newCacheId, 12020 getEncryptKey(), Process.SYSTEM_UID); 12021 } else { 12022 newMountPath = PackageHelper.getSdDir(newCacheId); 12023 } 12024 if (newMountPath == null) { 12025 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 12026 return false; 12027 } 12028 Log.i(TAG, "Succesfully renamed " + cid + 12029 " to " + newCacheId + 12030 " at new path: " + newMountPath); 12031 cid = newCacheId; 12032 12033 final File beforeCodeFile = new File(packagePath); 12034 setMountPath(newMountPath); 12035 final File afterCodeFile = new File(packagePath); 12036 12037 // Reflect the rename in scanned details 12038 pkg.codePath = afterCodeFile.getAbsolutePath(); 12039 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 12040 pkg.baseCodePath); 12041 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 12042 pkg.splitCodePaths); 12043 12044 // Reflect the rename in app info 12045 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 12046 pkg.applicationInfo.setCodePath(pkg.codePath); 12047 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 12048 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 12049 pkg.applicationInfo.setResourcePath(pkg.codePath); 12050 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 12051 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 12052 12053 return true; 12054 } 12055 12056 private void setMountPath(String mountPath) { 12057 final File mountFile = new File(mountPath); 12058 12059 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 12060 if (monolithicFile.exists()) { 12061 packagePath = monolithicFile.getAbsolutePath(); 12062 if (isFwdLocked()) { 12063 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 12064 } else { 12065 resourcePath = packagePath; 12066 } 12067 } else { 12068 packagePath = mountFile.getAbsolutePath(); 12069 resourcePath = packagePath; 12070 } 12071 } 12072 12073 int doPostInstall(int status, int uid) { 12074 if (status != PackageManager.INSTALL_SUCCEEDED) { 12075 cleanUp(); 12076 } else { 12077 final int groupOwner; 12078 final String protectedFile; 12079 if (isFwdLocked()) { 12080 groupOwner = UserHandle.getSharedAppGid(uid); 12081 protectedFile = RES_FILE_NAME; 12082 } else { 12083 groupOwner = -1; 12084 protectedFile = null; 12085 } 12086 12087 if (uid < Process.FIRST_APPLICATION_UID 12088 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 12089 Slog.e(TAG, "Failed to finalize " + cid); 12090 PackageHelper.destroySdDir(cid); 12091 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12092 } 12093 12094 boolean mounted = PackageHelper.isContainerMounted(cid); 12095 if (!mounted) { 12096 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12097 } 12098 } 12099 return status; 12100 } 12101 12102 private void cleanUp() { 12103 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12104 12105 // Destroy secure container 12106 PackageHelper.destroySdDir(cid); 12107 } 12108 12109 private List<String> getAllCodePaths() { 12110 final File codeFile = new File(getCodePath()); 12111 if (codeFile != null && codeFile.exists()) { 12112 try { 12113 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12114 return pkg.getAllCodePaths(); 12115 } catch (PackageParserException e) { 12116 // Ignored; we tried our best 12117 } 12118 } 12119 return Collections.EMPTY_LIST; 12120 } 12121 12122 void cleanUpResourcesLI() { 12123 // Enumerate all code paths before deleting 12124 cleanUpResourcesLI(getAllCodePaths()); 12125 } 12126 12127 private void cleanUpResourcesLI(List<String> allCodePaths) { 12128 cleanUp(); 12129 removeDexFiles(allCodePaths, instructionSets); 12130 } 12131 12132 String getPackageName() { 12133 return getAsecPackageName(cid); 12134 } 12135 12136 boolean doPostDeleteLI(boolean delete) { 12137 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12138 final List<String> allCodePaths = getAllCodePaths(); 12139 boolean mounted = PackageHelper.isContainerMounted(cid); 12140 if (mounted) { 12141 // Unmount first 12142 if (PackageHelper.unMountSdDir(cid)) { 12143 mounted = false; 12144 } 12145 } 12146 if (!mounted && delete) { 12147 cleanUpResourcesLI(allCodePaths); 12148 } 12149 return !mounted; 12150 } 12151 12152 @Override 12153 int doPreCopy() { 12154 if (isFwdLocked()) { 12155 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12156 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12157 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12158 } 12159 } 12160 12161 return PackageManager.INSTALL_SUCCEEDED; 12162 } 12163 12164 @Override 12165 int doPostCopy(int uid) { 12166 if (isFwdLocked()) { 12167 if (uid < Process.FIRST_APPLICATION_UID 12168 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12169 RES_FILE_NAME)) { 12170 Slog.e(TAG, "Failed to finalize " + cid); 12171 PackageHelper.destroySdDir(cid); 12172 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12173 } 12174 } 12175 12176 return PackageManager.INSTALL_SUCCEEDED; 12177 } 12178 } 12179 12180 /** 12181 * Logic to handle movement of existing installed applications. 12182 */ 12183 class MoveInstallArgs extends InstallArgs { 12184 private File codeFile; 12185 private File resourceFile; 12186 12187 /** New install */ 12188 MoveInstallArgs(InstallParams params) { 12189 super(params.origin, params.move, params.observer, params.installFlags, 12190 params.installerPackageName, params.volumeUuid, 12191 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12192 params.grantedRuntimePermissions, 12193 params.traceMethod, params.traceCookie); 12194 } 12195 12196 int copyApk(IMediaContainerService imcs, boolean temp) { 12197 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12198 + move.fromUuid + " to " + move.toUuid); 12199 synchronized (mInstaller) { 12200 try { 12201 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12202 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12203 } catch (InstallerException e) { 12204 Slog.w(TAG, "Failed to move app", e); 12205 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12206 } 12207 } 12208 12209 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12210 resourceFile = codeFile; 12211 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12212 12213 return PackageManager.INSTALL_SUCCEEDED; 12214 } 12215 12216 int doPreInstall(int status) { 12217 if (status != PackageManager.INSTALL_SUCCEEDED) { 12218 cleanUp(move.toUuid); 12219 } 12220 return status; 12221 } 12222 12223 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12224 if (status != PackageManager.INSTALL_SUCCEEDED) { 12225 cleanUp(move.toUuid); 12226 return false; 12227 } 12228 12229 // Reflect the move in app info 12230 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 12231 pkg.applicationInfo.setCodePath(pkg.codePath); 12232 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 12233 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 12234 pkg.applicationInfo.setResourcePath(pkg.codePath); 12235 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 12236 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 12237 12238 return true; 12239 } 12240 12241 int doPostInstall(int status, int uid) { 12242 if (status == PackageManager.INSTALL_SUCCEEDED) { 12243 cleanUp(move.fromUuid); 12244 } else { 12245 cleanUp(move.toUuid); 12246 } 12247 return status; 12248 } 12249 12250 @Override 12251 String getCodePath() { 12252 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12253 } 12254 12255 @Override 12256 String getResourcePath() { 12257 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12258 } 12259 12260 private boolean cleanUp(String volumeUuid) { 12261 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12262 move.dataAppName); 12263 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12264 synchronized (mInstallLock) { 12265 // Clean up both app data and code 12266 removeDataDirsLI(volumeUuid, move.packageName); 12267 removeCodePathLI(codeFile); 12268 } 12269 return true; 12270 } 12271 12272 void cleanUpResourcesLI() { 12273 throw new UnsupportedOperationException(); 12274 } 12275 12276 boolean doPostDeleteLI(boolean delete) { 12277 throw new UnsupportedOperationException(); 12278 } 12279 } 12280 12281 static String getAsecPackageName(String packageCid) { 12282 int idx = packageCid.lastIndexOf("-"); 12283 if (idx == -1) { 12284 return packageCid; 12285 } 12286 return packageCid.substring(0, idx); 12287 } 12288 12289 // Utility method used to create code paths based on package name and available index. 12290 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12291 String idxStr = ""; 12292 int idx = 1; 12293 // Fall back to default value of idx=1 if prefix is not 12294 // part of oldCodePath 12295 if (oldCodePath != null) { 12296 String subStr = oldCodePath; 12297 // Drop the suffix right away 12298 if (suffix != null && subStr.endsWith(suffix)) { 12299 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12300 } 12301 // If oldCodePath already contains prefix find out the 12302 // ending index to either increment or decrement. 12303 int sidx = subStr.lastIndexOf(prefix); 12304 if (sidx != -1) { 12305 subStr = subStr.substring(sidx + prefix.length()); 12306 if (subStr != null) { 12307 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12308 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12309 } 12310 try { 12311 idx = Integer.parseInt(subStr); 12312 if (idx <= 1) { 12313 idx++; 12314 } else { 12315 idx--; 12316 } 12317 } catch(NumberFormatException e) { 12318 } 12319 } 12320 } 12321 } 12322 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12323 return prefix + idxStr; 12324 } 12325 12326 private File getNextCodePath(File targetDir, String packageName) { 12327 int suffix = 1; 12328 File result; 12329 do { 12330 result = new File(targetDir, packageName + "-" + suffix); 12331 suffix++; 12332 } while (result.exists()); 12333 return result; 12334 } 12335 12336 // Utility method that returns the relative package path with respect 12337 // to the installation directory. Like say for /data/data/com.test-1.apk 12338 // string com.test-1 is returned. 12339 static String deriveCodePathName(String codePath) { 12340 if (codePath == null) { 12341 return null; 12342 } 12343 final File codeFile = new File(codePath); 12344 final String name = codeFile.getName(); 12345 if (codeFile.isDirectory()) { 12346 return name; 12347 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12348 final int lastDot = name.lastIndexOf('.'); 12349 return name.substring(0, lastDot); 12350 } else { 12351 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12352 return null; 12353 } 12354 } 12355 12356 static class PackageInstalledInfo { 12357 String name; 12358 int uid; 12359 // The set of users that originally had this package installed. 12360 int[] origUsers; 12361 // The set of users that now have this package installed. 12362 int[] newUsers; 12363 PackageParser.Package pkg; 12364 int returnCode; 12365 String returnMsg; 12366 PackageRemovedInfo removedInfo; 12367 12368 public void setError(int code, String msg) { 12369 returnCode = code; 12370 returnMsg = msg; 12371 Slog.w(TAG, msg); 12372 } 12373 12374 public void setError(String msg, PackageParserException e) { 12375 returnCode = e.error; 12376 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12377 Slog.w(TAG, msg, e); 12378 } 12379 12380 public void setError(String msg, PackageManagerException e) { 12381 returnCode = e.error; 12382 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12383 Slog.w(TAG, msg, e); 12384 } 12385 12386 // In some error cases we want to convey more info back to the observer 12387 String origPackage; 12388 String origPermission; 12389 } 12390 12391 /* 12392 * Install a non-existing package. 12393 */ 12394 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12395 UserHandle user, String installerPackageName, String volumeUuid, 12396 PackageInstalledInfo res) { 12397 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12398 12399 // Remember this for later, in case we need to rollback this install 12400 String pkgName = pkg.packageName; 12401 12402 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12403 // TODO: b/23350563 12404 final boolean dataDirExists = Environment 12405 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12406 12407 synchronized(mPackages) { 12408 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12409 // A package with the same name is already installed, though 12410 // it has been renamed to an older name. The package we 12411 // are trying to install should be installed as an update to 12412 // the existing one, but that has not been requested, so bail. 12413 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12414 + " without first uninstalling package running as " 12415 + mSettings.mRenamedPackages.get(pkgName)); 12416 return; 12417 } 12418 if (mPackages.containsKey(pkgName)) { 12419 // Don't allow installation over an existing package with the same name. 12420 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12421 + " without first uninstalling."); 12422 return; 12423 } 12424 } 12425 12426 try { 12427 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12428 System.currentTimeMillis(), user); 12429 12430 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12431 prepareAppDataAfterInstall(newPackage); 12432 12433 // delete the partially installed application. the data directory will have to be 12434 // restored if it was already existing 12435 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12436 // remove package from internal structures. Note that we want deletePackageX to 12437 // delete the package data and cache directories that it created in 12438 // scanPackageLocked, unless those directories existed before we even tried to 12439 // install. 12440 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12441 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12442 res.removedInfo, true); 12443 } 12444 12445 } catch (PackageManagerException e) { 12446 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12447 } 12448 12449 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12450 } 12451 12452 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12453 // Can't rotate keys during boot or if sharedUser. 12454 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12455 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12456 return false; 12457 } 12458 // app is using upgradeKeySets; make sure all are valid 12459 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12460 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12461 for (int i = 0; i < upgradeKeySets.length; i++) { 12462 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12463 Slog.wtf(TAG, "Package " 12464 + (oldPs.name != null ? oldPs.name : "<null>") 12465 + " contains upgrade-key-set reference to unknown key-set: " 12466 + upgradeKeySets[i] 12467 + " reverting to signatures check."); 12468 return false; 12469 } 12470 } 12471 return true; 12472 } 12473 12474 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12475 // Upgrade keysets are being used. Determine if new package has a superset of the 12476 // required keys. 12477 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12478 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12479 for (int i = 0; i < upgradeKeySets.length; i++) { 12480 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12481 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12482 return true; 12483 } 12484 } 12485 return false; 12486 } 12487 12488 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12489 UserHandle user, String installerPackageName, String volumeUuid, 12490 PackageInstalledInfo res) { 12491 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12492 12493 final PackageParser.Package oldPackage; 12494 final String pkgName = pkg.packageName; 12495 final int[] allUsers; 12496 final boolean[] perUserInstalled; 12497 12498 // First find the old package info and check signatures 12499 synchronized(mPackages) { 12500 oldPackage = mPackages.get(pkgName); 12501 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12502 if (isEphemeral && !oldIsEphemeral) { 12503 // can't downgrade from full to ephemeral 12504 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12505 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12506 return; 12507 } 12508 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12509 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12510 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12511 if(!checkUpgradeKeySetLP(ps, pkg)) { 12512 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12513 "New package not signed by keys specified by upgrade-keysets: " 12514 + pkgName); 12515 return; 12516 } 12517 } else { 12518 // default to original signature matching 12519 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12520 != PackageManager.SIGNATURE_MATCH) { 12521 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12522 "New package has a different signature: " + pkgName); 12523 return; 12524 } 12525 } 12526 12527 // In case of rollback, remember per-user/profile install state 12528 allUsers = sUserManager.getUserIds(); 12529 perUserInstalled = new boolean[allUsers.length]; 12530 for (int i = 0; i < allUsers.length; i++) { 12531 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12532 } 12533 } 12534 12535 boolean sysPkg = (isSystemApp(oldPackage)); 12536 if (sysPkg) { 12537 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12538 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12539 } else { 12540 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12541 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12542 } 12543 } 12544 12545 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12546 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12547 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12548 String volumeUuid, PackageInstalledInfo res) { 12549 String pkgName = deletedPackage.packageName; 12550 boolean deletedPkg = true; 12551 boolean updatedSettings = false; 12552 12553 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12554 + deletedPackage); 12555 long origUpdateTime; 12556 if (pkg.mExtras != null) { 12557 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12558 } else { 12559 origUpdateTime = 0; 12560 } 12561 12562 // First delete the existing package while retaining the data directory 12563 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12564 res.removedInfo, true)) { 12565 // If the existing package wasn't successfully deleted 12566 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12567 deletedPkg = false; 12568 } else { 12569 // Successfully deleted the old package; proceed with replace. 12570 12571 // If deleted package lived in a container, give users a chance to 12572 // relinquish resources before killing. 12573 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12574 if (DEBUG_INSTALL) { 12575 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12576 } 12577 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12578 final ArrayList<String> pkgList = new ArrayList<String>(1); 12579 pkgList.add(deletedPackage.applicationInfo.packageName); 12580 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12581 } 12582 12583 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12584 try { 12585 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12586 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12587 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12588 perUserInstalled, res, user); 12589 prepareAppDataAfterInstall(newPackage); 12590 updatedSettings = true; 12591 } catch (PackageManagerException e) { 12592 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12593 } 12594 } 12595 12596 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12597 // remove package from internal structures. Note that we want deletePackageX to 12598 // delete the package data and cache directories that it created in 12599 // scanPackageLocked, unless those directories existed before we even tried to 12600 // install. 12601 if(updatedSettings) { 12602 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12603 deletePackageLI( 12604 pkgName, null, true, allUsers, perUserInstalled, 12605 PackageManager.DELETE_KEEP_DATA, 12606 res.removedInfo, true); 12607 } 12608 // Since we failed to install the new package we need to restore the old 12609 // package that we deleted. 12610 if (deletedPkg) { 12611 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12612 File restoreFile = new File(deletedPackage.codePath); 12613 // Parse old package 12614 boolean oldExternal = isExternal(deletedPackage); 12615 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12616 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12617 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12618 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12619 try { 12620 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12621 null); 12622 } catch (PackageManagerException e) { 12623 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12624 + e.getMessage()); 12625 return; 12626 } 12627 // Restore of old package succeeded. Update permissions. 12628 // writer 12629 synchronized (mPackages) { 12630 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12631 UPDATE_PERMISSIONS_ALL); 12632 // can downgrade to reader 12633 mSettings.writeLPr(); 12634 } 12635 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12636 } 12637 } 12638 } 12639 12640 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12641 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12642 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12643 String volumeUuid, PackageInstalledInfo res) { 12644 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12645 + ", old=" + deletedPackage); 12646 boolean disabledSystem = false; 12647 boolean updatedSettings = false; 12648 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12649 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12650 != 0) { 12651 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12652 } 12653 String packageName = deletedPackage.packageName; 12654 if (packageName == null) { 12655 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12656 "Attempt to delete null packageName."); 12657 return; 12658 } 12659 PackageParser.Package oldPkg; 12660 PackageSetting oldPkgSetting; 12661 // reader 12662 synchronized (mPackages) { 12663 oldPkg = mPackages.get(packageName); 12664 oldPkgSetting = mSettings.mPackages.get(packageName); 12665 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12666 (oldPkgSetting == null)) { 12667 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12668 "Couldn't find package " + packageName + " information"); 12669 return; 12670 } 12671 } 12672 12673 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12674 12675 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12676 res.removedInfo.removedPackage = packageName; 12677 // Remove existing system package 12678 removePackageLI(oldPkgSetting, true); 12679 // writer 12680 synchronized (mPackages) { 12681 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12682 if (!disabledSystem && deletedPackage != null) { 12683 // We didn't need to disable the .apk as a current system package, 12684 // which means we are replacing another update that is already 12685 // installed. We need to make sure to delete the older one's .apk. 12686 res.removedInfo.args = createInstallArgsForExisting(0, 12687 deletedPackage.applicationInfo.getCodePath(), 12688 deletedPackage.applicationInfo.getResourcePath(), 12689 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12690 } else { 12691 res.removedInfo.args = null; 12692 } 12693 } 12694 12695 // Successfully disabled the old package. Now proceed with re-installation 12696 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12697 12698 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12699 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12700 12701 PackageParser.Package newPackage = null; 12702 try { 12703 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12704 if (newPackage.mExtras != null) { 12705 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12706 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12707 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12708 12709 // is the update attempting to change shared user? that isn't going to work... 12710 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12711 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12712 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12713 + " to " + newPkgSetting.sharedUser); 12714 updatedSettings = true; 12715 } 12716 } 12717 12718 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12719 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12720 perUserInstalled, res, user); 12721 prepareAppDataAfterInstall(newPackage); 12722 updatedSettings = true; 12723 } 12724 12725 } catch (PackageManagerException e) { 12726 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12727 } 12728 12729 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12730 // Re installation failed. Restore old information 12731 // Remove new pkg information 12732 if (newPackage != null) { 12733 removeInstalledPackageLI(newPackage, true); 12734 } 12735 // Add back the old system package 12736 try { 12737 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12738 } catch (PackageManagerException e) { 12739 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12740 } 12741 // Restore the old system information in Settings 12742 synchronized (mPackages) { 12743 if (disabledSystem) { 12744 mSettings.enableSystemPackageLPw(packageName); 12745 } 12746 if (updatedSettings) { 12747 mSettings.setInstallerPackageName(packageName, 12748 oldPkgSetting.installerPackageName); 12749 } 12750 mSettings.writeLPr(); 12751 } 12752 } 12753 } 12754 12755 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12756 // Collect all used permissions in the UID 12757 ArraySet<String> usedPermissions = new ArraySet<>(); 12758 final int packageCount = su.packages.size(); 12759 for (int i = 0; i < packageCount; i++) { 12760 PackageSetting ps = su.packages.valueAt(i); 12761 if (ps.pkg == null) { 12762 continue; 12763 } 12764 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12765 for (int j = 0; j < requestedPermCount; j++) { 12766 String permission = ps.pkg.requestedPermissions.get(j); 12767 BasePermission bp = mSettings.mPermissions.get(permission); 12768 if (bp != null) { 12769 usedPermissions.add(permission); 12770 } 12771 } 12772 } 12773 12774 PermissionsState permissionsState = su.getPermissionsState(); 12775 // Prune install permissions 12776 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12777 final int installPermCount = installPermStates.size(); 12778 for (int i = installPermCount - 1; i >= 0; i--) { 12779 PermissionState permissionState = installPermStates.get(i); 12780 if (!usedPermissions.contains(permissionState.getName())) { 12781 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12782 if (bp != null) { 12783 permissionsState.revokeInstallPermission(bp); 12784 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12785 PackageManager.MASK_PERMISSION_FLAGS, 0); 12786 } 12787 } 12788 } 12789 12790 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12791 12792 // Prune runtime permissions 12793 for (int userId : allUserIds) { 12794 List<PermissionState> runtimePermStates = permissionsState 12795 .getRuntimePermissionStates(userId); 12796 final int runtimePermCount = runtimePermStates.size(); 12797 for (int i = runtimePermCount - 1; i >= 0; i--) { 12798 PermissionState permissionState = runtimePermStates.get(i); 12799 if (!usedPermissions.contains(permissionState.getName())) { 12800 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12801 if (bp != null) { 12802 permissionsState.revokeRuntimePermission(bp, userId); 12803 permissionsState.updatePermissionFlags(bp, userId, 12804 PackageManager.MASK_PERMISSION_FLAGS, 0); 12805 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12806 runtimePermissionChangedUserIds, userId); 12807 } 12808 } 12809 } 12810 } 12811 12812 return runtimePermissionChangedUserIds; 12813 } 12814 12815 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12816 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12817 UserHandle user) { 12818 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12819 12820 String pkgName = newPackage.packageName; 12821 synchronized (mPackages) { 12822 //write settings. the installStatus will be incomplete at this stage. 12823 //note that the new package setting would have already been 12824 //added to mPackages. It hasn't been persisted yet. 12825 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12826 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12827 mSettings.writeLPr(); 12828 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12829 } 12830 12831 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12832 synchronized (mPackages) { 12833 updatePermissionsLPw(newPackage.packageName, newPackage, 12834 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12835 ? UPDATE_PERMISSIONS_ALL : 0)); 12836 // For system-bundled packages, we assume that installing an upgraded version 12837 // of the package implies that the user actually wants to run that new code, 12838 // so we enable the package. 12839 PackageSetting ps = mSettings.mPackages.get(pkgName); 12840 final int userId = user.getIdentifier(); 12841 if (ps != null) { 12842 if (isSystemApp(newPackage)) { 12843 if (DEBUG_INSTALL) { 12844 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12845 } 12846 // Enable system package for requested users 12847 if (res.origUsers != null) { 12848 for (int origUserId : res.origUsers) { 12849 if (userId == UserHandle.USER_ALL || userId == origUserId) { 12850 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12851 origUserId, installerPackageName); 12852 } 12853 } 12854 } 12855 // Also convey the prior install/uninstall state 12856 if (allUsers != null && perUserInstalled != null) { 12857 for (int i = 0; i < allUsers.length; i++) { 12858 if (DEBUG_INSTALL) { 12859 Slog.d(TAG, " user " + allUsers[i] 12860 + " => " + perUserInstalled[i]); 12861 } 12862 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12863 } 12864 // these install state changes will be persisted in the 12865 // upcoming call to mSettings.writeLPr(). 12866 } 12867 } 12868 // It's implied that when a user requests installation, they want the app to be 12869 // installed and enabled. 12870 if (userId != UserHandle.USER_ALL) { 12871 ps.setInstalled(true, userId); 12872 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12873 } 12874 } 12875 res.name = pkgName; 12876 res.uid = newPackage.applicationInfo.uid; 12877 res.pkg = newPackage; 12878 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12879 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12880 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12881 //to update install status 12882 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12883 mSettings.writeLPr(); 12884 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12885 } 12886 12887 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12888 } 12889 12890 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12891 try { 12892 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12893 installPackageLI(args, res); 12894 } finally { 12895 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12896 } 12897 } 12898 12899 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12900 final int installFlags = args.installFlags; 12901 final String installerPackageName = args.installerPackageName; 12902 final String volumeUuid = args.volumeUuid; 12903 final File tmpPackageFile = new File(args.getCodePath()); 12904 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12905 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12906 || (args.volumeUuid != null)); 12907 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 12908 boolean replace = false; 12909 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12910 if (args.move != null) { 12911 // moving a complete application; perfom an initial scan on the new install location 12912 scanFlags |= SCAN_INITIAL; 12913 } 12914 // Result object to be returned 12915 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12916 12917 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12918 12919 // Sanity check 12920 if (ephemeral && (forwardLocked || onExternal)) { 12921 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 12922 + " external=" + onExternal); 12923 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12924 return; 12925 } 12926 12927 // Retrieve PackageSettings and parse package 12928 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12929 | PackageParser.PARSE_ENFORCE_CODE 12930 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12931 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12932 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 12933 PackageParser pp = new PackageParser(); 12934 pp.setSeparateProcesses(mSeparateProcesses); 12935 pp.setDisplayMetrics(mMetrics); 12936 12937 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12938 final PackageParser.Package pkg; 12939 try { 12940 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12941 } catch (PackageParserException e) { 12942 res.setError("Failed parse during installPackageLI", e); 12943 return; 12944 } finally { 12945 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12946 } 12947 12948 // If package doesn't declare API override, mark that we have an install 12949 // time CPU ABI override. 12950 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 12951 pkg.cpuAbiOverride = args.abiOverride; 12952 } 12953 12954 String pkgName = res.name = pkg.packageName; 12955 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12956 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12957 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12958 return; 12959 } 12960 } 12961 12962 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12963 try { 12964 pp.collectCertificates(pkg, parseFlags); 12965 } catch (PackageParserException e) { 12966 res.setError("Failed collect during installPackageLI", e); 12967 return; 12968 } finally { 12969 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12970 } 12971 12972 // Get rid of all references to package scan path via parser. 12973 pp = null; 12974 String oldCodePath = null; 12975 boolean systemApp = false; 12976 synchronized (mPackages) { 12977 // Check if installing already existing package 12978 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12979 String oldName = mSettings.mRenamedPackages.get(pkgName); 12980 if (pkg.mOriginalPackages != null 12981 && pkg.mOriginalPackages.contains(oldName) 12982 && mPackages.containsKey(oldName)) { 12983 // This package is derived from an original package, 12984 // and this device has been updating from that original 12985 // name. We must continue using the original name, so 12986 // rename the new package here. 12987 pkg.setPackageName(oldName); 12988 pkgName = pkg.packageName; 12989 replace = true; 12990 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12991 + oldName + " pkgName=" + pkgName); 12992 } else if (mPackages.containsKey(pkgName)) { 12993 // This package, under its official name, already exists 12994 // on the device; we should replace it. 12995 replace = true; 12996 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12997 } 12998 12999 // Prevent apps opting out from runtime permissions 13000 if (replace) { 13001 PackageParser.Package oldPackage = mPackages.get(pkgName); 13002 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 13003 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 13004 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 13005 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 13006 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 13007 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 13008 + " doesn't support runtime permissions but the old" 13009 + " target SDK " + oldTargetSdk + " does."); 13010 return; 13011 } 13012 } 13013 } 13014 13015 PackageSetting ps = mSettings.mPackages.get(pkgName); 13016 if (ps != null) { 13017 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 13018 13019 // Quick sanity check that we're signed correctly if updating; 13020 // we'll check this again later when scanning, but we want to 13021 // bail early here before tripping over redefined permissions. 13022 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13023 if (!checkUpgradeKeySetLP(ps, pkg)) { 13024 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 13025 + pkg.packageName + " upgrade keys do not match the " 13026 + "previously installed version"); 13027 return; 13028 } 13029 } else { 13030 try { 13031 verifySignaturesLP(ps, pkg); 13032 } catch (PackageManagerException e) { 13033 res.setError(e.error, e.getMessage()); 13034 return; 13035 } 13036 } 13037 13038 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 13039 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 13040 systemApp = (ps.pkg.applicationInfo.flags & 13041 ApplicationInfo.FLAG_SYSTEM) != 0; 13042 } 13043 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13044 } 13045 13046 // Check whether the newly-scanned package wants to define an already-defined perm 13047 int N = pkg.permissions.size(); 13048 for (int i = N-1; i >= 0; i--) { 13049 PackageParser.Permission perm = pkg.permissions.get(i); 13050 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 13051 if (bp != null) { 13052 // If the defining package is signed with our cert, it's okay. This 13053 // also includes the "updating the same package" case, of course. 13054 // "updating same package" could also involve key-rotation. 13055 final boolean sigsOk; 13056 if (bp.sourcePackage.equals(pkg.packageName) 13057 && (bp.packageSetting instanceof PackageSetting) 13058 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 13059 scanFlags))) { 13060 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 13061 } else { 13062 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 13063 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 13064 } 13065 if (!sigsOk) { 13066 // If the owning package is the system itself, we log but allow 13067 // install to proceed; we fail the install on all other permission 13068 // redefinitions. 13069 if (!bp.sourcePackage.equals("android")) { 13070 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 13071 + pkg.packageName + " attempting to redeclare permission " 13072 + perm.info.name + " already owned by " + bp.sourcePackage); 13073 res.origPermission = perm.info.name; 13074 res.origPackage = bp.sourcePackage; 13075 return; 13076 } else { 13077 Slog.w(TAG, "Package " + pkg.packageName 13078 + " attempting to redeclare system permission " 13079 + perm.info.name + "; ignoring new declaration"); 13080 pkg.permissions.remove(i); 13081 } 13082 } 13083 } 13084 } 13085 13086 } 13087 13088 if (systemApp) { 13089 if (onExternal) { 13090 // Abort update; system app can't be replaced with app on sdcard 13091 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 13092 "Cannot install updates to system apps on sdcard"); 13093 return; 13094 } else if (ephemeral) { 13095 // Abort update; system app can't be replaced with an ephemeral app 13096 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 13097 "Cannot update a system app with an ephemeral app"); 13098 return; 13099 } 13100 } 13101 13102 if (args.move != null) { 13103 // We did an in-place move, so dex is ready to roll 13104 scanFlags |= SCAN_NO_DEX; 13105 scanFlags |= SCAN_MOVE; 13106 13107 synchronized (mPackages) { 13108 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13109 if (ps == null) { 13110 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 13111 "Missing settings for moved package " + pkgName); 13112 } 13113 13114 // We moved the entire application as-is, so bring over the 13115 // previously derived ABI information. 13116 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13117 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13118 } 13119 13120 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13121 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13122 scanFlags |= SCAN_NO_DEX; 13123 13124 try { 13125 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 13126 args.abiOverride : pkg.cpuAbiOverride); 13127 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 13128 true /* extract libs */); 13129 } catch (PackageManagerException pme) { 13130 Slog.e(TAG, "Error deriving application ABI", pme); 13131 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13132 return; 13133 } 13134 13135 // Extract package to save the VM unzipping the APK in memory during 13136 // launch. Only do this if profile-guided compilation is enabled because 13137 // otherwise BackgroundDexOptService will not dexopt the package later. 13138 if (mUseJitProfiles) { 13139 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 13140 // Do not run PackageDexOptimizer through the local performDexOpt 13141 // method because `pkg` is not in `mPackages` yet. 13142 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 13143 false /* useProfiles */, true /* extractOnly */); 13144 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13145 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 13146 String msg = "Extracking package failed for " + pkgName; 13147 res.setError(INSTALL_FAILED_DEXOPT, msg); 13148 return; 13149 } 13150 } 13151 } 13152 13153 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13154 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13155 return; 13156 } 13157 13158 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13159 13160 if (replace) { 13161 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13162 installerPackageName, volumeUuid, res); 13163 } else { 13164 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13165 args.user, installerPackageName, volumeUuid, res); 13166 } 13167 synchronized (mPackages) { 13168 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13169 if (ps != null) { 13170 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13171 } 13172 } 13173 } 13174 13175 private void startIntentFilterVerifications(int userId, boolean replacing, 13176 PackageParser.Package pkg) { 13177 if (mIntentFilterVerifierComponent == null) { 13178 Slog.w(TAG, "No IntentFilter verification will not be done as " 13179 + "there is no IntentFilterVerifier available!"); 13180 return; 13181 } 13182 13183 final int verifierUid = getPackageUid( 13184 mIntentFilterVerifierComponent.getPackageName(), 13185 MATCH_DEBUG_TRIAGED_MISSING, 13186 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13187 13188 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 13189 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13190 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13191 mHandler.sendMessage(msg); 13192 } 13193 13194 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13195 PackageParser.Package pkg) { 13196 int size = pkg.activities.size(); 13197 if (size == 0) { 13198 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13199 "No activity, so no need to verify any IntentFilter!"); 13200 return; 13201 } 13202 13203 final boolean hasDomainURLs = hasDomainURLs(pkg); 13204 if (!hasDomainURLs) { 13205 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13206 "No domain URLs, so no need to verify any IntentFilter!"); 13207 return; 13208 } 13209 13210 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13211 + " if any IntentFilter from the " + size 13212 + " Activities needs verification ..."); 13213 13214 int count = 0; 13215 final String packageName = pkg.packageName; 13216 13217 synchronized (mPackages) { 13218 // If this is a new install and we see that we've already run verification for this 13219 // package, we have nothing to do: it means the state was restored from backup. 13220 if (!replacing) { 13221 IntentFilterVerificationInfo ivi = 13222 mSettings.getIntentFilterVerificationLPr(packageName); 13223 if (ivi != null) { 13224 if (DEBUG_DOMAIN_VERIFICATION) { 13225 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13226 + ivi.getStatusString()); 13227 } 13228 return; 13229 } 13230 } 13231 13232 // If any filters need to be verified, then all need to be. 13233 boolean needToVerify = false; 13234 for (PackageParser.Activity a : pkg.activities) { 13235 for (ActivityIntentInfo filter : a.intents) { 13236 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13237 if (DEBUG_DOMAIN_VERIFICATION) { 13238 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13239 } 13240 needToVerify = true; 13241 break; 13242 } 13243 } 13244 } 13245 13246 if (needToVerify) { 13247 final int verificationId = mIntentFilterVerificationToken++; 13248 for (PackageParser.Activity a : pkg.activities) { 13249 for (ActivityIntentInfo filter : a.intents) { 13250 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13251 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13252 "Verification needed for IntentFilter:" + filter.toString()); 13253 mIntentFilterVerifier.addOneIntentFilterVerification( 13254 verifierUid, userId, verificationId, filter, packageName); 13255 count++; 13256 } 13257 } 13258 } 13259 } 13260 } 13261 13262 if (count > 0) { 13263 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13264 + " IntentFilter verification" + (count > 1 ? "s" : "") 13265 + " for userId:" + userId); 13266 mIntentFilterVerifier.startVerifications(userId); 13267 } else { 13268 if (DEBUG_DOMAIN_VERIFICATION) { 13269 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13270 } 13271 } 13272 } 13273 13274 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13275 final ComponentName cn = filter.activity.getComponentName(); 13276 final String packageName = cn.getPackageName(); 13277 13278 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13279 packageName); 13280 if (ivi == null) { 13281 return true; 13282 } 13283 int status = ivi.getStatus(); 13284 switch (status) { 13285 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13286 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13287 return true; 13288 13289 default: 13290 // Nothing to do 13291 return false; 13292 } 13293 } 13294 13295 private static boolean isMultiArch(ApplicationInfo info) { 13296 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13297 } 13298 13299 private static boolean isExternal(PackageParser.Package pkg) { 13300 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13301 } 13302 13303 private static boolean isExternal(PackageSetting ps) { 13304 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13305 } 13306 13307 private static boolean isEphemeral(PackageParser.Package pkg) { 13308 return pkg.applicationInfo.isEphemeralApp(); 13309 } 13310 13311 private static boolean isEphemeral(PackageSetting ps) { 13312 return ps.pkg != null && isEphemeral(ps.pkg); 13313 } 13314 13315 private static boolean isSystemApp(PackageParser.Package pkg) { 13316 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13317 } 13318 13319 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13320 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13321 } 13322 13323 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13324 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13325 } 13326 13327 private static boolean isSystemApp(PackageSetting ps) { 13328 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13329 } 13330 13331 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13332 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13333 } 13334 13335 private int packageFlagsToInstallFlags(PackageSetting ps) { 13336 int installFlags = 0; 13337 if (isEphemeral(ps)) { 13338 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13339 } 13340 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13341 // This existing package was an external ASEC install when we have 13342 // the external flag without a UUID 13343 installFlags |= PackageManager.INSTALL_EXTERNAL; 13344 } 13345 if (ps.isForwardLocked()) { 13346 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13347 } 13348 return installFlags; 13349 } 13350 13351 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13352 if (isExternal(pkg)) { 13353 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13354 return StorageManager.UUID_PRIMARY_PHYSICAL; 13355 } else { 13356 return pkg.volumeUuid; 13357 } 13358 } else { 13359 return StorageManager.UUID_PRIVATE_INTERNAL; 13360 } 13361 } 13362 13363 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13364 if (isExternal(pkg)) { 13365 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13366 return mSettings.getExternalVersion(); 13367 } else { 13368 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13369 } 13370 } else { 13371 return mSettings.getInternalVersion(); 13372 } 13373 } 13374 13375 private void deleteTempPackageFiles() { 13376 final FilenameFilter filter = new FilenameFilter() { 13377 public boolean accept(File dir, String name) { 13378 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13379 } 13380 }; 13381 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13382 file.delete(); 13383 } 13384 } 13385 13386 @Override 13387 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13388 int flags) { 13389 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13390 flags); 13391 } 13392 13393 @Override 13394 public void deletePackage(final String packageName, 13395 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13396 mContext.enforceCallingOrSelfPermission( 13397 android.Manifest.permission.DELETE_PACKAGES, null); 13398 Preconditions.checkNotNull(packageName); 13399 Preconditions.checkNotNull(observer); 13400 final int uid = Binder.getCallingUid(); 13401 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13402 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13403 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13404 mContext.enforceCallingOrSelfPermission( 13405 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13406 "deletePackage for user " + userId); 13407 } 13408 13409 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13410 try { 13411 observer.onPackageDeleted(packageName, 13412 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13413 } catch (RemoteException re) { 13414 } 13415 return; 13416 } 13417 13418 for (int currentUserId : users) { 13419 if (getBlockUninstallForUser(packageName, currentUserId)) { 13420 try { 13421 observer.onPackageDeleted(packageName, 13422 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13423 } catch (RemoteException re) { 13424 } 13425 return; 13426 } 13427 } 13428 13429 if (DEBUG_REMOVE) { 13430 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13431 } 13432 // Queue up an async operation since the package deletion may take a little while. 13433 mHandler.post(new Runnable() { 13434 public void run() { 13435 mHandler.removeCallbacks(this); 13436 final int returnCode = deletePackageX(packageName, userId, flags); 13437 try { 13438 observer.onPackageDeleted(packageName, returnCode, null); 13439 } catch (RemoteException e) { 13440 Log.i(TAG, "Observer no longer exists."); 13441 } //end catch 13442 } //end run 13443 }); 13444 } 13445 13446 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13447 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13448 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13449 try { 13450 if (dpm != null) { 13451 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13452 /* callingUserOnly =*/ false); 13453 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13454 : deviceOwnerComponentName.getPackageName(); 13455 // Does the package contains the device owner? 13456 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13457 // this check is probably not needed, since DO should be registered as a device 13458 // admin on some user too. (Original bug for this: b/17657954) 13459 if (packageName.equals(deviceOwnerPackageName)) { 13460 return true; 13461 } 13462 // Does it contain a device admin for any user? 13463 int[] users; 13464 if (userId == UserHandle.USER_ALL) { 13465 users = sUserManager.getUserIds(); 13466 } else { 13467 users = new int[]{userId}; 13468 } 13469 for (int i = 0; i < users.length; ++i) { 13470 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13471 return true; 13472 } 13473 } 13474 } 13475 } catch (RemoteException e) { 13476 } 13477 return false; 13478 } 13479 13480 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13481 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13482 } 13483 13484 /** 13485 * This method is an internal method that could be get invoked either 13486 * to delete an installed package or to clean up a failed installation. 13487 * After deleting an installed package, a broadcast is sent to notify any 13488 * listeners that the package has been installed. For cleaning up a failed 13489 * installation, the broadcast is not necessary since the package's 13490 * installation wouldn't have sent the initial broadcast either 13491 * The key steps in deleting a package are 13492 * deleting the package information in internal structures like mPackages, 13493 * deleting the packages base directories through installd 13494 * updating mSettings to reflect current status 13495 * persisting settings for later use 13496 * sending a broadcast if necessary 13497 */ 13498 private int deletePackageX(String packageName, int userId, int flags) { 13499 final PackageRemovedInfo info = new PackageRemovedInfo(); 13500 final boolean res; 13501 13502 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13503 ? UserHandle.ALL : new UserHandle(userId); 13504 13505 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13506 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13507 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13508 } 13509 13510 boolean removedForAllUsers = false; 13511 boolean systemUpdate = false; 13512 13513 PackageParser.Package uninstalledPkg; 13514 13515 // for the uninstall-updates case and restricted profiles, remember the per- 13516 // userhandle installed state 13517 int[] allUsers; 13518 boolean[] perUserInstalled; 13519 synchronized (mPackages) { 13520 uninstalledPkg = mPackages.get(packageName); 13521 PackageSetting ps = mSettings.mPackages.get(packageName); 13522 allUsers = sUserManager.getUserIds(); 13523 perUserInstalled = new boolean[allUsers.length]; 13524 for (int i = 0; i < allUsers.length; i++) { 13525 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13526 } 13527 } 13528 13529 synchronized (mInstallLock) { 13530 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13531 res = deletePackageLI(packageName, removeForUser, 13532 true, allUsers, perUserInstalled, 13533 flags | REMOVE_CHATTY, info, true); 13534 systemUpdate = info.isRemovedPackageSystemUpdate; 13535 synchronized (mPackages) { 13536 if (res) { 13537 if (!systemUpdate && mPackages.get(packageName) == null) { 13538 removedForAllUsers = true; 13539 } 13540 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg); 13541 } 13542 } 13543 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13544 + " removedForAllUsers=" + removedForAllUsers); 13545 } 13546 13547 if (res) { 13548 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13549 13550 // If the removed package was a system update, the old system package 13551 // was re-enabled; we need to broadcast this information 13552 if (systemUpdate) { 13553 Bundle extras = new Bundle(1); 13554 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13555 ? info.removedAppId : info.uid); 13556 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13557 13558 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13559 extras, 0, null, null, null); 13560 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13561 extras, 0, null, null, null); 13562 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13563 null, 0, packageName, null, null); 13564 } 13565 } 13566 // Force a gc here. 13567 Runtime.getRuntime().gc(); 13568 // Delete the resources here after sending the broadcast to let 13569 // other processes clean up before deleting resources. 13570 if (info.args != null) { 13571 synchronized (mInstallLock) { 13572 info.args.doPostDeleteLI(true); 13573 } 13574 } 13575 13576 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13577 } 13578 13579 class PackageRemovedInfo { 13580 String removedPackage; 13581 int uid = -1; 13582 int removedAppId = -1; 13583 int[] removedUsers = null; 13584 boolean isRemovedPackageSystemUpdate = false; 13585 // Clean up resources deleted packages. 13586 InstallArgs args = null; 13587 13588 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13589 Bundle extras = new Bundle(1); 13590 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13591 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13592 if (replacing) { 13593 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13594 } 13595 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13596 if (removedPackage != null) { 13597 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13598 extras, 0, null, null, removedUsers); 13599 if (fullRemove && !replacing) { 13600 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13601 extras, 0, null, null, removedUsers); 13602 } 13603 } 13604 if (removedAppId >= 0) { 13605 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 13606 removedUsers); 13607 } 13608 } 13609 } 13610 13611 /* 13612 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13613 * flag is not set, the data directory is removed as well. 13614 * make sure this flag is set for partially installed apps. If not its meaningless to 13615 * delete a partially installed application. 13616 */ 13617 private void removePackageDataLI(PackageSetting ps, 13618 int[] allUserHandles, boolean[] perUserInstalled, 13619 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13620 String packageName = ps.name; 13621 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13622 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13623 // Retrieve object to delete permissions for shared user later on 13624 final PackageSetting deletedPs; 13625 // reader 13626 synchronized (mPackages) { 13627 deletedPs = mSettings.mPackages.get(packageName); 13628 if (outInfo != null) { 13629 outInfo.removedPackage = packageName; 13630 outInfo.removedUsers = deletedPs != null 13631 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13632 : null; 13633 } 13634 } 13635 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13636 removeDataDirsLI(ps.volumeUuid, packageName); 13637 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13638 } 13639 // writer 13640 synchronized (mPackages) { 13641 if (deletedPs != null) { 13642 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13643 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13644 clearDefaultBrowserIfNeeded(packageName); 13645 if (outInfo != null) { 13646 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13647 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13648 } 13649 updatePermissionsLPw(deletedPs.name, null, 0); 13650 if (deletedPs.sharedUser != null) { 13651 // Remove permissions associated with package. Since runtime 13652 // permissions are per user we have to kill the removed package 13653 // or packages running under the shared user of the removed 13654 // package if revoking the permissions requested only by the removed 13655 // package is successful and this causes a change in gids. 13656 for (int userId : UserManagerService.getInstance().getUserIds()) { 13657 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13658 userId); 13659 if (userIdToKill == UserHandle.USER_ALL 13660 || userIdToKill >= UserHandle.USER_SYSTEM) { 13661 // If gids changed for this user, kill all affected packages. 13662 mHandler.post(new Runnable() { 13663 @Override 13664 public void run() { 13665 // This has to happen with no lock held. 13666 killApplication(deletedPs.name, deletedPs.appId, 13667 KILL_APP_REASON_GIDS_CHANGED); 13668 } 13669 }); 13670 break; 13671 } 13672 } 13673 } 13674 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13675 } 13676 // make sure to preserve per-user disabled state if this removal was just 13677 // a downgrade of a system app to the factory package 13678 if (allUserHandles != null && perUserInstalled != null) { 13679 if (DEBUG_REMOVE) { 13680 Slog.d(TAG, "Propagating install state across downgrade"); 13681 } 13682 for (int i = 0; i < allUserHandles.length; i++) { 13683 if (DEBUG_REMOVE) { 13684 Slog.d(TAG, " user " + allUserHandles[i] 13685 + " => " + perUserInstalled[i]); 13686 } 13687 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13688 } 13689 } 13690 } 13691 // can downgrade to reader 13692 if (writeSettings) { 13693 // Save settings now 13694 mSettings.writeLPr(); 13695 } 13696 } 13697 if (outInfo != null) { 13698 // A user ID was deleted here. Go through all users and remove it 13699 // from KeyStore. 13700 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13701 } 13702 } 13703 13704 static boolean locationIsPrivileged(File path) { 13705 try { 13706 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13707 .getCanonicalPath(); 13708 return path.getCanonicalPath().startsWith(privilegedAppDir); 13709 } catch (IOException e) { 13710 Slog.e(TAG, "Unable to access code path " + path); 13711 } 13712 return false; 13713 } 13714 13715 /* 13716 * Tries to delete system package. 13717 */ 13718 private boolean deleteSystemPackageLI(PackageSetting newPs, 13719 int[] allUserHandles, boolean[] perUserInstalled, 13720 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13721 final boolean applyUserRestrictions 13722 = (allUserHandles != null) && (perUserInstalled != null); 13723 PackageSetting disabledPs = null; 13724 // Confirm if the system package has been updated 13725 // An updated system app can be deleted. This will also have to restore 13726 // the system pkg from system partition 13727 // reader 13728 synchronized (mPackages) { 13729 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13730 } 13731 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13732 + " disabledPs=" + disabledPs); 13733 if (disabledPs == null) { 13734 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13735 return false; 13736 } else if (DEBUG_REMOVE) { 13737 Slog.d(TAG, "Deleting system pkg from data partition"); 13738 } 13739 if (DEBUG_REMOVE) { 13740 if (applyUserRestrictions) { 13741 Slog.d(TAG, "Remembering install states:"); 13742 for (int i = 0; i < allUserHandles.length; i++) { 13743 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13744 } 13745 } 13746 } 13747 // Delete the updated package 13748 outInfo.isRemovedPackageSystemUpdate = true; 13749 if (disabledPs.versionCode < newPs.versionCode) { 13750 // Delete data for downgrades 13751 flags &= ~PackageManager.DELETE_KEEP_DATA; 13752 } else { 13753 // Preserve data by setting flag 13754 flags |= PackageManager.DELETE_KEEP_DATA; 13755 } 13756 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13757 allUserHandles, perUserInstalled, outInfo, writeSettings); 13758 if (!ret) { 13759 return false; 13760 } 13761 // writer 13762 synchronized (mPackages) { 13763 // Reinstate the old system package 13764 mSettings.enableSystemPackageLPw(newPs.name); 13765 // Remove any native libraries from the upgraded package. 13766 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13767 } 13768 // Install the system package 13769 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13770 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13771 if (locationIsPrivileged(disabledPs.codePath)) { 13772 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13773 } 13774 13775 final PackageParser.Package newPkg; 13776 try { 13777 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13778 } catch (PackageManagerException e) { 13779 Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage()); 13780 return false; 13781 } 13782 13783 prepareAppDataAfterInstall(newPkg); 13784 13785 // writer 13786 synchronized (mPackages) { 13787 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13788 13789 // Propagate the permissions state as we do not want to drop on the floor 13790 // runtime permissions. The update permissions method below will take 13791 // care of removing obsolete permissions and grant install permissions. 13792 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13793 updatePermissionsLPw(newPkg.packageName, newPkg, 13794 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13795 13796 if (applyUserRestrictions) { 13797 if (DEBUG_REMOVE) { 13798 Slog.d(TAG, "Propagating install state across reinstall"); 13799 } 13800 for (int i = 0; i < allUserHandles.length; i++) { 13801 if (DEBUG_REMOVE) { 13802 Slog.d(TAG, " user " + allUserHandles[i] 13803 + " => " + perUserInstalled[i]); 13804 } 13805 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13806 13807 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13808 } 13809 // Regardless of writeSettings we need to ensure that this restriction 13810 // state propagation is persisted 13811 mSettings.writeAllUsersPackageRestrictionsLPr(); 13812 } 13813 // can downgrade to reader here 13814 if (writeSettings) { 13815 mSettings.writeLPr(); 13816 } 13817 } 13818 return true; 13819 } 13820 13821 private boolean deleteInstalledPackageLI(PackageSetting ps, 13822 boolean deleteCodeAndResources, int flags, 13823 int[] allUserHandles, boolean[] perUserInstalled, 13824 PackageRemovedInfo outInfo, boolean writeSettings) { 13825 if (outInfo != null) { 13826 outInfo.uid = ps.appId; 13827 } 13828 13829 // Delete package data from internal structures and also remove data if flag is set 13830 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13831 13832 // Delete application code and resources 13833 if (deleteCodeAndResources && (outInfo != null)) { 13834 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13835 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13836 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13837 } 13838 return true; 13839 } 13840 13841 @Override 13842 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13843 int userId) { 13844 mContext.enforceCallingOrSelfPermission( 13845 android.Manifest.permission.DELETE_PACKAGES, null); 13846 synchronized (mPackages) { 13847 PackageSetting ps = mSettings.mPackages.get(packageName); 13848 if (ps == null) { 13849 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13850 return false; 13851 } 13852 if (!ps.getInstalled(userId)) { 13853 // Can't block uninstall for an app that is not installed or enabled. 13854 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13855 return false; 13856 } 13857 ps.setBlockUninstall(blockUninstall, userId); 13858 mSettings.writePackageRestrictionsLPr(userId); 13859 } 13860 return true; 13861 } 13862 13863 @Override 13864 public boolean getBlockUninstallForUser(String packageName, int userId) { 13865 synchronized (mPackages) { 13866 PackageSetting ps = mSettings.mPackages.get(packageName); 13867 if (ps == null) { 13868 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13869 return false; 13870 } 13871 return ps.getBlockUninstall(userId); 13872 } 13873 } 13874 13875 @Override 13876 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 13877 int callingUid = Binder.getCallingUid(); 13878 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 13879 throw new SecurityException( 13880 "setRequiredForSystemUser can only be run by the system or root"); 13881 } 13882 synchronized (mPackages) { 13883 PackageSetting ps = mSettings.mPackages.get(packageName); 13884 if (ps == null) { 13885 Log.w(TAG, "Package doesn't exist: " + packageName); 13886 return false; 13887 } 13888 if (systemUserApp) { 13889 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13890 } else { 13891 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13892 } 13893 mSettings.writeLPr(); 13894 } 13895 return true; 13896 } 13897 13898 /* 13899 * This method handles package deletion in general 13900 */ 13901 private boolean deletePackageLI(String packageName, UserHandle user, 13902 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13903 int flags, PackageRemovedInfo outInfo, 13904 boolean writeSettings) { 13905 if (packageName == null) { 13906 Slog.w(TAG, "Attempt to delete null packageName."); 13907 return false; 13908 } 13909 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13910 PackageSetting ps; 13911 boolean dataOnly = false; 13912 int removeUser = -1; 13913 int appId = -1; 13914 synchronized (mPackages) { 13915 ps = mSettings.mPackages.get(packageName); 13916 if (ps == null) { 13917 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13918 return false; 13919 } 13920 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13921 && user.getIdentifier() != UserHandle.USER_ALL) { 13922 // The caller is asking that the package only be deleted for a single 13923 // user. To do this, we just mark its uninstalled state and delete 13924 // its data. If this is a system app, we only allow this to happen if 13925 // they have set the special DELETE_SYSTEM_APP which requests different 13926 // semantics than normal for uninstalling system apps. 13927 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13928 final int userId = user.getIdentifier(); 13929 ps.setUserState(userId, 13930 COMPONENT_ENABLED_STATE_DEFAULT, 13931 false, //installed 13932 true, //stopped 13933 true, //notLaunched 13934 false, //hidden 13935 false, //suspended 13936 null, null, null, 13937 false, // blockUninstall 13938 ps.readUserState(userId).domainVerificationStatus, 0); 13939 if (!isSystemApp(ps)) { 13940 // Do not uninstall the APK if an app should be cached 13941 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 13942 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 13943 // Other user still have this package installed, so all 13944 // we need to do is clear this user's data and save that 13945 // it is uninstalled. 13946 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13947 removeUser = user.getIdentifier(); 13948 appId = ps.appId; 13949 scheduleWritePackageRestrictionsLocked(removeUser); 13950 } else { 13951 // We need to set it back to 'installed' so the uninstall 13952 // broadcasts will be sent correctly. 13953 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13954 ps.setInstalled(true, user.getIdentifier()); 13955 } 13956 } else { 13957 // This is a system app, so we assume that the 13958 // other users still have this package installed, so all 13959 // we need to do is clear this user's data and save that 13960 // it is uninstalled. 13961 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13962 removeUser = user.getIdentifier(); 13963 appId = ps.appId; 13964 scheduleWritePackageRestrictionsLocked(removeUser); 13965 } 13966 } 13967 } 13968 13969 if (removeUser >= 0) { 13970 // From above, we determined that we are deleting this only 13971 // for a single user. Continue the work here. 13972 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13973 if (outInfo != null) { 13974 outInfo.removedPackage = packageName; 13975 outInfo.removedAppId = appId; 13976 outInfo.removedUsers = new int[] {removeUser}; 13977 } 13978 // TODO: triage flags as part of 26466827 13979 final int installerFlags = StorageManager.FLAG_STORAGE_CE 13980 | StorageManager.FLAG_STORAGE_DE; 13981 try { 13982 mInstaller.destroyAppData(ps.volumeUuid, packageName, removeUser, installerFlags); 13983 } catch (InstallerException e) { 13984 Slog.w(TAG, "Failed to delete app data", e); 13985 } 13986 removeKeystoreDataIfNeeded(removeUser, appId); 13987 schedulePackageCleaning(packageName, removeUser, false); 13988 synchronized (mPackages) { 13989 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13990 scheduleWritePackageRestrictionsLocked(removeUser); 13991 } 13992 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13993 } 13994 return true; 13995 } 13996 13997 if (dataOnly) { 13998 // Delete application data first 13999 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 14000 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 14001 return true; 14002 } 14003 14004 boolean ret = false; 14005 if (isSystemApp(ps)) { 14006 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 14007 // When an updated system application is deleted we delete the existing resources as well and 14008 // fall back to existing code in system partition 14009 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 14010 flags, outInfo, writeSettings); 14011 } else { 14012 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 14013 // Kill application pre-emptively especially for apps on sd. 14014 killApplication(packageName, ps.appId, "uninstall pkg"); 14015 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 14016 allUserHandles, perUserInstalled, 14017 outInfo, writeSettings); 14018 } 14019 14020 return ret; 14021 } 14022 14023 private final static class ClearStorageConnection implements ServiceConnection { 14024 IMediaContainerService mContainerService; 14025 14026 @Override 14027 public void onServiceConnected(ComponentName name, IBinder service) { 14028 synchronized (this) { 14029 mContainerService = IMediaContainerService.Stub.asInterface(service); 14030 notifyAll(); 14031 } 14032 } 14033 14034 @Override 14035 public void onServiceDisconnected(ComponentName name) { 14036 } 14037 } 14038 14039 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 14040 final boolean mounted; 14041 if (Environment.isExternalStorageEmulated()) { 14042 mounted = true; 14043 } else { 14044 final String status = Environment.getExternalStorageState(); 14045 14046 mounted = status.equals(Environment.MEDIA_MOUNTED) 14047 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 14048 } 14049 14050 if (!mounted) { 14051 return; 14052 } 14053 14054 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 14055 int[] users; 14056 if (userId == UserHandle.USER_ALL) { 14057 users = sUserManager.getUserIds(); 14058 } else { 14059 users = new int[] { userId }; 14060 } 14061 final ClearStorageConnection conn = new ClearStorageConnection(); 14062 if (mContext.bindServiceAsUser( 14063 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 14064 try { 14065 for (int curUser : users) { 14066 long timeout = SystemClock.uptimeMillis() + 5000; 14067 synchronized (conn) { 14068 long now = SystemClock.uptimeMillis(); 14069 while (conn.mContainerService == null && now < timeout) { 14070 try { 14071 conn.wait(timeout - now); 14072 } catch (InterruptedException e) { 14073 } 14074 } 14075 } 14076 if (conn.mContainerService == null) { 14077 return; 14078 } 14079 14080 final UserEnvironment userEnv = new UserEnvironment(curUser); 14081 clearDirectory(conn.mContainerService, 14082 userEnv.buildExternalStorageAppCacheDirs(packageName)); 14083 if (allData) { 14084 clearDirectory(conn.mContainerService, 14085 userEnv.buildExternalStorageAppDataDirs(packageName)); 14086 clearDirectory(conn.mContainerService, 14087 userEnv.buildExternalStorageAppMediaDirs(packageName)); 14088 } 14089 } 14090 } finally { 14091 mContext.unbindService(conn); 14092 } 14093 } 14094 } 14095 14096 @Override 14097 public void clearApplicationUserData(final String packageName, 14098 final IPackageDataObserver observer, final int userId) { 14099 mContext.enforceCallingOrSelfPermission( 14100 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 14101 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 14102 // Queue up an async operation since the package deletion may take a little while. 14103 mHandler.post(new Runnable() { 14104 public void run() { 14105 mHandler.removeCallbacks(this); 14106 final boolean succeeded; 14107 synchronized (mInstallLock) { 14108 succeeded = clearApplicationUserDataLI(packageName, userId); 14109 } 14110 clearExternalStorageDataSync(packageName, userId, true); 14111 if (succeeded) { 14112 // invoke DeviceStorageMonitor's update method to clear any notifications 14113 DeviceStorageMonitorInternal 14114 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14115 if (dsm != null) { 14116 dsm.checkMemory(); 14117 } 14118 } 14119 if(observer != null) { 14120 try { 14121 observer.onRemoveCompleted(packageName, succeeded); 14122 } catch (RemoteException e) { 14123 Log.i(TAG, "Observer no longer exists."); 14124 } 14125 } //end if observer 14126 } //end run 14127 }); 14128 } 14129 14130 private boolean clearApplicationUserDataLI(String packageName, int userId) { 14131 if (packageName == null) { 14132 Slog.w(TAG, "Attempt to delete null packageName."); 14133 return false; 14134 } 14135 14136 // Try finding details about the requested package 14137 PackageParser.Package pkg; 14138 synchronized (mPackages) { 14139 pkg = mPackages.get(packageName); 14140 if (pkg == null) { 14141 final PackageSetting ps = mSettings.mPackages.get(packageName); 14142 if (ps != null) { 14143 pkg = ps.pkg; 14144 } 14145 } 14146 14147 if (pkg == null) { 14148 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14149 return false; 14150 } 14151 14152 PackageSetting ps = (PackageSetting) pkg.mExtras; 14153 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14154 } 14155 14156 // Always delete data directories for package, even if we found no other 14157 // record of app. This helps users recover from UID mismatches without 14158 // resorting to a full data wipe. 14159 // TODO: triage flags as part of 26466827 14160 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 14161 try { 14162 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 14163 } catch (InstallerException e) { 14164 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 14165 return false; 14166 } 14167 14168 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14169 removeKeystoreDataIfNeeded(userId, appId); 14170 14171 // Create a native library symlink only if we have native libraries 14172 // and if the native libraries are 32 bit libraries. We do not provide 14173 // this symlink for 64 bit libraries. 14174 if (pkg.applicationInfo.primaryCpuAbi != null && 14175 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 14176 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 14177 try { 14178 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 14179 nativeLibPath, userId); 14180 } catch (InstallerException e) { 14181 Slog.w(TAG, "Failed linking native library dir", e); 14182 return false; 14183 } 14184 } 14185 14186 return true; 14187 } 14188 14189 /** 14190 * Reverts user permission state changes (permissions and flags) in 14191 * all packages for a given user. 14192 * 14193 * @param userId The device user for which to do a reset. 14194 */ 14195 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 14196 final int packageCount = mPackages.size(); 14197 for (int i = 0; i < packageCount; i++) { 14198 PackageParser.Package pkg = mPackages.valueAt(i); 14199 PackageSetting ps = (PackageSetting) pkg.mExtras; 14200 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14201 } 14202 } 14203 14204 /** 14205 * Reverts user permission state changes (permissions and flags). 14206 * 14207 * @param ps The package for which to reset. 14208 * @param userId The device user for which to do a reset. 14209 */ 14210 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 14211 final PackageSetting ps, final int userId) { 14212 if (ps.pkg == null) { 14213 return; 14214 } 14215 14216 // These are flags that can change base on user actions. 14217 final int userSettableMask = FLAG_PERMISSION_USER_SET 14218 | FLAG_PERMISSION_USER_FIXED 14219 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 14220 | FLAG_PERMISSION_REVIEW_REQUIRED; 14221 14222 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 14223 | FLAG_PERMISSION_POLICY_FIXED; 14224 14225 boolean writeInstallPermissions = false; 14226 boolean writeRuntimePermissions = false; 14227 14228 final int permissionCount = ps.pkg.requestedPermissions.size(); 14229 for (int i = 0; i < permissionCount; i++) { 14230 String permission = ps.pkg.requestedPermissions.get(i); 14231 14232 BasePermission bp = mSettings.mPermissions.get(permission); 14233 if (bp == null) { 14234 continue; 14235 } 14236 14237 // If shared user we just reset the state to which only this app contributed. 14238 if (ps.sharedUser != null) { 14239 boolean used = false; 14240 final int packageCount = ps.sharedUser.packages.size(); 14241 for (int j = 0; j < packageCount; j++) { 14242 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 14243 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 14244 && pkg.pkg.requestedPermissions.contains(permission)) { 14245 used = true; 14246 break; 14247 } 14248 } 14249 if (used) { 14250 continue; 14251 } 14252 } 14253 14254 PermissionsState permissionsState = ps.getPermissionsState(); 14255 14256 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 14257 14258 // Always clear the user settable flags. 14259 final boolean hasInstallState = permissionsState.getInstallPermissionState( 14260 bp.name) != null; 14261 // If permission review is enabled and this is a legacy app, mark the 14262 // permission as requiring a review as this is the initial state. 14263 int flags = 0; 14264 if (Build.PERMISSIONS_REVIEW_REQUIRED 14265 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 14266 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 14267 } 14268 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 14269 if (hasInstallState) { 14270 writeInstallPermissions = true; 14271 } else { 14272 writeRuntimePermissions = true; 14273 } 14274 } 14275 14276 // Below is only runtime permission handling. 14277 if (!bp.isRuntime()) { 14278 continue; 14279 } 14280 14281 // Never clobber system or policy. 14282 if ((oldFlags & policyOrSystemFlags) != 0) { 14283 continue; 14284 } 14285 14286 // If this permission was granted by default, make sure it is. 14287 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 14288 if (permissionsState.grantRuntimePermission(bp, userId) 14289 != PERMISSION_OPERATION_FAILURE) { 14290 writeRuntimePermissions = true; 14291 } 14292 // If permission review is enabled the permissions for a legacy apps 14293 // are represented as constantly granted runtime ones, so don't revoke. 14294 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 14295 // Otherwise, reset the permission. 14296 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 14297 switch (revokeResult) { 14298 case PERMISSION_OPERATION_SUCCESS: { 14299 writeRuntimePermissions = true; 14300 } break; 14301 14302 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 14303 writeRuntimePermissions = true; 14304 final int appId = ps.appId; 14305 mHandler.post(new Runnable() { 14306 @Override 14307 public void run() { 14308 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 14309 } 14310 }); 14311 } break; 14312 } 14313 } 14314 } 14315 14316 // Synchronously write as we are taking permissions away. 14317 if (writeRuntimePermissions) { 14318 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 14319 } 14320 14321 // Synchronously write as we are taking permissions away. 14322 if (writeInstallPermissions) { 14323 mSettings.writeLPr(); 14324 } 14325 } 14326 14327 /** 14328 * Remove entries from the keystore daemon. Will only remove it if the 14329 * {@code appId} is valid. 14330 */ 14331 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 14332 if (appId < 0) { 14333 return; 14334 } 14335 14336 final KeyStore keyStore = KeyStore.getInstance(); 14337 if (keyStore != null) { 14338 if (userId == UserHandle.USER_ALL) { 14339 for (final int individual : sUserManager.getUserIds()) { 14340 keyStore.clearUid(UserHandle.getUid(individual, appId)); 14341 } 14342 } else { 14343 keyStore.clearUid(UserHandle.getUid(userId, appId)); 14344 } 14345 } else { 14346 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 14347 } 14348 } 14349 14350 @Override 14351 public void deleteApplicationCacheFiles(final String packageName, 14352 final IPackageDataObserver observer) { 14353 mContext.enforceCallingOrSelfPermission( 14354 android.Manifest.permission.DELETE_CACHE_FILES, null); 14355 // Queue up an async operation since the package deletion may take a little while. 14356 final int userId = UserHandle.getCallingUserId(); 14357 mHandler.post(new Runnable() { 14358 public void run() { 14359 mHandler.removeCallbacks(this); 14360 final boolean succeded; 14361 synchronized (mInstallLock) { 14362 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14363 } 14364 clearExternalStorageDataSync(packageName, userId, false); 14365 if (observer != null) { 14366 try { 14367 observer.onRemoveCompleted(packageName, succeded); 14368 } catch (RemoteException e) { 14369 Log.i(TAG, "Observer no longer exists."); 14370 } 14371 } //end if observer 14372 } //end run 14373 }); 14374 } 14375 14376 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14377 if (packageName == null) { 14378 Slog.w(TAG, "Attempt to delete null packageName."); 14379 return false; 14380 } 14381 PackageParser.Package p; 14382 synchronized (mPackages) { 14383 p = mPackages.get(packageName); 14384 } 14385 if (p == null) { 14386 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14387 return false; 14388 } 14389 final ApplicationInfo applicationInfo = p.applicationInfo; 14390 if (applicationInfo == null) { 14391 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14392 return false; 14393 } 14394 // TODO: triage flags as part of 26466827 14395 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 14396 try { 14397 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 14398 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 14399 } catch (InstallerException e) { 14400 Slog.w(TAG, "Couldn't remove cache files for package " 14401 + packageName + " u" + userId, e); 14402 return false; 14403 } 14404 return true; 14405 } 14406 14407 @Override 14408 public void getPackageSizeInfo(final String packageName, int userHandle, 14409 final IPackageStatsObserver observer) { 14410 mContext.enforceCallingOrSelfPermission( 14411 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14412 if (packageName == null) { 14413 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14414 } 14415 14416 PackageStats stats = new PackageStats(packageName, userHandle); 14417 14418 /* 14419 * Queue up an async operation since the package measurement may take a 14420 * little while. 14421 */ 14422 Message msg = mHandler.obtainMessage(INIT_COPY); 14423 msg.obj = new MeasureParams(stats, observer); 14424 mHandler.sendMessage(msg); 14425 } 14426 14427 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14428 PackageStats pStats) { 14429 if (packageName == null) { 14430 Slog.w(TAG, "Attempt to get size of null packageName."); 14431 return false; 14432 } 14433 PackageParser.Package p; 14434 boolean dataOnly = false; 14435 String libDirRoot = null; 14436 String asecPath = null; 14437 PackageSetting ps = null; 14438 synchronized (mPackages) { 14439 p = mPackages.get(packageName); 14440 ps = mSettings.mPackages.get(packageName); 14441 if(p == null) { 14442 dataOnly = true; 14443 if((ps == null) || (ps.pkg == null)) { 14444 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14445 return false; 14446 } 14447 p = ps.pkg; 14448 } 14449 if (ps != null) { 14450 libDirRoot = ps.legacyNativeLibraryPathString; 14451 } 14452 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14453 final long token = Binder.clearCallingIdentity(); 14454 try { 14455 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14456 if (secureContainerId != null) { 14457 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14458 } 14459 } finally { 14460 Binder.restoreCallingIdentity(token); 14461 } 14462 } 14463 } 14464 String publicSrcDir = null; 14465 if(!dataOnly) { 14466 final ApplicationInfo applicationInfo = p.applicationInfo; 14467 if (applicationInfo == null) { 14468 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14469 return false; 14470 } 14471 if (p.isForwardLocked()) { 14472 publicSrcDir = applicationInfo.getBaseResourcePath(); 14473 } 14474 } 14475 // TODO: extend to measure size of split APKs 14476 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14477 // not just the first level. 14478 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14479 // just the primary. 14480 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14481 14482 String apkPath; 14483 File packageDir = new File(p.codePath); 14484 14485 if (packageDir.isDirectory() && p.canHaveOatDir()) { 14486 apkPath = packageDir.getAbsolutePath(); 14487 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 14488 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 14489 libDirRoot = null; 14490 } 14491 } else { 14492 apkPath = p.baseCodePath; 14493 } 14494 14495 // TODO: triage flags as part of 26466827 14496 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 14497 try { 14498 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 14499 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14500 } catch (InstallerException e) { 14501 return false; 14502 } 14503 14504 // Fix-up for forward-locked applications in ASEC containers. 14505 if (!isExternal(p)) { 14506 pStats.codeSize += pStats.externalCodeSize; 14507 pStats.externalCodeSize = 0L; 14508 } 14509 14510 return true; 14511 } 14512 14513 14514 @Override 14515 public void addPackageToPreferred(String packageName) { 14516 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14517 } 14518 14519 @Override 14520 public void removePackageFromPreferred(String packageName) { 14521 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14522 } 14523 14524 @Override 14525 public List<PackageInfo> getPreferredPackages(int flags) { 14526 return new ArrayList<PackageInfo>(); 14527 } 14528 14529 private int getUidTargetSdkVersionLockedLPr(int uid) { 14530 Object obj = mSettings.getUserIdLPr(uid); 14531 if (obj instanceof SharedUserSetting) { 14532 final SharedUserSetting sus = (SharedUserSetting) obj; 14533 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14534 final Iterator<PackageSetting> it = sus.packages.iterator(); 14535 while (it.hasNext()) { 14536 final PackageSetting ps = it.next(); 14537 if (ps.pkg != null) { 14538 int v = ps.pkg.applicationInfo.targetSdkVersion; 14539 if (v < vers) vers = v; 14540 } 14541 } 14542 return vers; 14543 } else if (obj instanceof PackageSetting) { 14544 final PackageSetting ps = (PackageSetting) obj; 14545 if (ps.pkg != null) { 14546 return ps.pkg.applicationInfo.targetSdkVersion; 14547 } 14548 } 14549 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14550 } 14551 14552 @Override 14553 public void addPreferredActivity(IntentFilter filter, int match, 14554 ComponentName[] set, ComponentName activity, int userId) { 14555 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14556 "Adding preferred"); 14557 } 14558 14559 private void addPreferredActivityInternal(IntentFilter filter, int match, 14560 ComponentName[] set, ComponentName activity, boolean always, int userId, 14561 String opname) { 14562 // writer 14563 int callingUid = Binder.getCallingUid(); 14564 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14565 if (filter.countActions() == 0) { 14566 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14567 return; 14568 } 14569 synchronized (mPackages) { 14570 if (mContext.checkCallingOrSelfPermission( 14571 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14572 != PackageManager.PERMISSION_GRANTED) { 14573 if (getUidTargetSdkVersionLockedLPr(callingUid) 14574 < Build.VERSION_CODES.FROYO) { 14575 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14576 + callingUid); 14577 return; 14578 } 14579 mContext.enforceCallingOrSelfPermission( 14580 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14581 } 14582 14583 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14584 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14585 + userId + ":"); 14586 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14587 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14588 scheduleWritePackageRestrictionsLocked(userId); 14589 } 14590 } 14591 14592 @Override 14593 public void replacePreferredActivity(IntentFilter filter, int match, 14594 ComponentName[] set, ComponentName activity, int userId) { 14595 if (filter.countActions() != 1) { 14596 throw new IllegalArgumentException( 14597 "replacePreferredActivity expects filter to have only 1 action."); 14598 } 14599 if (filter.countDataAuthorities() != 0 14600 || filter.countDataPaths() != 0 14601 || filter.countDataSchemes() > 1 14602 || filter.countDataTypes() != 0) { 14603 throw new IllegalArgumentException( 14604 "replacePreferredActivity expects filter to have no data authorities, " + 14605 "paths, or types; and at most one scheme."); 14606 } 14607 14608 final int callingUid = Binder.getCallingUid(); 14609 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14610 synchronized (mPackages) { 14611 if (mContext.checkCallingOrSelfPermission( 14612 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14613 != PackageManager.PERMISSION_GRANTED) { 14614 if (getUidTargetSdkVersionLockedLPr(callingUid) 14615 < Build.VERSION_CODES.FROYO) { 14616 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14617 + Binder.getCallingUid()); 14618 return; 14619 } 14620 mContext.enforceCallingOrSelfPermission( 14621 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14622 } 14623 14624 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14625 if (pir != null) { 14626 // Get all of the existing entries that exactly match this filter. 14627 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14628 if (existing != null && existing.size() == 1) { 14629 PreferredActivity cur = existing.get(0); 14630 if (DEBUG_PREFERRED) { 14631 Slog.i(TAG, "Checking replace of preferred:"); 14632 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14633 if (!cur.mPref.mAlways) { 14634 Slog.i(TAG, " -- CUR; not mAlways!"); 14635 } else { 14636 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14637 Slog.i(TAG, " -- CUR: mSet=" 14638 + Arrays.toString(cur.mPref.mSetComponents)); 14639 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14640 Slog.i(TAG, " -- NEW: mMatch=" 14641 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14642 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14643 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14644 } 14645 } 14646 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14647 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14648 && cur.mPref.sameSet(set)) { 14649 // Setting the preferred activity to what it happens to be already 14650 if (DEBUG_PREFERRED) { 14651 Slog.i(TAG, "Replacing with same preferred activity " 14652 + cur.mPref.mShortComponent + " for user " 14653 + userId + ":"); 14654 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14655 } 14656 return; 14657 } 14658 } 14659 14660 if (existing != null) { 14661 if (DEBUG_PREFERRED) { 14662 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14663 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14664 } 14665 for (int i = 0; i < existing.size(); i++) { 14666 PreferredActivity pa = existing.get(i); 14667 if (DEBUG_PREFERRED) { 14668 Slog.i(TAG, "Removing existing preferred activity " 14669 + pa.mPref.mComponent + ":"); 14670 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14671 } 14672 pir.removeFilter(pa); 14673 } 14674 } 14675 } 14676 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14677 "Replacing preferred"); 14678 } 14679 } 14680 14681 @Override 14682 public void clearPackagePreferredActivities(String packageName) { 14683 final int uid = Binder.getCallingUid(); 14684 // writer 14685 synchronized (mPackages) { 14686 PackageParser.Package pkg = mPackages.get(packageName); 14687 if (pkg == null || pkg.applicationInfo.uid != uid) { 14688 if (mContext.checkCallingOrSelfPermission( 14689 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14690 != PackageManager.PERMISSION_GRANTED) { 14691 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14692 < Build.VERSION_CODES.FROYO) { 14693 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14694 + Binder.getCallingUid()); 14695 return; 14696 } 14697 mContext.enforceCallingOrSelfPermission( 14698 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14699 } 14700 } 14701 14702 int user = UserHandle.getCallingUserId(); 14703 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14704 scheduleWritePackageRestrictionsLocked(user); 14705 } 14706 } 14707 } 14708 14709 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14710 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14711 ArrayList<PreferredActivity> removed = null; 14712 boolean changed = false; 14713 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14714 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14715 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14716 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14717 continue; 14718 } 14719 Iterator<PreferredActivity> it = pir.filterIterator(); 14720 while (it.hasNext()) { 14721 PreferredActivity pa = it.next(); 14722 // Mark entry for removal only if it matches the package name 14723 // and the entry is of type "always". 14724 if (packageName == null || 14725 (pa.mPref.mComponent.getPackageName().equals(packageName) 14726 && pa.mPref.mAlways)) { 14727 if (removed == null) { 14728 removed = new ArrayList<PreferredActivity>(); 14729 } 14730 removed.add(pa); 14731 } 14732 } 14733 if (removed != null) { 14734 for (int j=0; j<removed.size(); j++) { 14735 PreferredActivity pa = removed.get(j); 14736 pir.removeFilter(pa); 14737 } 14738 changed = true; 14739 } 14740 } 14741 return changed; 14742 } 14743 14744 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14745 private void clearIntentFilterVerificationsLPw(int userId) { 14746 final int packageCount = mPackages.size(); 14747 for (int i = 0; i < packageCount; i++) { 14748 PackageParser.Package pkg = mPackages.valueAt(i); 14749 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14750 } 14751 } 14752 14753 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14754 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14755 if (userId == UserHandle.USER_ALL) { 14756 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14757 sUserManager.getUserIds())) { 14758 for (int oneUserId : sUserManager.getUserIds()) { 14759 scheduleWritePackageRestrictionsLocked(oneUserId); 14760 } 14761 } 14762 } else { 14763 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14764 scheduleWritePackageRestrictionsLocked(userId); 14765 } 14766 } 14767 } 14768 14769 void clearDefaultBrowserIfNeeded(String packageName) { 14770 for (int oneUserId : sUserManager.getUserIds()) { 14771 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14772 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14773 if (packageName.equals(defaultBrowserPackageName)) { 14774 setDefaultBrowserPackageName(null, oneUserId); 14775 } 14776 } 14777 } 14778 14779 @Override 14780 public void resetApplicationPreferences(int userId) { 14781 mContext.enforceCallingOrSelfPermission( 14782 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14783 // writer 14784 synchronized (mPackages) { 14785 final long identity = Binder.clearCallingIdentity(); 14786 try { 14787 clearPackagePreferredActivitiesLPw(null, userId); 14788 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14789 // TODO: We have to reset the default SMS and Phone. This requires 14790 // significant refactoring to keep all default apps in the package 14791 // manager (cleaner but more work) or have the services provide 14792 // callbacks to the package manager to request a default app reset. 14793 applyFactoryDefaultBrowserLPw(userId); 14794 clearIntentFilterVerificationsLPw(userId); 14795 primeDomainVerificationsLPw(userId); 14796 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14797 scheduleWritePackageRestrictionsLocked(userId); 14798 } finally { 14799 Binder.restoreCallingIdentity(identity); 14800 } 14801 } 14802 } 14803 14804 @Override 14805 public int getPreferredActivities(List<IntentFilter> outFilters, 14806 List<ComponentName> outActivities, String packageName) { 14807 14808 int num = 0; 14809 final int userId = UserHandle.getCallingUserId(); 14810 // reader 14811 synchronized (mPackages) { 14812 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14813 if (pir != null) { 14814 final Iterator<PreferredActivity> it = pir.filterIterator(); 14815 while (it.hasNext()) { 14816 final PreferredActivity pa = it.next(); 14817 if (packageName == null 14818 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14819 && pa.mPref.mAlways)) { 14820 if (outFilters != null) { 14821 outFilters.add(new IntentFilter(pa)); 14822 } 14823 if (outActivities != null) { 14824 outActivities.add(pa.mPref.mComponent); 14825 } 14826 } 14827 } 14828 } 14829 } 14830 14831 return num; 14832 } 14833 14834 @Override 14835 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14836 int userId) { 14837 int callingUid = Binder.getCallingUid(); 14838 if (callingUid != Process.SYSTEM_UID) { 14839 throw new SecurityException( 14840 "addPersistentPreferredActivity can only be run by the system"); 14841 } 14842 if (filter.countActions() == 0) { 14843 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14844 return; 14845 } 14846 synchronized (mPackages) { 14847 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14848 ":"); 14849 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14850 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14851 new PersistentPreferredActivity(filter, activity)); 14852 scheduleWritePackageRestrictionsLocked(userId); 14853 } 14854 } 14855 14856 @Override 14857 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14858 int callingUid = Binder.getCallingUid(); 14859 if (callingUid != Process.SYSTEM_UID) { 14860 throw new SecurityException( 14861 "clearPackagePersistentPreferredActivities can only be run by the system"); 14862 } 14863 ArrayList<PersistentPreferredActivity> removed = null; 14864 boolean changed = false; 14865 synchronized (mPackages) { 14866 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14867 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14868 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14869 .valueAt(i); 14870 if (userId != thisUserId) { 14871 continue; 14872 } 14873 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14874 while (it.hasNext()) { 14875 PersistentPreferredActivity ppa = it.next(); 14876 // Mark entry for removal only if it matches the package name. 14877 if (ppa.mComponent.getPackageName().equals(packageName)) { 14878 if (removed == null) { 14879 removed = new ArrayList<PersistentPreferredActivity>(); 14880 } 14881 removed.add(ppa); 14882 } 14883 } 14884 if (removed != null) { 14885 for (int j=0; j<removed.size(); j++) { 14886 PersistentPreferredActivity ppa = removed.get(j); 14887 ppir.removeFilter(ppa); 14888 } 14889 changed = true; 14890 } 14891 } 14892 14893 if (changed) { 14894 scheduleWritePackageRestrictionsLocked(userId); 14895 } 14896 } 14897 } 14898 14899 /** 14900 * Common machinery for picking apart a restored XML blob and passing 14901 * it to a caller-supplied functor to be applied to the running system. 14902 */ 14903 private void restoreFromXml(XmlPullParser parser, int userId, 14904 String expectedStartTag, BlobXmlRestorer functor) 14905 throws IOException, XmlPullParserException { 14906 int type; 14907 while ((type = parser.next()) != XmlPullParser.START_TAG 14908 && type != XmlPullParser.END_DOCUMENT) { 14909 } 14910 if (type != XmlPullParser.START_TAG) { 14911 // oops didn't find a start tag?! 14912 if (DEBUG_BACKUP) { 14913 Slog.e(TAG, "Didn't find start tag during restore"); 14914 } 14915 return; 14916 } 14917Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 14918 // this is supposed to be TAG_PREFERRED_BACKUP 14919 if (!expectedStartTag.equals(parser.getName())) { 14920 if (DEBUG_BACKUP) { 14921 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14922 } 14923 return; 14924 } 14925 14926 // skip interfering stuff, then we're aligned with the backing implementation 14927 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14928Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 14929 functor.apply(parser, userId); 14930 } 14931 14932 private interface BlobXmlRestorer { 14933 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14934 } 14935 14936 /** 14937 * Non-Binder method, support for the backup/restore mechanism: write the 14938 * full set of preferred activities in its canonical XML format. Returns the 14939 * XML output as a byte array, or null if there is none. 14940 */ 14941 @Override 14942 public byte[] getPreferredActivityBackup(int userId) { 14943 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14944 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14945 } 14946 14947 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14948 try { 14949 final XmlSerializer serializer = new FastXmlSerializer(); 14950 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14951 serializer.startDocument(null, true); 14952 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14953 14954 synchronized (mPackages) { 14955 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14956 } 14957 14958 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14959 serializer.endDocument(); 14960 serializer.flush(); 14961 } catch (Exception e) { 14962 if (DEBUG_BACKUP) { 14963 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14964 } 14965 return null; 14966 } 14967 14968 return dataStream.toByteArray(); 14969 } 14970 14971 @Override 14972 public void restorePreferredActivities(byte[] backup, int userId) { 14973 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14974 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14975 } 14976 14977 try { 14978 final XmlPullParser parser = Xml.newPullParser(); 14979 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14980 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14981 new BlobXmlRestorer() { 14982 @Override 14983 public void apply(XmlPullParser parser, int userId) 14984 throws XmlPullParserException, IOException { 14985 synchronized (mPackages) { 14986 mSettings.readPreferredActivitiesLPw(parser, userId); 14987 } 14988 } 14989 } ); 14990 } catch (Exception e) { 14991 if (DEBUG_BACKUP) { 14992 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14993 } 14994 } 14995 } 14996 14997 /** 14998 * Non-Binder method, support for the backup/restore mechanism: write the 14999 * default browser (etc) settings in its canonical XML format. Returns the default 15000 * browser XML representation as a byte array, or null if there is none. 15001 */ 15002 @Override 15003 public byte[] getDefaultAppsBackup(int userId) { 15004 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15005 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 15006 } 15007 15008 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15009 try { 15010 final XmlSerializer serializer = new FastXmlSerializer(); 15011 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15012 serializer.startDocument(null, true); 15013 serializer.startTag(null, TAG_DEFAULT_APPS); 15014 15015 synchronized (mPackages) { 15016 mSettings.writeDefaultAppsLPr(serializer, userId); 15017 } 15018 15019 serializer.endTag(null, TAG_DEFAULT_APPS); 15020 serializer.endDocument(); 15021 serializer.flush(); 15022 } catch (Exception e) { 15023 if (DEBUG_BACKUP) { 15024 Slog.e(TAG, "Unable to write default apps for backup", e); 15025 } 15026 return null; 15027 } 15028 15029 return dataStream.toByteArray(); 15030 } 15031 15032 @Override 15033 public void restoreDefaultApps(byte[] backup, int userId) { 15034 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15035 throw new SecurityException("Only the system may call restoreDefaultApps()"); 15036 } 15037 15038 try { 15039 final XmlPullParser parser = Xml.newPullParser(); 15040 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15041 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 15042 new BlobXmlRestorer() { 15043 @Override 15044 public void apply(XmlPullParser parser, int userId) 15045 throws XmlPullParserException, IOException { 15046 synchronized (mPackages) { 15047 mSettings.readDefaultAppsLPw(parser, userId); 15048 } 15049 } 15050 } ); 15051 } catch (Exception e) { 15052 if (DEBUG_BACKUP) { 15053 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 15054 } 15055 } 15056 } 15057 15058 @Override 15059 public byte[] getIntentFilterVerificationBackup(int userId) { 15060 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15061 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 15062 } 15063 15064 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15065 try { 15066 final XmlSerializer serializer = new FastXmlSerializer(); 15067 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15068 serializer.startDocument(null, true); 15069 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 15070 15071 synchronized (mPackages) { 15072 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 15073 } 15074 15075 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 15076 serializer.endDocument(); 15077 serializer.flush(); 15078 } catch (Exception e) { 15079 if (DEBUG_BACKUP) { 15080 Slog.e(TAG, "Unable to write default apps for backup", e); 15081 } 15082 return null; 15083 } 15084 15085 return dataStream.toByteArray(); 15086 } 15087 15088 @Override 15089 public void restoreIntentFilterVerification(byte[] backup, int userId) { 15090 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15091 throw new SecurityException("Only the system may call restorePreferredActivities()"); 15092 } 15093 15094 try { 15095 final XmlPullParser parser = Xml.newPullParser(); 15096 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15097 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 15098 new BlobXmlRestorer() { 15099 @Override 15100 public void apply(XmlPullParser parser, int userId) 15101 throws XmlPullParserException, IOException { 15102 synchronized (mPackages) { 15103 mSettings.readAllDomainVerificationsLPr(parser, userId); 15104 mSettings.writeLPr(); 15105 } 15106 } 15107 } ); 15108 } catch (Exception e) { 15109 if (DEBUG_BACKUP) { 15110 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15111 } 15112 } 15113 } 15114 15115 @Override 15116 public byte[] getPermissionGrantBackup(int userId) { 15117 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15118 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 15119 } 15120 15121 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15122 try { 15123 final XmlSerializer serializer = new FastXmlSerializer(); 15124 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15125 serializer.startDocument(null, true); 15126 serializer.startTag(null, TAG_PERMISSION_BACKUP); 15127 15128 synchronized (mPackages) { 15129 serializeRuntimePermissionGrantsLPr(serializer, userId); 15130 } 15131 15132 serializer.endTag(null, TAG_PERMISSION_BACKUP); 15133 serializer.endDocument(); 15134 serializer.flush(); 15135 } catch (Exception e) { 15136 if (DEBUG_BACKUP) { 15137 Slog.e(TAG, "Unable to write default apps for backup", e); 15138 } 15139 return null; 15140 } 15141 15142 return dataStream.toByteArray(); 15143 } 15144 15145 @Override 15146 public void restorePermissionGrants(byte[] backup, int userId) { 15147 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15148 throw new SecurityException("Only the system may call restorePermissionGrants()"); 15149 } 15150 15151 try { 15152 final XmlPullParser parser = Xml.newPullParser(); 15153 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15154 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 15155 new BlobXmlRestorer() { 15156 @Override 15157 public void apply(XmlPullParser parser, int userId) 15158 throws XmlPullParserException, IOException { 15159 synchronized (mPackages) { 15160 processRestoredPermissionGrantsLPr(parser, userId); 15161 } 15162 } 15163 } ); 15164 } catch (Exception e) { 15165 if (DEBUG_BACKUP) { 15166 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15167 } 15168 } 15169 } 15170 15171 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 15172 throws IOException { 15173 serializer.startTag(null, TAG_ALL_GRANTS); 15174 15175 final int N = mSettings.mPackages.size(); 15176 for (int i = 0; i < N; i++) { 15177 final PackageSetting ps = mSettings.mPackages.valueAt(i); 15178 boolean pkgGrantsKnown = false; 15179 15180 PermissionsState packagePerms = ps.getPermissionsState(); 15181 15182 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 15183 final int grantFlags = state.getFlags(); 15184 // only look at grants that are not system/policy fixed 15185 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 15186 final boolean isGranted = state.isGranted(); 15187 // And only back up the user-twiddled state bits 15188 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 15189 final String packageName = mSettings.mPackages.keyAt(i); 15190 if (!pkgGrantsKnown) { 15191 serializer.startTag(null, TAG_GRANT); 15192 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 15193 pkgGrantsKnown = true; 15194 } 15195 15196 final boolean userSet = 15197 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 15198 final boolean userFixed = 15199 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 15200 final boolean revoke = 15201 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 15202 15203 serializer.startTag(null, TAG_PERMISSION); 15204 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 15205 if (isGranted) { 15206 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 15207 } 15208 if (userSet) { 15209 serializer.attribute(null, ATTR_USER_SET, "true"); 15210 } 15211 if (userFixed) { 15212 serializer.attribute(null, ATTR_USER_FIXED, "true"); 15213 } 15214 if (revoke) { 15215 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 15216 } 15217 serializer.endTag(null, TAG_PERMISSION); 15218 } 15219 } 15220 } 15221 15222 if (pkgGrantsKnown) { 15223 serializer.endTag(null, TAG_GRANT); 15224 } 15225 } 15226 15227 serializer.endTag(null, TAG_ALL_GRANTS); 15228 } 15229 15230 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 15231 throws XmlPullParserException, IOException { 15232 String pkgName = null; 15233 int outerDepth = parser.getDepth(); 15234 int type; 15235 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 15236 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 15237 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 15238 continue; 15239 } 15240 15241 final String tagName = parser.getName(); 15242 if (tagName.equals(TAG_GRANT)) { 15243 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 15244 if (DEBUG_BACKUP) { 15245 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 15246 } 15247 } else if (tagName.equals(TAG_PERMISSION)) { 15248 15249 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 15250 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 15251 15252 int newFlagSet = 0; 15253 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 15254 newFlagSet |= FLAG_PERMISSION_USER_SET; 15255 } 15256 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 15257 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 15258 } 15259 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 15260 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 15261 } 15262 if (DEBUG_BACKUP) { 15263 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 15264 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 15265 } 15266 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15267 if (ps != null) { 15268 // Already installed so we apply the grant immediately 15269 if (DEBUG_BACKUP) { 15270 Slog.v(TAG, " + already installed; applying"); 15271 } 15272 PermissionsState perms = ps.getPermissionsState(); 15273 BasePermission bp = mSettings.mPermissions.get(permName); 15274 if (bp != null) { 15275 if (isGranted) { 15276 perms.grantRuntimePermission(bp, userId); 15277 } 15278 if (newFlagSet != 0) { 15279 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 15280 } 15281 } 15282 } else { 15283 // Need to wait for post-restore install to apply the grant 15284 if (DEBUG_BACKUP) { 15285 Slog.v(TAG, " - not yet installed; saving for later"); 15286 } 15287 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 15288 isGranted, newFlagSet, userId); 15289 } 15290 } else { 15291 PackageManagerService.reportSettingsProblem(Log.WARN, 15292 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 15293 XmlUtils.skipCurrentTag(parser); 15294 } 15295 } 15296 15297 scheduleWriteSettingsLocked(); 15298 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15299 } 15300 15301 @Override 15302 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 15303 int sourceUserId, int targetUserId, int flags) { 15304 mContext.enforceCallingOrSelfPermission( 15305 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15306 int callingUid = Binder.getCallingUid(); 15307 enforceOwnerRights(ownerPackage, callingUid); 15308 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15309 if (intentFilter.countActions() == 0) { 15310 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 15311 return; 15312 } 15313 synchronized (mPackages) { 15314 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 15315 ownerPackage, targetUserId, flags); 15316 CrossProfileIntentResolver resolver = 15317 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15318 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 15319 // We have all those whose filter is equal. Now checking if the rest is equal as well. 15320 if (existing != null) { 15321 int size = existing.size(); 15322 for (int i = 0; i < size; i++) { 15323 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 15324 return; 15325 } 15326 } 15327 } 15328 resolver.addFilter(newFilter); 15329 scheduleWritePackageRestrictionsLocked(sourceUserId); 15330 } 15331 } 15332 15333 @Override 15334 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 15335 mContext.enforceCallingOrSelfPermission( 15336 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15337 int callingUid = Binder.getCallingUid(); 15338 enforceOwnerRights(ownerPackage, callingUid); 15339 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15340 synchronized (mPackages) { 15341 CrossProfileIntentResolver resolver = 15342 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15343 ArraySet<CrossProfileIntentFilter> set = 15344 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 15345 for (CrossProfileIntentFilter filter : set) { 15346 if (filter.getOwnerPackage().equals(ownerPackage)) { 15347 resolver.removeFilter(filter); 15348 } 15349 } 15350 scheduleWritePackageRestrictionsLocked(sourceUserId); 15351 } 15352 } 15353 15354 // Enforcing that callingUid is owning pkg on userId 15355 private void enforceOwnerRights(String pkg, int callingUid) { 15356 // The system owns everything. 15357 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 15358 return; 15359 } 15360 int callingUserId = UserHandle.getUserId(callingUid); 15361 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 15362 if (pi == null) { 15363 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 15364 + callingUserId); 15365 } 15366 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 15367 throw new SecurityException("Calling uid " + callingUid 15368 + " does not own package " + pkg); 15369 } 15370 } 15371 15372 @Override 15373 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 15374 Intent intent = new Intent(Intent.ACTION_MAIN); 15375 intent.addCategory(Intent.CATEGORY_HOME); 15376 15377 final int callingUserId = UserHandle.getCallingUserId(); 15378 List<ResolveInfo> list = queryIntentActivities(intent, null, 15379 PackageManager.GET_META_DATA, callingUserId); 15380 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 15381 true, false, false, callingUserId); 15382 15383 allHomeCandidates.clear(); 15384 if (list != null) { 15385 for (ResolveInfo ri : list) { 15386 allHomeCandidates.add(ri); 15387 } 15388 } 15389 return (preferred == null || preferred.activityInfo == null) 15390 ? null 15391 : new ComponentName(preferred.activityInfo.packageName, 15392 preferred.activityInfo.name); 15393 } 15394 15395 @Override 15396 public void setApplicationEnabledSetting(String appPackageName, 15397 int newState, int flags, int userId, String callingPackage) { 15398 if (!sUserManager.exists(userId)) return; 15399 if (callingPackage == null) { 15400 callingPackage = Integer.toString(Binder.getCallingUid()); 15401 } 15402 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 15403 } 15404 15405 @Override 15406 public void setComponentEnabledSetting(ComponentName componentName, 15407 int newState, int flags, int userId) { 15408 if (!sUserManager.exists(userId)) return; 15409 setEnabledSetting(componentName.getPackageName(), 15410 componentName.getClassName(), newState, flags, userId, null); 15411 } 15412 15413 private void setEnabledSetting(final String packageName, String className, int newState, 15414 final int flags, int userId, String callingPackage) { 15415 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 15416 || newState == COMPONENT_ENABLED_STATE_ENABLED 15417 || newState == COMPONENT_ENABLED_STATE_DISABLED 15418 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 15419 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 15420 throw new IllegalArgumentException("Invalid new component state: " 15421 + newState); 15422 } 15423 PackageSetting pkgSetting; 15424 final int uid = Binder.getCallingUid(); 15425 final int permission = mContext.checkCallingOrSelfPermission( 15426 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15427 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 15428 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15429 boolean sendNow = false; 15430 boolean isApp = (className == null); 15431 String componentName = isApp ? packageName : className; 15432 int packageUid = -1; 15433 ArrayList<String> components; 15434 15435 // writer 15436 synchronized (mPackages) { 15437 pkgSetting = mSettings.mPackages.get(packageName); 15438 if (pkgSetting == null) { 15439 if (className == null) { 15440 throw new IllegalArgumentException("Unknown package: " + packageName); 15441 } 15442 throw new IllegalArgumentException( 15443 "Unknown component: " + packageName + "/" + className); 15444 } 15445 // Allow root and verify that userId is not being specified by a different user 15446 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 15447 throw new SecurityException( 15448 "Permission Denial: attempt to change component state from pid=" 15449 + Binder.getCallingPid() 15450 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 15451 } 15452 if (className == null) { 15453 // We're dealing with an application/package level state change 15454 if (pkgSetting.getEnabled(userId) == newState) { 15455 // Nothing to do 15456 return; 15457 } 15458 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 15459 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 15460 // Don't care about who enables an app. 15461 callingPackage = null; 15462 } 15463 pkgSetting.setEnabled(newState, userId, callingPackage); 15464 // pkgSetting.pkg.mSetEnabled = newState; 15465 } else { 15466 // We're dealing with a component level state change 15467 // First, verify that this is a valid class name. 15468 PackageParser.Package pkg = pkgSetting.pkg; 15469 if (pkg == null || !pkg.hasComponentClassName(className)) { 15470 if (pkg != null && 15471 pkg.applicationInfo.targetSdkVersion >= 15472 Build.VERSION_CODES.JELLY_BEAN) { 15473 throw new IllegalArgumentException("Component class " + className 15474 + " does not exist in " + packageName); 15475 } else { 15476 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 15477 + className + " does not exist in " + packageName); 15478 } 15479 } 15480 switch (newState) { 15481 case COMPONENT_ENABLED_STATE_ENABLED: 15482 if (!pkgSetting.enableComponentLPw(className, userId)) { 15483 return; 15484 } 15485 break; 15486 case COMPONENT_ENABLED_STATE_DISABLED: 15487 if (!pkgSetting.disableComponentLPw(className, userId)) { 15488 return; 15489 } 15490 break; 15491 case COMPONENT_ENABLED_STATE_DEFAULT: 15492 if (!pkgSetting.restoreComponentLPw(className, userId)) { 15493 return; 15494 } 15495 break; 15496 default: 15497 Slog.e(TAG, "Invalid new component state: " + newState); 15498 return; 15499 } 15500 } 15501 scheduleWritePackageRestrictionsLocked(userId); 15502 components = mPendingBroadcasts.get(userId, packageName); 15503 final boolean newPackage = components == null; 15504 if (newPackage) { 15505 components = new ArrayList<String>(); 15506 } 15507 if (!components.contains(componentName)) { 15508 components.add(componentName); 15509 } 15510 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 15511 sendNow = true; 15512 // Purge entry from pending broadcast list if another one exists already 15513 // since we are sending one right away. 15514 mPendingBroadcasts.remove(userId, packageName); 15515 } else { 15516 if (newPackage) { 15517 mPendingBroadcasts.put(userId, packageName, components); 15518 } 15519 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 15520 // Schedule a message 15521 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 15522 } 15523 } 15524 } 15525 15526 long callingId = Binder.clearCallingIdentity(); 15527 try { 15528 if (sendNow) { 15529 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 15530 sendPackageChangedBroadcast(packageName, 15531 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 15532 } 15533 } finally { 15534 Binder.restoreCallingIdentity(callingId); 15535 } 15536 } 15537 15538 private void sendPackageChangedBroadcast(String packageName, 15539 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 15540 if (DEBUG_INSTALL) 15541 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 15542 + componentNames); 15543 Bundle extras = new Bundle(4); 15544 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 15545 String nameList[] = new String[componentNames.size()]; 15546 componentNames.toArray(nameList); 15547 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 15548 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 15549 extras.putInt(Intent.EXTRA_UID, packageUid); 15550 // If this is not reporting a change of the overall package, then only send it 15551 // to registered receivers. We don't want to launch a swath of apps for every 15552 // little component state change. 15553 final int flags = !componentNames.contains(packageName) 15554 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 15555 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 15556 new int[] {UserHandle.getUserId(packageUid)}); 15557 } 15558 15559 @Override 15560 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 15561 if (!sUserManager.exists(userId)) return; 15562 final int uid = Binder.getCallingUid(); 15563 final int permission = mContext.checkCallingOrSelfPermission( 15564 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15565 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15566 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 15567 // writer 15568 synchronized (mPackages) { 15569 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 15570 allowedByPermission, uid, userId)) { 15571 scheduleWritePackageRestrictionsLocked(userId); 15572 } 15573 } 15574 } 15575 15576 @Override 15577 public String getInstallerPackageName(String packageName) { 15578 // reader 15579 synchronized (mPackages) { 15580 return mSettings.getInstallerPackageNameLPr(packageName); 15581 } 15582 } 15583 15584 @Override 15585 public int getApplicationEnabledSetting(String packageName, int userId) { 15586 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15587 int uid = Binder.getCallingUid(); 15588 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 15589 // reader 15590 synchronized (mPackages) { 15591 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 15592 } 15593 } 15594 15595 @Override 15596 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 15597 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15598 int uid = Binder.getCallingUid(); 15599 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 15600 // reader 15601 synchronized (mPackages) { 15602 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 15603 } 15604 } 15605 15606 @Override 15607 public void enterSafeMode() { 15608 enforceSystemOrRoot("Only the system can request entering safe mode"); 15609 15610 if (!mSystemReady) { 15611 mSafeMode = true; 15612 } 15613 } 15614 15615 @Override 15616 public void systemReady() { 15617 mSystemReady = true; 15618 15619 // Read the compatibilty setting when the system is ready. 15620 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 15621 mContext.getContentResolver(), 15622 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 15623 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 15624 if (DEBUG_SETTINGS) { 15625 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 15626 } 15627 15628 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 15629 15630 synchronized (mPackages) { 15631 // Verify that all of the preferred activity components actually 15632 // exist. It is possible for applications to be updated and at 15633 // that point remove a previously declared activity component that 15634 // had been set as a preferred activity. We try to clean this up 15635 // the next time we encounter that preferred activity, but it is 15636 // possible for the user flow to never be able to return to that 15637 // situation so here we do a sanity check to make sure we haven't 15638 // left any junk around. 15639 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 15640 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15641 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15642 removed.clear(); 15643 for (PreferredActivity pa : pir.filterSet()) { 15644 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 15645 removed.add(pa); 15646 } 15647 } 15648 if (removed.size() > 0) { 15649 for (int r=0; r<removed.size(); r++) { 15650 PreferredActivity pa = removed.get(r); 15651 Slog.w(TAG, "Removing dangling preferred activity: " 15652 + pa.mPref.mComponent); 15653 pir.removeFilter(pa); 15654 } 15655 mSettings.writePackageRestrictionsLPr( 15656 mSettings.mPreferredActivities.keyAt(i)); 15657 } 15658 } 15659 15660 for (int userId : UserManagerService.getInstance().getUserIds()) { 15661 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 15662 grantPermissionsUserIds = ArrayUtils.appendInt( 15663 grantPermissionsUserIds, userId); 15664 } 15665 } 15666 } 15667 sUserManager.systemReady(); 15668 15669 // If we upgraded grant all default permissions before kicking off. 15670 for (int userId : grantPermissionsUserIds) { 15671 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15672 } 15673 15674 // Kick off any messages waiting for system ready 15675 if (mPostSystemReadyMessages != null) { 15676 for (Message msg : mPostSystemReadyMessages) { 15677 msg.sendToTarget(); 15678 } 15679 mPostSystemReadyMessages = null; 15680 } 15681 15682 // Watch for external volumes that come and go over time 15683 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15684 storage.registerListener(mStorageListener); 15685 15686 mInstallerService.systemReady(); 15687 mPackageDexOptimizer.systemReady(); 15688 15689 MountServiceInternal mountServiceInternal = LocalServices.getService( 15690 MountServiceInternal.class); 15691 mountServiceInternal.addExternalStoragePolicy( 15692 new MountServiceInternal.ExternalStorageMountPolicy() { 15693 @Override 15694 public int getMountMode(int uid, String packageName) { 15695 if (Process.isIsolated(uid)) { 15696 return Zygote.MOUNT_EXTERNAL_NONE; 15697 } 15698 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15699 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15700 } 15701 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15702 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15703 } 15704 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15705 return Zygote.MOUNT_EXTERNAL_READ; 15706 } 15707 return Zygote.MOUNT_EXTERNAL_WRITE; 15708 } 15709 15710 @Override 15711 public boolean hasExternalStorage(int uid, String packageName) { 15712 return true; 15713 } 15714 }); 15715 } 15716 15717 @Override 15718 public boolean isSafeMode() { 15719 return mSafeMode; 15720 } 15721 15722 @Override 15723 public boolean hasSystemUidErrors() { 15724 return mHasSystemUidErrors; 15725 } 15726 15727 static String arrayToString(int[] array) { 15728 StringBuffer buf = new StringBuffer(128); 15729 buf.append('['); 15730 if (array != null) { 15731 for (int i=0; i<array.length; i++) { 15732 if (i > 0) buf.append(", "); 15733 buf.append(array[i]); 15734 } 15735 } 15736 buf.append(']'); 15737 return buf.toString(); 15738 } 15739 15740 static class DumpState { 15741 public static final int DUMP_LIBS = 1 << 0; 15742 public static final int DUMP_FEATURES = 1 << 1; 15743 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 15744 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 15745 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 15746 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 15747 public static final int DUMP_PERMISSIONS = 1 << 6; 15748 public static final int DUMP_PACKAGES = 1 << 7; 15749 public static final int DUMP_SHARED_USERS = 1 << 8; 15750 public static final int DUMP_MESSAGES = 1 << 9; 15751 public static final int DUMP_PROVIDERS = 1 << 10; 15752 public static final int DUMP_VERIFIERS = 1 << 11; 15753 public static final int DUMP_PREFERRED = 1 << 12; 15754 public static final int DUMP_PREFERRED_XML = 1 << 13; 15755 public static final int DUMP_KEYSETS = 1 << 14; 15756 public static final int DUMP_VERSION = 1 << 15; 15757 public static final int DUMP_INSTALLS = 1 << 16; 15758 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 15759 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 15760 15761 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15762 15763 private int mTypes; 15764 15765 private int mOptions; 15766 15767 private boolean mTitlePrinted; 15768 15769 private SharedUserSetting mSharedUser; 15770 15771 public boolean isDumping(int type) { 15772 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15773 return true; 15774 } 15775 15776 return (mTypes & type) != 0; 15777 } 15778 15779 public void setDump(int type) { 15780 mTypes |= type; 15781 } 15782 15783 public boolean isOptionEnabled(int option) { 15784 return (mOptions & option) != 0; 15785 } 15786 15787 public void setOptionEnabled(int option) { 15788 mOptions |= option; 15789 } 15790 15791 public boolean onTitlePrinted() { 15792 final boolean printed = mTitlePrinted; 15793 mTitlePrinted = true; 15794 return printed; 15795 } 15796 15797 public boolean getTitlePrinted() { 15798 return mTitlePrinted; 15799 } 15800 15801 public void setTitlePrinted(boolean enabled) { 15802 mTitlePrinted = enabled; 15803 } 15804 15805 public SharedUserSetting getSharedUser() { 15806 return mSharedUser; 15807 } 15808 15809 public void setSharedUser(SharedUserSetting user) { 15810 mSharedUser = user; 15811 } 15812 } 15813 15814 @Override 15815 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15816 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15817 (new PackageManagerShellCommand(this)).exec( 15818 this, in, out, err, args, resultReceiver); 15819 } 15820 15821 @Override 15822 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15823 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15824 != PackageManager.PERMISSION_GRANTED) { 15825 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15826 + Binder.getCallingPid() 15827 + ", uid=" + Binder.getCallingUid() 15828 + " without permission " 15829 + android.Manifest.permission.DUMP); 15830 return; 15831 } 15832 15833 DumpState dumpState = new DumpState(); 15834 boolean fullPreferred = false; 15835 boolean checkin = false; 15836 15837 String packageName = null; 15838 ArraySet<String> permissionNames = null; 15839 15840 int opti = 0; 15841 while (opti < args.length) { 15842 String opt = args[opti]; 15843 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15844 break; 15845 } 15846 opti++; 15847 15848 if ("-a".equals(opt)) { 15849 // Right now we only know how to print all. 15850 } else if ("-h".equals(opt)) { 15851 pw.println("Package manager dump options:"); 15852 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15853 pw.println(" --checkin: dump for a checkin"); 15854 pw.println(" -f: print details of intent filters"); 15855 pw.println(" -h: print this help"); 15856 pw.println(" cmd may be one of:"); 15857 pw.println(" l[ibraries]: list known shared libraries"); 15858 pw.println(" f[eatures]: list device features"); 15859 pw.println(" k[eysets]: print known keysets"); 15860 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 15861 pw.println(" perm[issions]: dump permissions"); 15862 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15863 pw.println(" pref[erred]: print preferred package settings"); 15864 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15865 pw.println(" prov[iders]: dump content providers"); 15866 pw.println(" p[ackages]: dump installed packages"); 15867 pw.println(" s[hared-users]: dump shared user IDs"); 15868 pw.println(" m[essages]: print collected runtime messages"); 15869 pw.println(" v[erifiers]: print package verifier info"); 15870 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15871 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15872 pw.println(" version: print database version info"); 15873 pw.println(" write: write current settings now"); 15874 pw.println(" installs: details about install sessions"); 15875 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15876 pw.println(" <package.name>: info about given package"); 15877 return; 15878 } else if ("--checkin".equals(opt)) { 15879 checkin = true; 15880 } else if ("-f".equals(opt)) { 15881 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15882 } else { 15883 pw.println("Unknown argument: " + opt + "; use -h for help"); 15884 } 15885 } 15886 15887 // Is the caller requesting to dump a particular piece of data? 15888 if (opti < args.length) { 15889 String cmd = args[opti]; 15890 opti++; 15891 // Is this a package name? 15892 if ("android".equals(cmd) || cmd.contains(".")) { 15893 packageName = cmd; 15894 // When dumping a single package, we always dump all of its 15895 // filter information since the amount of data will be reasonable. 15896 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15897 } else if ("check-permission".equals(cmd)) { 15898 if (opti >= args.length) { 15899 pw.println("Error: check-permission missing permission argument"); 15900 return; 15901 } 15902 String perm = args[opti]; 15903 opti++; 15904 if (opti >= args.length) { 15905 pw.println("Error: check-permission missing package argument"); 15906 return; 15907 } 15908 String pkg = args[opti]; 15909 opti++; 15910 int user = UserHandle.getUserId(Binder.getCallingUid()); 15911 if (opti < args.length) { 15912 try { 15913 user = Integer.parseInt(args[opti]); 15914 } catch (NumberFormatException e) { 15915 pw.println("Error: check-permission user argument is not a number: " 15916 + args[opti]); 15917 return; 15918 } 15919 } 15920 pw.println(checkPermission(perm, pkg, user)); 15921 return; 15922 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15923 dumpState.setDump(DumpState.DUMP_LIBS); 15924 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15925 dumpState.setDump(DumpState.DUMP_FEATURES); 15926 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15927 if (opti >= args.length) { 15928 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 15929 | DumpState.DUMP_SERVICE_RESOLVERS 15930 | DumpState.DUMP_RECEIVER_RESOLVERS 15931 | DumpState.DUMP_CONTENT_RESOLVERS); 15932 } else { 15933 while (opti < args.length) { 15934 String name = args[opti]; 15935 if ("a".equals(name) || "activity".equals(name)) { 15936 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 15937 } else if ("s".equals(name) || "service".equals(name)) { 15938 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 15939 } else if ("r".equals(name) || "receiver".equals(name)) { 15940 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 15941 } else if ("c".equals(name) || "content".equals(name)) { 15942 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 15943 } else { 15944 pw.println("Error: unknown resolver table type: " + name); 15945 return; 15946 } 15947 opti++; 15948 } 15949 } 15950 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15951 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15952 } else if ("permission".equals(cmd)) { 15953 if (opti >= args.length) { 15954 pw.println("Error: permission requires permission name"); 15955 return; 15956 } 15957 permissionNames = new ArraySet<>(); 15958 while (opti < args.length) { 15959 permissionNames.add(args[opti]); 15960 opti++; 15961 } 15962 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15963 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15964 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15965 dumpState.setDump(DumpState.DUMP_PREFERRED); 15966 } else if ("preferred-xml".equals(cmd)) { 15967 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15968 if (opti < args.length && "--full".equals(args[opti])) { 15969 fullPreferred = true; 15970 opti++; 15971 } 15972 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15973 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15974 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15975 dumpState.setDump(DumpState.DUMP_PACKAGES); 15976 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15977 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15978 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15979 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15980 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15981 dumpState.setDump(DumpState.DUMP_MESSAGES); 15982 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15983 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15984 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15985 || "intent-filter-verifiers".equals(cmd)) { 15986 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15987 } else if ("version".equals(cmd)) { 15988 dumpState.setDump(DumpState.DUMP_VERSION); 15989 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15990 dumpState.setDump(DumpState.DUMP_KEYSETS); 15991 } else if ("installs".equals(cmd)) { 15992 dumpState.setDump(DumpState.DUMP_INSTALLS); 15993 } else if ("write".equals(cmd)) { 15994 synchronized (mPackages) { 15995 mSettings.writeLPr(); 15996 pw.println("Settings written."); 15997 return; 15998 } 15999 } 16000 } 16001 16002 if (checkin) { 16003 pw.println("vers,1"); 16004 } 16005 16006 // reader 16007 synchronized (mPackages) { 16008 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 16009 if (!checkin) { 16010 if (dumpState.onTitlePrinted()) 16011 pw.println(); 16012 pw.println("Database versions:"); 16013 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 16014 } 16015 } 16016 16017 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 16018 if (!checkin) { 16019 if (dumpState.onTitlePrinted()) 16020 pw.println(); 16021 pw.println("Verifiers:"); 16022 pw.print(" Required: "); 16023 pw.print(mRequiredVerifierPackage); 16024 pw.print(" (uid="); 16025 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 16026 UserHandle.USER_SYSTEM)); 16027 pw.println(")"); 16028 } else if (mRequiredVerifierPackage != null) { 16029 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 16030 pw.print(","); 16031 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 16032 UserHandle.USER_SYSTEM)); 16033 } 16034 } 16035 16036 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 16037 packageName == null) { 16038 if (mIntentFilterVerifierComponent != null) { 16039 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 16040 if (!checkin) { 16041 if (dumpState.onTitlePrinted()) 16042 pw.println(); 16043 pw.println("Intent Filter Verifier:"); 16044 pw.print(" Using: "); 16045 pw.print(verifierPackageName); 16046 pw.print(" (uid="); 16047 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 16048 UserHandle.USER_SYSTEM)); 16049 pw.println(")"); 16050 } else if (verifierPackageName != null) { 16051 pw.print("ifv,"); pw.print(verifierPackageName); 16052 pw.print(","); 16053 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 16054 UserHandle.USER_SYSTEM)); 16055 } 16056 } else { 16057 pw.println(); 16058 pw.println("No Intent Filter Verifier available!"); 16059 } 16060 } 16061 16062 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 16063 boolean printedHeader = false; 16064 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 16065 while (it.hasNext()) { 16066 String name = it.next(); 16067 SharedLibraryEntry ent = mSharedLibraries.get(name); 16068 if (!checkin) { 16069 if (!printedHeader) { 16070 if (dumpState.onTitlePrinted()) 16071 pw.println(); 16072 pw.println("Libraries:"); 16073 printedHeader = true; 16074 } 16075 pw.print(" "); 16076 } else { 16077 pw.print("lib,"); 16078 } 16079 pw.print(name); 16080 if (!checkin) { 16081 pw.print(" -> "); 16082 } 16083 if (ent.path != null) { 16084 if (!checkin) { 16085 pw.print("(jar) "); 16086 pw.print(ent.path); 16087 } else { 16088 pw.print(",jar,"); 16089 pw.print(ent.path); 16090 } 16091 } else { 16092 if (!checkin) { 16093 pw.print("(apk) "); 16094 pw.print(ent.apk); 16095 } else { 16096 pw.print(",apk,"); 16097 pw.print(ent.apk); 16098 } 16099 } 16100 pw.println(); 16101 } 16102 } 16103 16104 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 16105 if (dumpState.onTitlePrinted()) 16106 pw.println(); 16107 if (!checkin) { 16108 pw.println("Features:"); 16109 } 16110 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 16111 while (it.hasNext()) { 16112 String name = it.next(); 16113 if (!checkin) { 16114 pw.print(" "); 16115 } else { 16116 pw.print("feat,"); 16117 } 16118 pw.println(name); 16119 } 16120 } 16121 16122 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 16123 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 16124 : "Activity Resolver Table:", " ", packageName, 16125 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16126 dumpState.setTitlePrinted(true); 16127 } 16128 } 16129 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 16130 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 16131 : "Receiver Resolver Table:", " ", packageName, 16132 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16133 dumpState.setTitlePrinted(true); 16134 } 16135 } 16136 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 16137 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 16138 : "Service Resolver Table:", " ", packageName, 16139 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16140 dumpState.setTitlePrinted(true); 16141 } 16142 } 16143 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 16144 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 16145 : "Provider Resolver Table:", " ", packageName, 16146 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16147 dumpState.setTitlePrinted(true); 16148 } 16149 } 16150 16151 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 16152 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16153 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16154 int user = mSettings.mPreferredActivities.keyAt(i); 16155 if (pir.dump(pw, 16156 dumpState.getTitlePrinted() 16157 ? "\nPreferred Activities User " + user + ":" 16158 : "Preferred Activities User " + user + ":", " ", 16159 packageName, true, false)) { 16160 dumpState.setTitlePrinted(true); 16161 } 16162 } 16163 } 16164 16165 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 16166 pw.flush(); 16167 FileOutputStream fout = new FileOutputStream(fd); 16168 BufferedOutputStream str = new BufferedOutputStream(fout); 16169 XmlSerializer serializer = new FastXmlSerializer(); 16170 try { 16171 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 16172 serializer.startDocument(null, true); 16173 serializer.setFeature( 16174 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 16175 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 16176 serializer.endDocument(); 16177 serializer.flush(); 16178 } catch (IllegalArgumentException e) { 16179 pw.println("Failed writing: " + e); 16180 } catch (IllegalStateException e) { 16181 pw.println("Failed writing: " + e); 16182 } catch (IOException e) { 16183 pw.println("Failed writing: " + e); 16184 } 16185 } 16186 16187 if (!checkin 16188 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 16189 && packageName == null) { 16190 pw.println(); 16191 int count = mSettings.mPackages.size(); 16192 if (count == 0) { 16193 pw.println("No applications!"); 16194 pw.println(); 16195 } else { 16196 final String prefix = " "; 16197 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 16198 if (allPackageSettings.size() == 0) { 16199 pw.println("No domain preferred apps!"); 16200 pw.println(); 16201 } else { 16202 pw.println("App verification status:"); 16203 pw.println(); 16204 count = 0; 16205 for (PackageSetting ps : allPackageSettings) { 16206 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 16207 if (ivi == null || ivi.getPackageName() == null) continue; 16208 pw.println(prefix + "Package: " + ivi.getPackageName()); 16209 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 16210 pw.println(prefix + "Status: " + ivi.getStatusString()); 16211 pw.println(); 16212 count++; 16213 } 16214 if (count == 0) { 16215 pw.println(prefix + "No app verification established."); 16216 pw.println(); 16217 } 16218 for (int userId : sUserManager.getUserIds()) { 16219 pw.println("App linkages for user " + userId + ":"); 16220 pw.println(); 16221 count = 0; 16222 for (PackageSetting ps : allPackageSettings) { 16223 final long status = ps.getDomainVerificationStatusForUser(userId); 16224 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 16225 continue; 16226 } 16227 pw.println(prefix + "Package: " + ps.name); 16228 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 16229 String statusStr = IntentFilterVerificationInfo. 16230 getStatusStringFromValue(status); 16231 pw.println(prefix + "Status: " + statusStr); 16232 pw.println(); 16233 count++; 16234 } 16235 if (count == 0) { 16236 pw.println(prefix + "No configured app linkages."); 16237 pw.println(); 16238 } 16239 } 16240 } 16241 } 16242 } 16243 16244 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 16245 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 16246 if (packageName == null && permissionNames == null) { 16247 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 16248 if (iperm == 0) { 16249 if (dumpState.onTitlePrinted()) 16250 pw.println(); 16251 pw.println("AppOp Permissions:"); 16252 } 16253 pw.print(" AppOp Permission "); 16254 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 16255 pw.println(":"); 16256 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 16257 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 16258 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 16259 } 16260 } 16261 } 16262 } 16263 16264 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 16265 boolean printedSomething = false; 16266 for (PackageParser.Provider p : mProviders.mProviders.values()) { 16267 if (packageName != null && !packageName.equals(p.info.packageName)) { 16268 continue; 16269 } 16270 if (!printedSomething) { 16271 if (dumpState.onTitlePrinted()) 16272 pw.println(); 16273 pw.println("Registered ContentProviders:"); 16274 printedSomething = true; 16275 } 16276 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 16277 pw.print(" "); pw.println(p.toString()); 16278 } 16279 printedSomething = false; 16280 for (Map.Entry<String, PackageParser.Provider> entry : 16281 mProvidersByAuthority.entrySet()) { 16282 PackageParser.Provider p = entry.getValue(); 16283 if (packageName != null && !packageName.equals(p.info.packageName)) { 16284 continue; 16285 } 16286 if (!printedSomething) { 16287 if (dumpState.onTitlePrinted()) 16288 pw.println(); 16289 pw.println("ContentProvider Authorities:"); 16290 printedSomething = true; 16291 } 16292 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 16293 pw.print(" "); pw.println(p.toString()); 16294 if (p.info != null && p.info.applicationInfo != null) { 16295 final String appInfo = p.info.applicationInfo.toString(); 16296 pw.print(" applicationInfo="); pw.println(appInfo); 16297 } 16298 } 16299 } 16300 16301 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 16302 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 16303 } 16304 16305 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 16306 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 16307 } 16308 16309 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 16310 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 16311 } 16312 16313 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 16314 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 16315 } 16316 16317 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 16318 // XXX should handle packageName != null by dumping only install data that 16319 // the given package is involved with. 16320 if (dumpState.onTitlePrinted()) pw.println(); 16321 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 16322 } 16323 16324 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 16325 if (dumpState.onTitlePrinted()) pw.println(); 16326 mSettings.dumpReadMessagesLPr(pw, dumpState); 16327 16328 pw.println(); 16329 pw.println("Package warning messages:"); 16330 BufferedReader in = null; 16331 String line = null; 16332 try { 16333 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16334 while ((line = in.readLine()) != null) { 16335 if (line.contains("ignored: updated version")) continue; 16336 pw.println(line); 16337 } 16338 } catch (IOException ignored) { 16339 } finally { 16340 IoUtils.closeQuietly(in); 16341 } 16342 } 16343 16344 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 16345 BufferedReader in = null; 16346 String line = null; 16347 try { 16348 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16349 while ((line = in.readLine()) != null) { 16350 if (line.contains("ignored: updated version")) continue; 16351 pw.print("msg,"); 16352 pw.println(line); 16353 } 16354 } catch (IOException ignored) { 16355 } finally { 16356 IoUtils.closeQuietly(in); 16357 } 16358 } 16359 } 16360 } 16361 16362 private String dumpDomainString(String packageName) { 16363 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 16364 List<IntentFilter> filters = getAllIntentFilters(packageName); 16365 16366 ArraySet<String> result = new ArraySet<>(); 16367 if (iviList.size() > 0) { 16368 for (IntentFilterVerificationInfo ivi : iviList) { 16369 for (String host : ivi.getDomains()) { 16370 result.add(host); 16371 } 16372 } 16373 } 16374 if (filters != null && filters.size() > 0) { 16375 for (IntentFilter filter : filters) { 16376 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 16377 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 16378 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 16379 result.addAll(filter.getHostsList()); 16380 } 16381 } 16382 } 16383 16384 StringBuilder sb = new StringBuilder(result.size() * 16); 16385 for (String domain : result) { 16386 if (sb.length() > 0) sb.append(" "); 16387 sb.append(domain); 16388 } 16389 return sb.toString(); 16390 } 16391 16392 // ------- apps on sdcard specific code ------- 16393 static final boolean DEBUG_SD_INSTALL = false; 16394 16395 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 16396 16397 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 16398 16399 private boolean mMediaMounted = false; 16400 16401 static String getEncryptKey() { 16402 try { 16403 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 16404 SD_ENCRYPTION_KEYSTORE_NAME); 16405 if (sdEncKey == null) { 16406 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 16407 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 16408 if (sdEncKey == null) { 16409 Slog.e(TAG, "Failed to create encryption keys"); 16410 return null; 16411 } 16412 } 16413 return sdEncKey; 16414 } catch (NoSuchAlgorithmException nsae) { 16415 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 16416 return null; 16417 } catch (IOException ioe) { 16418 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 16419 return null; 16420 } 16421 } 16422 16423 /* 16424 * Update media status on PackageManager. 16425 */ 16426 @Override 16427 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 16428 int callingUid = Binder.getCallingUid(); 16429 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 16430 throw new SecurityException("Media status can only be updated by the system"); 16431 } 16432 // reader; this apparently protects mMediaMounted, but should probably 16433 // be a different lock in that case. 16434 synchronized (mPackages) { 16435 Log.i(TAG, "Updating external media status from " 16436 + (mMediaMounted ? "mounted" : "unmounted") + " to " 16437 + (mediaStatus ? "mounted" : "unmounted")); 16438 if (DEBUG_SD_INSTALL) 16439 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 16440 + ", mMediaMounted=" + mMediaMounted); 16441 if (mediaStatus == mMediaMounted) { 16442 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 16443 : 0, -1); 16444 mHandler.sendMessage(msg); 16445 return; 16446 } 16447 mMediaMounted = mediaStatus; 16448 } 16449 // Queue up an async operation since the package installation may take a 16450 // little while. 16451 mHandler.post(new Runnable() { 16452 public void run() { 16453 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 16454 } 16455 }); 16456 } 16457 16458 /** 16459 * Called by MountService when the initial ASECs to scan are available. 16460 * Should block until all the ASEC containers are finished being scanned. 16461 */ 16462 public void scanAvailableAsecs() { 16463 updateExternalMediaStatusInner(true, false, false); 16464 } 16465 16466 /* 16467 * Collect information of applications on external media, map them against 16468 * existing containers and update information based on current mount status. 16469 * Please note that we always have to report status if reportStatus has been 16470 * set to true especially when unloading packages. 16471 */ 16472 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 16473 boolean externalStorage) { 16474 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 16475 int[] uidArr = EmptyArray.INT; 16476 16477 final String[] list = PackageHelper.getSecureContainerList(); 16478 if (ArrayUtils.isEmpty(list)) { 16479 Log.i(TAG, "No secure containers found"); 16480 } else { 16481 // Process list of secure containers and categorize them 16482 // as active or stale based on their package internal state. 16483 16484 // reader 16485 synchronized (mPackages) { 16486 for (String cid : list) { 16487 // Leave stages untouched for now; installer service owns them 16488 if (PackageInstallerService.isStageName(cid)) continue; 16489 16490 if (DEBUG_SD_INSTALL) 16491 Log.i(TAG, "Processing container " + cid); 16492 String pkgName = getAsecPackageName(cid); 16493 if (pkgName == null) { 16494 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 16495 continue; 16496 } 16497 if (DEBUG_SD_INSTALL) 16498 Log.i(TAG, "Looking for pkg : " + pkgName); 16499 16500 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16501 if (ps == null) { 16502 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 16503 continue; 16504 } 16505 16506 /* 16507 * Skip packages that are not external if we're unmounting 16508 * external storage. 16509 */ 16510 if (externalStorage && !isMounted && !isExternal(ps)) { 16511 continue; 16512 } 16513 16514 final AsecInstallArgs args = new AsecInstallArgs(cid, 16515 getAppDexInstructionSets(ps), ps.isForwardLocked()); 16516 // The package status is changed only if the code path 16517 // matches between settings and the container id. 16518 if (ps.codePathString != null 16519 && ps.codePathString.startsWith(args.getCodePath())) { 16520 if (DEBUG_SD_INSTALL) { 16521 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 16522 + " at code path: " + ps.codePathString); 16523 } 16524 16525 // We do have a valid package installed on sdcard 16526 processCids.put(args, ps.codePathString); 16527 final int uid = ps.appId; 16528 if (uid != -1) { 16529 uidArr = ArrayUtils.appendInt(uidArr, uid); 16530 } 16531 } else { 16532 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 16533 + ps.codePathString); 16534 } 16535 } 16536 } 16537 16538 Arrays.sort(uidArr); 16539 } 16540 16541 // Process packages with valid entries. 16542 if (isMounted) { 16543 if (DEBUG_SD_INSTALL) 16544 Log.i(TAG, "Loading packages"); 16545 loadMediaPackages(processCids, uidArr, externalStorage); 16546 startCleaningPackages(); 16547 mInstallerService.onSecureContainersAvailable(); 16548 } else { 16549 if (DEBUG_SD_INSTALL) 16550 Log.i(TAG, "Unloading packages"); 16551 unloadMediaPackages(processCids, uidArr, reportStatus); 16552 } 16553 } 16554 16555 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16556 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 16557 final int size = infos.size(); 16558 final String[] packageNames = new String[size]; 16559 final int[] packageUids = new int[size]; 16560 for (int i = 0; i < size; i++) { 16561 final ApplicationInfo info = infos.get(i); 16562 packageNames[i] = info.packageName; 16563 packageUids[i] = info.uid; 16564 } 16565 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 16566 finishedReceiver); 16567 } 16568 16569 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16570 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16571 sendResourcesChangedBroadcast(mediaStatus, replacing, 16572 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 16573 } 16574 16575 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16576 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16577 int size = pkgList.length; 16578 if (size > 0) { 16579 // Send broadcasts here 16580 Bundle extras = new Bundle(); 16581 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 16582 if (uidArr != null) { 16583 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 16584 } 16585 if (replacing) { 16586 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 16587 } 16588 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 16589 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 16590 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 16591 } 16592 } 16593 16594 /* 16595 * Look at potentially valid container ids from processCids If package 16596 * information doesn't match the one on record or package scanning fails, 16597 * the cid is added to list of removeCids. We currently don't delete stale 16598 * containers. 16599 */ 16600 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 16601 boolean externalStorage) { 16602 ArrayList<String> pkgList = new ArrayList<String>(); 16603 Set<AsecInstallArgs> keys = processCids.keySet(); 16604 16605 for (AsecInstallArgs args : keys) { 16606 String codePath = processCids.get(args); 16607 if (DEBUG_SD_INSTALL) 16608 Log.i(TAG, "Loading container : " + args.cid); 16609 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16610 try { 16611 // Make sure there are no container errors first. 16612 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 16613 Slog.e(TAG, "Failed to mount cid : " + args.cid 16614 + " when installing from sdcard"); 16615 continue; 16616 } 16617 // Check code path here. 16618 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 16619 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 16620 + " does not match one in settings " + codePath); 16621 continue; 16622 } 16623 // Parse package 16624 int parseFlags = mDefParseFlags; 16625 if (args.isExternalAsec()) { 16626 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 16627 } 16628 if (args.isFwdLocked()) { 16629 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 16630 } 16631 16632 synchronized (mInstallLock) { 16633 PackageParser.Package pkg = null; 16634 try { 16635 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 16636 } catch (PackageManagerException e) { 16637 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 16638 } 16639 // Scan the package 16640 if (pkg != null) { 16641 /* 16642 * TODO why is the lock being held? doPostInstall is 16643 * called in other places without the lock. This needs 16644 * to be straightened out. 16645 */ 16646 // writer 16647 synchronized (mPackages) { 16648 retCode = PackageManager.INSTALL_SUCCEEDED; 16649 pkgList.add(pkg.packageName); 16650 // Post process args 16651 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 16652 pkg.applicationInfo.uid); 16653 } 16654 } else { 16655 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 16656 } 16657 } 16658 16659 } finally { 16660 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 16661 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 16662 } 16663 } 16664 } 16665 // writer 16666 synchronized (mPackages) { 16667 // If the platform SDK has changed since the last time we booted, 16668 // we need to re-grant app permission to catch any new ones that 16669 // appear. This is really a hack, and means that apps can in some 16670 // cases get permissions that the user didn't initially explicitly 16671 // allow... it would be nice to have some better way to handle 16672 // this situation. 16673 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 16674 : mSettings.getInternalVersion(); 16675 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 16676 : StorageManager.UUID_PRIVATE_INTERNAL; 16677 16678 int updateFlags = UPDATE_PERMISSIONS_ALL; 16679 if (ver.sdkVersion != mSdkVersion) { 16680 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16681 + mSdkVersion + "; regranting permissions for external"); 16682 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16683 } 16684 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16685 16686 // Yay, everything is now upgraded 16687 ver.forceCurrent(); 16688 16689 // can downgrade to reader 16690 // Persist settings 16691 mSettings.writeLPr(); 16692 } 16693 // Send a broadcast to let everyone know we are done processing 16694 if (pkgList.size() > 0) { 16695 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 16696 } 16697 } 16698 16699 /* 16700 * Utility method to unload a list of specified containers 16701 */ 16702 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 16703 // Just unmount all valid containers. 16704 for (AsecInstallArgs arg : cidArgs) { 16705 synchronized (mInstallLock) { 16706 arg.doPostDeleteLI(false); 16707 } 16708 } 16709 } 16710 16711 /* 16712 * Unload packages mounted on external media. This involves deleting package 16713 * data from internal structures, sending broadcasts about diabled packages, 16714 * gc'ing to free up references, unmounting all secure containers 16715 * corresponding to packages on external media, and posting a 16716 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 16717 * that we always have to post this message if status has been requested no 16718 * matter what. 16719 */ 16720 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 16721 final boolean reportStatus) { 16722 if (DEBUG_SD_INSTALL) 16723 Log.i(TAG, "unloading media packages"); 16724 ArrayList<String> pkgList = new ArrayList<String>(); 16725 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 16726 final Set<AsecInstallArgs> keys = processCids.keySet(); 16727 for (AsecInstallArgs args : keys) { 16728 String pkgName = args.getPackageName(); 16729 if (DEBUG_SD_INSTALL) 16730 Log.i(TAG, "Trying to unload pkg : " + pkgName); 16731 // Delete package internally 16732 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16733 synchronized (mInstallLock) { 16734 boolean res = deletePackageLI(pkgName, null, false, null, null, 16735 PackageManager.DELETE_KEEP_DATA, outInfo, false); 16736 if (res) { 16737 pkgList.add(pkgName); 16738 } else { 16739 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 16740 failedList.add(args); 16741 } 16742 } 16743 } 16744 16745 // reader 16746 synchronized (mPackages) { 16747 // We didn't update the settings after removing each package; 16748 // write them now for all packages. 16749 mSettings.writeLPr(); 16750 } 16751 16752 // We have to absolutely send UPDATED_MEDIA_STATUS only 16753 // after confirming that all the receivers processed the ordered 16754 // broadcast when packages get disabled, force a gc to clean things up. 16755 // and unload all the containers. 16756 if (pkgList.size() > 0) { 16757 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 16758 new IIntentReceiver.Stub() { 16759 public void performReceive(Intent intent, int resultCode, String data, 16760 Bundle extras, boolean ordered, boolean sticky, 16761 int sendingUser) throws RemoteException { 16762 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16763 reportStatus ? 1 : 0, 1, keys); 16764 mHandler.sendMessage(msg); 16765 } 16766 }); 16767 } else { 16768 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16769 keys); 16770 mHandler.sendMessage(msg); 16771 } 16772 } 16773 16774 private void loadPrivatePackages(final VolumeInfo vol) { 16775 mHandler.post(new Runnable() { 16776 @Override 16777 public void run() { 16778 loadPrivatePackagesInner(vol); 16779 } 16780 }); 16781 } 16782 16783 private void loadPrivatePackagesInner(VolumeInfo vol) { 16784 final String volumeUuid = vol.fsUuid; 16785 if (TextUtils.isEmpty(volumeUuid)) { 16786 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 16787 return; 16788 } 16789 16790 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16791 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16792 16793 final VersionInfo ver; 16794 final List<PackageSetting> packages; 16795 synchronized (mPackages) { 16796 ver = mSettings.findOrCreateVersion(volumeUuid); 16797 packages = mSettings.getVolumePackagesLPr(volumeUuid); 16798 } 16799 16800 // TODO: introduce a new concept similar to "frozen" to prevent these 16801 // apps from being launched until after data has been fully reconciled 16802 for (PackageSetting ps : packages) { 16803 synchronized (mInstallLock) { 16804 final PackageParser.Package pkg; 16805 try { 16806 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16807 loaded.add(pkg.applicationInfo); 16808 16809 } catch (PackageManagerException e) { 16810 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16811 } 16812 16813 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16814 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16815 } 16816 } 16817 } 16818 16819 // Reconcile app data for all started/unlocked users 16820 final StorageManager sm = mContext.getSystemService(StorageManager.class); 16821 final UserManager um = mContext.getSystemService(UserManager.class); 16822 for (UserInfo user : um.getUsers()) { 16823 final int flags; 16824 if (um.isUserUnlocked(user.id)) { 16825 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16826 } else if (um.isUserRunning(user.id)) { 16827 flags = StorageManager.FLAG_STORAGE_DE; 16828 } else { 16829 continue; 16830 } 16831 16832 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 16833 reconcileAppsData(volumeUuid, user.id, flags); 16834 } 16835 16836 synchronized (mPackages) { 16837 int updateFlags = UPDATE_PERMISSIONS_ALL; 16838 if (ver.sdkVersion != mSdkVersion) { 16839 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16840 + mSdkVersion + "; regranting permissions for " + volumeUuid); 16841 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16842 } 16843 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16844 16845 // Yay, everything is now upgraded 16846 ver.forceCurrent(); 16847 16848 mSettings.writeLPr(); 16849 } 16850 16851 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16852 sendResourcesChangedBroadcast(true, false, loaded, null); 16853 } 16854 16855 private void unloadPrivatePackages(final VolumeInfo vol) { 16856 mHandler.post(new Runnable() { 16857 @Override 16858 public void run() { 16859 unloadPrivatePackagesInner(vol); 16860 } 16861 }); 16862 } 16863 16864 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16865 final String volumeUuid = vol.fsUuid; 16866 if (TextUtils.isEmpty(volumeUuid)) { 16867 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 16868 return; 16869 } 16870 16871 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16872 synchronized (mInstallLock) { 16873 synchronized (mPackages) { 16874 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 16875 for (PackageSetting ps : packages) { 16876 if (ps.pkg == null) continue; 16877 16878 final ApplicationInfo info = ps.pkg.applicationInfo; 16879 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16880 if (deletePackageLI(ps.name, null, false, null, null, 16881 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16882 unloaded.add(info); 16883 } else { 16884 Slog.w(TAG, "Failed to unload " + ps.codePath); 16885 } 16886 } 16887 16888 mSettings.writeLPr(); 16889 } 16890 } 16891 16892 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16893 sendResourcesChangedBroadcast(false, false, unloaded, null); 16894 } 16895 16896 /** 16897 * Examine all users present on given mounted volume, and destroy data 16898 * belonging to users that are no longer valid, or whose user ID has been 16899 * recycled. 16900 */ 16901 private void reconcileUsers(String volumeUuid) { 16902 final File[] files = FileUtils 16903 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16904 for (File file : files) { 16905 if (!file.isDirectory()) continue; 16906 16907 final int userId; 16908 final UserInfo info; 16909 try { 16910 userId = Integer.parseInt(file.getName()); 16911 info = sUserManager.getUserInfo(userId); 16912 } catch (NumberFormatException e) { 16913 Slog.w(TAG, "Invalid user directory " + file); 16914 continue; 16915 } 16916 16917 boolean destroyUser = false; 16918 if (info == null) { 16919 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16920 + " because no matching user was found"); 16921 destroyUser = true; 16922 } else { 16923 try { 16924 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16925 } catch (IOException e) { 16926 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16927 + " because we failed to enforce serial number: " + e); 16928 destroyUser = true; 16929 } 16930 } 16931 16932 if (destroyUser) { 16933 synchronized (mInstallLock) { 16934 try { 16935 mInstaller.removeUserDataDirs(volumeUuid, userId); 16936 } catch (InstallerException e) { 16937 Slog.w(TAG, "Failed to clean up user dirs", e); 16938 } 16939 } 16940 } 16941 } 16942 } 16943 16944 private void assertPackageKnown(String volumeUuid, String packageName) 16945 throws PackageManagerException { 16946 synchronized (mPackages) { 16947 final PackageSetting ps = mSettings.mPackages.get(packageName); 16948 if (ps == null) { 16949 throw new PackageManagerException("Package " + packageName + " is unknown"); 16950 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16951 throw new PackageManagerException( 16952 "Package " + packageName + " found on unknown volume " + volumeUuid 16953 + "; expected volume " + ps.volumeUuid); 16954 } 16955 } 16956 } 16957 16958 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 16959 throws PackageManagerException { 16960 synchronized (mPackages) { 16961 final PackageSetting ps = mSettings.mPackages.get(packageName); 16962 if (ps == null) { 16963 throw new PackageManagerException("Package " + packageName + " is unknown"); 16964 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16965 throw new PackageManagerException( 16966 "Package " + packageName + " found on unknown volume " + volumeUuid 16967 + "; expected volume " + ps.volumeUuid); 16968 } else if (!ps.getInstalled(userId)) { 16969 throw new PackageManagerException( 16970 "Package " + packageName + " not installed for user " + userId); 16971 } 16972 } 16973 } 16974 16975 /** 16976 * Examine all apps present on given mounted volume, and destroy apps that 16977 * aren't expected, either due to uninstallation or reinstallation on 16978 * another volume. 16979 */ 16980 private void reconcileApps(String volumeUuid) { 16981 final File[] files = FileUtils 16982 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16983 for (File file : files) { 16984 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16985 && !PackageInstallerService.isStageName(file.getName()); 16986 if (!isPackage) { 16987 // Ignore entries which are not packages 16988 continue; 16989 } 16990 16991 try { 16992 final PackageLite pkg = PackageParser.parsePackageLite(file, 16993 PackageParser.PARSE_MUST_BE_APK); 16994 assertPackageKnown(volumeUuid, pkg.packageName); 16995 16996 } catch (PackageParserException | PackageManagerException e) { 16997 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16998 synchronized (mInstallLock) { 16999 removeCodePathLI(file); 17000 } 17001 } 17002 } 17003 } 17004 17005 /** 17006 * Reconcile all app data for the given user. 17007 * <p> 17008 * Verifies that directories exist and that ownership and labeling is 17009 * correct for all installed apps on all mounted volumes. 17010 */ 17011 void reconcileAppsData(int userId, int flags) { 17012 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17013 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 17014 final String volumeUuid = vol.getFsUuid(); 17015 reconcileAppsData(volumeUuid, userId, flags); 17016 } 17017 } 17018 17019 /** 17020 * Reconcile all app data on given mounted volume. 17021 * <p> 17022 * Destroys app data that isn't expected, either due to uninstallation or 17023 * reinstallation on another volume. 17024 * <p> 17025 * Verifies that directories exist and that ownership and labeling is 17026 * correct for all installed apps. 17027 */ 17028 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 17029 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 17030 + Integer.toHexString(flags)); 17031 17032 final File ceDir = Environment.getDataUserCredentialEncryptedDirectory(volumeUuid, userId); 17033 final File deDir = Environment.getDataUserDeviceEncryptedDirectory(volumeUuid, userId); 17034 17035 boolean restoreconNeeded = false; 17036 17037 // First look for stale data that doesn't belong, and check if things 17038 // have changed since we did our last restorecon 17039 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 17040 if (!isUserKeyUnlocked(userId)) { 17041 throw new RuntimeException( 17042 "Yikes, someone asked us to reconcile CE storage while " + userId 17043 + " was still locked; this would have caused massive data loss!"); 17044 } 17045 17046 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 17047 17048 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 17049 for (File file : files) { 17050 final String packageName = file.getName(); 17051 try { 17052 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 17053 } catch (PackageManagerException e) { 17054 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17055 synchronized (mInstallLock) { 17056 destroyAppDataLI(volumeUuid, packageName, userId, 17057 StorageManager.FLAG_STORAGE_CE); 17058 } 17059 } 17060 } 17061 } 17062 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 17063 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 17064 17065 final File[] files = FileUtils.listFilesOrEmpty(deDir); 17066 for (File file : files) { 17067 final String packageName = file.getName(); 17068 try { 17069 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 17070 } catch (PackageManagerException e) { 17071 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17072 synchronized (mInstallLock) { 17073 destroyAppDataLI(volumeUuid, packageName, userId, 17074 StorageManager.FLAG_STORAGE_DE); 17075 } 17076 } 17077 } 17078 } 17079 17080 // Ensure that data directories are ready to roll for all packages 17081 // installed for this volume and user 17082 final List<PackageSetting> packages; 17083 synchronized (mPackages) { 17084 packages = mSettings.getVolumePackagesLPr(volumeUuid); 17085 } 17086 int preparedCount = 0; 17087 for (PackageSetting ps : packages) { 17088 final String packageName = ps.name; 17089 if (ps.pkg == null) { 17090 Slog.w(TAG, "Odd, missing scanned package " + packageName); 17091 // TODO: might be due to legacy ASEC apps; we should circle back 17092 // and reconcile again once they're scanned 17093 continue; 17094 } 17095 17096 if (ps.getInstalled(userId)) { 17097 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 17098 preparedCount++; 17099 } 17100 } 17101 17102 if (restoreconNeeded) { 17103 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 17104 SELinuxMMAC.setRestoreconDone(ceDir); 17105 } 17106 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 17107 SELinuxMMAC.setRestoreconDone(deDir); 17108 } 17109 } 17110 17111 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 17112 + " packages; restoreconNeeded was " + restoreconNeeded); 17113 } 17114 17115 /** 17116 * Prepare app data for the given app just after it was installed or 17117 * upgraded. This method carefully only touches users that it's installed 17118 * for, and it forces a restorecon to handle any seinfo changes. 17119 * <p> 17120 * Verifies that directories exist and that ownership and labeling is 17121 * correct for all installed apps. If there is an ownership mismatch, it 17122 * will try recovering system apps by wiping data; third-party app data is 17123 * left intact. 17124 */ 17125 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 17126 final PackageSetting ps; 17127 synchronized (mPackages) { 17128 ps = mSettings.mPackages.get(pkg.packageName); 17129 } 17130 17131 final UserManager um = mContext.getSystemService(UserManager.class); 17132 for (UserInfo user : um.getUsers()) { 17133 final int flags; 17134 if (um.isUserUnlocked(user.id)) { 17135 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17136 } else if (um.isUserRunning(user.id)) { 17137 flags = StorageManager.FLAG_STORAGE_DE; 17138 } else { 17139 continue; 17140 } 17141 17142 if (ps.getInstalled(user.id)) { 17143 // Whenever an app changes, force a restorecon of its data 17144 // TODO: when user data is locked, mark that we're still dirty 17145 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 17146 } 17147 } 17148 } 17149 17150 /** 17151 * Prepare app data for the given app. 17152 * <p> 17153 * Verifies that directories exist and that ownership and labeling is 17154 * correct for all installed apps. If there is an ownership mismatch, this 17155 * will try recovering system apps by wiping data; third-party app data is 17156 * left intact. 17157 */ 17158 private void prepareAppData(String volumeUuid, int userId, int flags, 17159 PackageParser.Package pkg, boolean restoreconNeeded) { 17160 if (DEBUG_APP_DATA) { 17161 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 17162 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 17163 } 17164 17165 final String packageName = pkg.packageName; 17166 final ApplicationInfo app = pkg.applicationInfo; 17167 final int appId = UserHandle.getAppId(app.uid); 17168 17169 Preconditions.checkNotNull(app.seinfo); 17170 17171 synchronized (mInstallLock) { 17172 try { 17173 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17174 appId, app.seinfo, app.targetSdkVersion); 17175 } catch (InstallerException e) { 17176 if (app.isSystemApp()) { 17177 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 17178 + ", but trying to recover: " + e); 17179 destroyAppDataLI(volumeUuid, packageName, userId, flags); 17180 try { 17181 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17182 appId, app.seinfo, app.targetSdkVersion); 17183 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 17184 } catch (InstallerException e2) { 17185 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 17186 } 17187 } else { 17188 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 17189 } 17190 } 17191 17192 if (restoreconNeeded) { 17193 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 17194 } 17195 17196 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 17197 // Create a native library symlink only if we have native libraries 17198 // and if the native libraries are 32 bit libraries. We do not provide 17199 // this symlink for 64 bit libraries. 17200 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 17201 final String nativeLibPath = app.nativeLibraryDir; 17202 try { 17203 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 17204 nativeLibPath, userId); 17205 } catch (InstallerException e) { 17206 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 17207 } 17208 } 17209 } 17210 } 17211 } 17212 17213 private void unfreezePackage(String packageName) { 17214 synchronized (mPackages) { 17215 final PackageSetting ps = mSettings.mPackages.get(packageName); 17216 if (ps != null) { 17217 ps.frozen = false; 17218 } 17219 } 17220 } 17221 17222 @Override 17223 public int movePackage(final String packageName, final String volumeUuid) { 17224 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17225 17226 final int moveId = mNextMoveId.getAndIncrement(); 17227 mHandler.post(new Runnable() { 17228 @Override 17229 public void run() { 17230 try { 17231 movePackageInternal(packageName, volumeUuid, moveId); 17232 } catch (PackageManagerException e) { 17233 Slog.w(TAG, "Failed to move " + packageName, e); 17234 mMoveCallbacks.notifyStatusChanged(moveId, 17235 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17236 } 17237 } 17238 }); 17239 return moveId; 17240 } 17241 17242 private void movePackageInternal(final String packageName, final String volumeUuid, 17243 final int moveId) throws PackageManagerException { 17244 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 17245 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17246 final PackageManager pm = mContext.getPackageManager(); 17247 17248 final boolean currentAsec; 17249 final String currentVolumeUuid; 17250 final File codeFile; 17251 final String installerPackageName; 17252 final String packageAbiOverride; 17253 final int appId; 17254 final String seinfo; 17255 final String label; 17256 final int targetSdkVersion; 17257 17258 // reader 17259 synchronized (mPackages) { 17260 final PackageParser.Package pkg = mPackages.get(packageName); 17261 final PackageSetting ps = mSettings.mPackages.get(packageName); 17262 if (pkg == null || ps == null) { 17263 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 17264 } 17265 17266 if (pkg.applicationInfo.isSystemApp()) { 17267 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 17268 "Cannot move system application"); 17269 } 17270 17271 if (pkg.applicationInfo.isExternalAsec()) { 17272 currentAsec = true; 17273 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 17274 } else if (pkg.applicationInfo.isForwardLocked()) { 17275 currentAsec = true; 17276 currentVolumeUuid = "forward_locked"; 17277 } else { 17278 currentAsec = false; 17279 currentVolumeUuid = ps.volumeUuid; 17280 17281 final File probe = new File(pkg.codePath); 17282 final File probeOat = new File(probe, "oat"); 17283 if (!probe.isDirectory() || !probeOat.isDirectory()) { 17284 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17285 "Move only supported for modern cluster style installs"); 17286 } 17287 } 17288 17289 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 17290 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17291 "Package already moved to " + volumeUuid); 17292 } 17293 17294 if (ps.frozen) { 17295 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 17296 "Failed to move already frozen package"); 17297 } 17298 ps.frozen = true; 17299 17300 codeFile = new File(pkg.codePath); 17301 installerPackageName = ps.installerPackageName; 17302 packageAbiOverride = ps.cpuAbiOverrideString; 17303 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 17304 seinfo = pkg.applicationInfo.seinfo; 17305 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 17306 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 17307 } 17308 17309 // Now that we're guarded by frozen state, kill app during move 17310 final long token = Binder.clearCallingIdentity(); 17311 try { 17312 killApplication(packageName, appId, "move pkg"); 17313 } finally { 17314 Binder.restoreCallingIdentity(token); 17315 } 17316 17317 final Bundle extras = new Bundle(); 17318 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 17319 extras.putString(Intent.EXTRA_TITLE, label); 17320 mMoveCallbacks.notifyCreated(moveId, extras); 17321 17322 int installFlags; 17323 final boolean moveCompleteApp; 17324 final File measurePath; 17325 17326 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 17327 installFlags = INSTALL_INTERNAL; 17328 moveCompleteApp = !currentAsec; 17329 measurePath = Environment.getDataAppDirectory(volumeUuid); 17330 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 17331 installFlags = INSTALL_EXTERNAL; 17332 moveCompleteApp = false; 17333 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 17334 } else { 17335 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 17336 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 17337 || !volume.isMountedWritable()) { 17338 unfreezePackage(packageName); 17339 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17340 "Move location not mounted private volume"); 17341 } 17342 17343 Preconditions.checkState(!currentAsec); 17344 17345 installFlags = INSTALL_INTERNAL; 17346 moveCompleteApp = true; 17347 measurePath = Environment.getDataAppDirectory(volumeUuid); 17348 } 17349 17350 final PackageStats stats = new PackageStats(null, -1); 17351 synchronized (mInstaller) { 17352 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 17353 unfreezePackage(packageName); 17354 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17355 "Failed to measure package size"); 17356 } 17357 } 17358 17359 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 17360 + stats.dataSize); 17361 17362 final long startFreeBytes = measurePath.getFreeSpace(); 17363 final long sizeBytes; 17364 if (moveCompleteApp) { 17365 sizeBytes = stats.codeSize + stats.dataSize; 17366 } else { 17367 sizeBytes = stats.codeSize; 17368 } 17369 17370 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 17371 unfreezePackage(packageName); 17372 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17373 "Not enough free space to move"); 17374 } 17375 17376 mMoveCallbacks.notifyStatusChanged(moveId, 10); 17377 17378 final CountDownLatch installedLatch = new CountDownLatch(1); 17379 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 17380 @Override 17381 public void onUserActionRequired(Intent intent) throws RemoteException { 17382 throw new IllegalStateException(); 17383 } 17384 17385 @Override 17386 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 17387 Bundle extras) throws RemoteException { 17388 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 17389 + PackageManager.installStatusToString(returnCode, msg)); 17390 17391 installedLatch.countDown(); 17392 17393 // Regardless of success or failure of the move operation, 17394 // always unfreeze the package 17395 unfreezePackage(packageName); 17396 17397 final int status = PackageManager.installStatusToPublicStatus(returnCode); 17398 switch (status) { 17399 case PackageInstaller.STATUS_SUCCESS: 17400 mMoveCallbacks.notifyStatusChanged(moveId, 17401 PackageManager.MOVE_SUCCEEDED); 17402 break; 17403 case PackageInstaller.STATUS_FAILURE_STORAGE: 17404 mMoveCallbacks.notifyStatusChanged(moveId, 17405 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 17406 break; 17407 default: 17408 mMoveCallbacks.notifyStatusChanged(moveId, 17409 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17410 break; 17411 } 17412 } 17413 }; 17414 17415 final MoveInfo move; 17416 if (moveCompleteApp) { 17417 // Kick off a thread to report progress estimates 17418 new Thread() { 17419 @Override 17420 public void run() { 17421 while (true) { 17422 try { 17423 if (installedLatch.await(1, TimeUnit.SECONDS)) { 17424 break; 17425 } 17426 } catch (InterruptedException ignored) { 17427 } 17428 17429 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 17430 final int progress = 10 + (int) MathUtils.constrain( 17431 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 17432 mMoveCallbacks.notifyStatusChanged(moveId, progress); 17433 } 17434 } 17435 }.start(); 17436 17437 final String dataAppName = codeFile.getName(); 17438 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 17439 dataAppName, appId, seinfo, targetSdkVersion); 17440 } else { 17441 move = null; 17442 } 17443 17444 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 17445 17446 final Message msg = mHandler.obtainMessage(INIT_COPY); 17447 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 17448 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 17449 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 17450 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 17451 msg.obj = params; 17452 17453 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 17454 System.identityHashCode(msg.obj)); 17455 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 17456 System.identityHashCode(msg.obj)); 17457 17458 mHandler.sendMessage(msg); 17459 } 17460 17461 @Override 17462 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 17463 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17464 17465 final int realMoveId = mNextMoveId.getAndIncrement(); 17466 final Bundle extras = new Bundle(); 17467 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 17468 mMoveCallbacks.notifyCreated(realMoveId, extras); 17469 17470 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 17471 @Override 17472 public void onCreated(int moveId, Bundle extras) { 17473 // Ignored 17474 } 17475 17476 @Override 17477 public void onStatusChanged(int moveId, int status, long estMillis) { 17478 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 17479 } 17480 }; 17481 17482 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17483 storage.setPrimaryStorageUuid(volumeUuid, callback); 17484 return realMoveId; 17485 } 17486 17487 @Override 17488 public int getMoveStatus(int moveId) { 17489 mContext.enforceCallingOrSelfPermission( 17490 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17491 return mMoveCallbacks.mLastStatus.get(moveId); 17492 } 17493 17494 @Override 17495 public void registerMoveCallback(IPackageMoveObserver callback) { 17496 mContext.enforceCallingOrSelfPermission( 17497 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17498 mMoveCallbacks.register(callback); 17499 } 17500 17501 @Override 17502 public void unregisterMoveCallback(IPackageMoveObserver callback) { 17503 mContext.enforceCallingOrSelfPermission( 17504 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17505 mMoveCallbacks.unregister(callback); 17506 } 17507 17508 @Override 17509 public boolean setInstallLocation(int loc) { 17510 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 17511 null); 17512 if (getInstallLocation() == loc) { 17513 return true; 17514 } 17515 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 17516 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 17517 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 17518 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 17519 return true; 17520 } 17521 return false; 17522 } 17523 17524 @Override 17525 public int getInstallLocation() { 17526 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 17527 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 17528 PackageHelper.APP_INSTALL_AUTO); 17529 } 17530 17531 /** Called by UserManagerService */ 17532 void cleanUpUser(UserManagerService userManager, int userHandle) { 17533 synchronized (mPackages) { 17534 mDirtyUsers.remove(userHandle); 17535 mUserNeedsBadging.delete(userHandle); 17536 mSettings.removeUserLPw(userHandle); 17537 mPendingBroadcasts.remove(userHandle); 17538 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 17539 } 17540 synchronized (mInstallLock) { 17541 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17542 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 17543 final String volumeUuid = vol.getFsUuid(); 17544 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 17545 try { 17546 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 17547 } catch (InstallerException e) { 17548 Slog.w(TAG, "Failed to remove user data", e); 17549 } 17550 } 17551 synchronized (mPackages) { 17552 removeUnusedPackagesLILPw(userManager, userHandle); 17553 } 17554 } 17555 } 17556 17557 /** 17558 * We're removing userHandle and would like to remove any downloaded packages 17559 * that are no longer in use by any other user. 17560 * @param userHandle the user being removed 17561 */ 17562 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 17563 final boolean DEBUG_CLEAN_APKS = false; 17564 int [] users = userManager.getUserIds(); 17565 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 17566 while (psit.hasNext()) { 17567 PackageSetting ps = psit.next(); 17568 if (ps.pkg == null) { 17569 continue; 17570 } 17571 final String packageName = ps.pkg.packageName; 17572 // Skip over if system app 17573 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 17574 continue; 17575 } 17576 if (DEBUG_CLEAN_APKS) { 17577 Slog.i(TAG, "Checking package " + packageName); 17578 } 17579 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 17580 if (keep) { 17581 if (DEBUG_CLEAN_APKS) { 17582 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 17583 } 17584 } else { 17585 for (int i = 0; i < users.length; i++) { 17586 if (users[i] != userHandle && ps.getInstalled(users[i])) { 17587 keep = true; 17588 if (DEBUG_CLEAN_APKS) { 17589 Slog.i(TAG, " Keeping package " + packageName + " for user " 17590 + users[i]); 17591 } 17592 break; 17593 } 17594 } 17595 } 17596 if (!keep) { 17597 if (DEBUG_CLEAN_APKS) { 17598 Slog.i(TAG, " Removing package " + packageName); 17599 } 17600 mHandler.post(new Runnable() { 17601 public void run() { 17602 deletePackageX(packageName, userHandle, 0); 17603 } //end run 17604 }); 17605 } 17606 } 17607 } 17608 17609 /** Called by UserManagerService */ 17610 void createNewUser(int userHandle) { 17611 synchronized (mInstallLock) { 17612 try { 17613 mInstaller.createUserConfig(userHandle); 17614 } catch (InstallerException e) { 17615 Slog.w(TAG, "Failed to create user config", e); 17616 } 17617 mSettings.createNewUserLI(this, mInstaller, userHandle); 17618 } 17619 synchronized (mPackages) { 17620 applyFactoryDefaultBrowserLPw(userHandle); 17621 primeDomainVerificationsLPw(userHandle); 17622 } 17623 } 17624 17625 void newUserCreated(final int userHandle) { 17626 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 17627 // If permission review for legacy apps is required, we represent 17628 // dagerous permissions for such apps as always granted runtime 17629 // permissions to keep per user flag state whether review is needed. 17630 // Hence, if a new user is added we have to propagate dangerous 17631 // permission grants for these legacy apps. 17632 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 17633 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 17634 | UPDATE_PERMISSIONS_REPLACE_ALL); 17635 } 17636 } 17637 17638 @Override 17639 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 17640 mContext.enforceCallingOrSelfPermission( 17641 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 17642 "Only package verification agents can read the verifier device identity"); 17643 17644 synchronized (mPackages) { 17645 return mSettings.getVerifierDeviceIdentityLPw(); 17646 } 17647 } 17648 17649 @Override 17650 public void setPermissionEnforced(String permission, boolean enforced) { 17651 // TODO: Now that we no longer change GID for storage, this should to away. 17652 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 17653 "setPermissionEnforced"); 17654 if (READ_EXTERNAL_STORAGE.equals(permission)) { 17655 synchronized (mPackages) { 17656 if (mSettings.mReadExternalStorageEnforced == null 17657 || mSettings.mReadExternalStorageEnforced != enforced) { 17658 mSettings.mReadExternalStorageEnforced = enforced; 17659 mSettings.writeLPr(); 17660 } 17661 } 17662 // kill any non-foreground processes so we restart them and 17663 // grant/revoke the GID. 17664 final IActivityManager am = ActivityManagerNative.getDefault(); 17665 if (am != null) { 17666 final long token = Binder.clearCallingIdentity(); 17667 try { 17668 am.killProcessesBelowForeground("setPermissionEnforcement"); 17669 } catch (RemoteException e) { 17670 } finally { 17671 Binder.restoreCallingIdentity(token); 17672 } 17673 } 17674 } else { 17675 throw new IllegalArgumentException("No selective enforcement for " + permission); 17676 } 17677 } 17678 17679 @Override 17680 @Deprecated 17681 public boolean isPermissionEnforced(String permission) { 17682 return true; 17683 } 17684 17685 @Override 17686 public boolean isStorageLow() { 17687 final long token = Binder.clearCallingIdentity(); 17688 try { 17689 final DeviceStorageMonitorInternal 17690 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 17691 if (dsm != null) { 17692 return dsm.isMemoryLow(); 17693 } else { 17694 return false; 17695 } 17696 } finally { 17697 Binder.restoreCallingIdentity(token); 17698 } 17699 } 17700 17701 @Override 17702 public IPackageInstaller getPackageInstaller() { 17703 return mInstallerService; 17704 } 17705 17706 private boolean userNeedsBadging(int userId) { 17707 int index = mUserNeedsBadging.indexOfKey(userId); 17708 if (index < 0) { 17709 final UserInfo userInfo; 17710 final long token = Binder.clearCallingIdentity(); 17711 try { 17712 userInfo = sUserManager.getUserInfo(userId); 17713 } finally { 17714 Binder.restoreCallingIdentity(token); 17715 } 17716 final boolean b; 17717 if (userInfo != null && userInfo.isManagedProfile()) { 17718 b = true; 17719 } else { 17720 b = false; 17721 } 17722 mUserNeedsBadging.put(userId, b); 17723 return b; 17724 } 17725 return mUserNeedsBadging.valueAt(index); 17726 } 17727 17728 @Override 17729 public KeySet getKeySetByAlias(String packageName, String alias) { 17730 if (packageName == null || alias == null) { 17731 return null; 17732 } 17733 synchronized(mPackages) { 17734 final PackageParser.Package pkg = mPackages.get(packageName); 17735 if (pkg == null) { 17736 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17737 throw new IllegalArgumentException("Unknown package: " + packageName); 17738 } 17739 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17740 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 17741 } 17742 } 17743 17744 @Override 17745 public KeySet getSigningKeySet(String packageName) { 17746 if (packageName == null) { 17747 return null; 17748 } 17749 synchronized(mPackages) { 17750 final PackageParser.Package pkg = mPackages.get(packageName); 17751 if (pkg == null) { 17752 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17753 throw new IllegalArgumentException("Unknown package: " + packageName); 17754 } 17755 if (pkg.applicationInfo.uid != Binder.getCallingUid() 17756 && Process.SYSTEM_UID != Binder.getCallingUid()) { 17757 throw new SecurityException("May not access signing KeySet of other apps."); 17758 } 17759 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17760 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 17761 } 17762 } 17763 17764 @Override 17765 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 17766 if (packageName == null || ks == null) { 17767 return false; 17768 } 17769 synchronized(mPackages) { 17770 final PackageParser.Package pkg = mPackages.get(packageName); 17771 if (pkg == null) { 17772 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17773 throw new IllegalArgumentException("Unknown package: " + packageName); 17774 } 17775 IBinder ksh = ks.getToken(); 17776 if (ksh instanceof KeySetHandle) { 17777 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17778 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 17779 } 17780 return false; 17781 } 17782 } 17783 17784 @Override 17785 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 17786 if (packageName == null || ks == null) { 17787 return false; 17788 } 17789 synchronized(mPackages) { 17790 final PackageParser.Package pkg = mPackages.get(packageName); 17791 if (pkg == null) { 17792 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17793 throw new IllegalArgumentException("Unknown package: " + packageName); 17794 } 17795 IBinder ksh = ks.getToken(); 17796 if (ksh instanceof KeySetHandle) { 17797 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17798 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 17799 } 17800 return false; 17801 } 17802 } 17803 17804 private void deletePackageIfUnusedLPr(final String packageName) { 17805 PackageSetting ps = mSettings.mPackages.get(packageName); 17806 if (ps == null) { 17807 return; 17808 } 17809 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 17810 // TODO Implement atomic delete if package is unused 17811 // It is currently possible that the package will be deleted even if it is installed 17812 // after this method returns. 17813 mHandler.post(new Runnable() { 17814 public void run() { 17815 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 17816 } 17817 }); 17818 } 17819 } 17820 17821 /** 17822 * Check and throw if the given before/after packages would be considered a 17823 * downgrade. 17824 */ 17825 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 17826 throws PackageManagerException { 17827 if (after.versionCode < before.mVersionCode) { 17828 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17829 "Update version code " + after.versionCode + " is older than current " 17830 + before.mVersionCode); 17831 } else if (after.versionCode == before.mVersionCode) { 17832 if (after.baseRevisionCode < before.baseRevisionCode) { 17833 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17834 "Update base revision code " + after.baseRevisionCode 17835 + " is older than current " + before.baseRevisionCode); 17836 } 17837 17838 if (!ArrayUtils.isEmpty(after.splitNames)) { 17839 for (int i = 0; i < after.splitNames.length; i++) { 17840 final String splitName = after.splitNames[i]; 17841 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 17842 if (j != -1) { 17843 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 17844 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17845 "Update split " + splitName + " revision code " 17846 + after.splitRevisionCodes[i] + " is older than current " 17847 + before.splitRevisionCodes[j]); 17848 } 17849 } 17850 } 17851 } 17852 } 17853 } 17854 17855 private static class MoveCallbacks extends Handler { 17856 private static final int MSG_CREATED = 1; 17857 private static final int MSG_STATUS_CHANGED = 2; 17858 17859 private final RemoteCallbackList<IPackageMoveObserver> 17860 mCallbacks = new RemoteCallbackList<>(); 17861 17862 private final SparseIntArray mLastStatus = new SparseIntArray(); 17863 17864 public MoveCallbacks(Looper looper) { 17865 super(looper); 17866 } 17867 17868 public void register(IPackageMoveObserver callback) { 17869 mCallbacks.register(callback); 17870 } 17871 17872 public void unregister(IPackageMoveObserver callback) { 17873 mCallbacks.unregister(callback); 17874 } 17875 17876 @Override 17877 public void handleMessage(Message msg) { 17878 final SomeArgs args = (SomeArgs) msg.obj; 17879 final int n = mCallbacks.beginBroadcast(); 17880 for (int i = 0; i < n; i++) { 17881 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 17882 try { 17883 invokeCallback(callback, msg.what, args); 17884 } catch (RemoteException ignored) { 17885 } 17886 } 17887 mCallbacks.finishBroadcast(); 17888 args.recycle(); 17889 } 17890 17891 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 17892 throws RemoteException { 17893 switch (what) { 17894 case MSG_CREATED: { 17895 callback.onCreated(args.argi1, (Bundle) args.arg2); 17896 break; 17897 } 17898 case MSG_STATUS_CHANGED: { 17899 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 17900 break; 17901 } 17902 } 17903 } 17904 17905 private void notifyCreated(int moveId, Bundle extras) { 17906 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 17907 17908 final SomeArgs args = SomeArgs.obtain(); 17909 args.argi1 = moveId; 17910 args.arg2 = extras; 17911 obtainMessage(MSG_CREATED, args).sendToTarget(); 17912 } 17913 17914 private void notifyStatusChanged(int moveId, int status) { 17915 notifyStatusChanged(moveId, status, -1); 17916 } 17917 17918 private void notifyStatusChanged(int moveId, int status, long estMillis) { 17919 Slog.v(TAG, "Move " + moveId + " status " + status); 17920 17921 final SomeArgs args = SomeArgs.obtain(); 17922 args.argi1 = moveId; 17923 args.argi2 = status; 17924 args.arg3 = estMillis; 17925 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 17926 17927 synchronized (mLastStatus) { 17928 mLastStatus.put(moveId, status); 17929 } 17930 } 17931 } 17932 17933 private final static class OnPermissionChangeListeners extends Handler { 17934 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 17935 17936 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 17937 new RemoteCallbackList<>(); 17938 17939 public OnPermissionChangeListeners(Looper looper) { 17940 super(looper); 17941 } 17942 17943 @Override 17944 public void handleMessage(Message msg) { 17945 switch (msg.what) { 17946 case MSG_ON_PERMISSIONS_CHANGED: { 17947 final int uid = msg.arg1; 17948 handleOnPermissionsChanged(uid); 17949 } break; 17950 } 17951 } 17952 17953 public void addListenerLocked(IOnPermissionsChangeListener listener) { 17954 mPermissionListeners.register(listener); 17955 17956 } 17957 17958 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 17959 mPermissionListeners.unregister(listener); 17960 } 17961 17962 public void onPermissionsChanged(int uid) { 17963 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 17964 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 17965 } 17966 } 17967 17968 private void handleOnPermissionsChanged(int uid) { 17969 final int count = mPermissionListeners.beginBroadcast(); 17970 try { 17971 for (int i = 0; i < count; i++) { 17972 IOnPermissionsChangeListener callback = mPermissionListeners 17973 .getBroadcastItem(i); 17974 try { 17975 callback.onPermissionsChanged(uid); 17976 } catch (RemoteException e) { 17977 Log.e(TAG, "Permission listener is dead", e); 17978 } 17979 } 17980 } finally { 17981 mPermissionListeners.finishBroadcast(); 17982 } 17983 } 17984 } 17985 17986 private class PackageManagerInternalImpl extends PackageManagerInternal { 17987 @Override 17988 public void setLocationPackagesProvider(PackagesProvider provider) { 17989 synchronized (mPackages) { 17990 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 17991 } 17992 } 17993 17994 @Override 17995 public void setImePackagesProvider(PackagesProvider provider) { 17996 synchronized (mPackages) { 17997 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 17998 } 17999 } 18000 18001 @Override 18002 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 18003 synchronized (mPackages) { 18004 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 18005 } 18006 } 18007 18008 @Override 18009 public void setSmsAppPackagesProvider(PackagesProvider provider) { 18010 synchronized (mPackages) { 18011 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 18012 } 18013 } 18014 18015 @Override 18016 public void setDialerAppPackagesProvider(PackagesProvider provider) { 18017 synchronized (mPackages) { 18018 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 18019 } 18020 } 18021 18022 @Override 18023 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 18024 synchronized (mPackages) { 18025 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 18026 } 18027 } 18028 18029 @Override 18030 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 18031 synchronized (mPackages) { 18032 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 18033 } 18034 } 18035 18036 @Override 18037 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 18038 synchronized (mPackages) { 18039 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 18040 packageName, userId); 18041 } 18042 } 18043 18044 @Override 18045 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 18046 synchronized (mPackages) { 18047 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 18048 packageName, userId); 18049 } 18050 } 18051 18052 @Override 18053 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 18054 synchronized (mPackages) { 18055 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 18056 packageName, userId); 18057 } 18058 } 18059 18060 @Override 18061 public void setKeepUninstalledPackages(final List<String> packageList) { 18062 Preconditions.checkNotNull(packageList); 18063 List<String> removedFromList = null; 18064 synchronized (mPackages) { 18065 if (mKeepUninstalledPackages != null) { 18066 final int packagesCount = mKeepUninstalledPackages.size(); 18067 for (int i = 0; i < packagesCount; i++) { 18068 String oldPackage = mKeepUninstalledPackages.get(i); 18069 if (packageList != null && packageList.contains(oldPackage)) { 18070 continue; 18071 } 18072 if (removedFromList == null) { 18073 removedFromList = new ArrayList<>(); 18074 } 18075 removedFromList.add(oldPackage); 18076 } 18077 } 18078 mKeepUninstalledPackages = new ArrayList<>(packageList); 18079 if (removedFromList != null) { 18080 final int removedCount = removedFromList.size(); 18081 for (int i = 0; i < removedCount; i++) { 18082 deletePackageIfUnusedLPr(removedFromList.get(i)); 18083 } 18084 } 18085 } 18086 } 18087 18088 @Override 18089 public boolean isPermissionsReviewRequired(String packageName, int userId) { 18090 synchronized (mPackages) { 18091 // If we do not support permission review, done. 18092 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 18093 return false; 18094 } 18095 18096 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 18097 if (packageSetting == null) { 18098 return false; 18099 } 18100 18101 // Permission review applies only to apps not supporting the new permission model. 18102 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 18103 return false; 18104 } 18105 18106 // Legacy apps have the permission and get user consent on launch. 18107 PermissionsState permissionsState = packageSetting.getPermissionsState(); 18108 return permissionsState.isPermissionReviewRequired(userId); 18109 } 18110 } 18111 } 18112 18113 @Override 18114 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 18115 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 18116 synchronized (mPackages) { 18117 final long identity = Binder.clearCallingIdentity(); 18118 try { 18119 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 18120 packageNames, userId); 18121 } finally { 18122 Binder.restoreCallingIdentity(identity); 18123 } 18124 } 18125 } 18126 18127 private static void enforceSystemOrPhoneCaller(String tag) { 18128 int callingUid = Binder.getCallingUid(); 18129 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 18130 throw new SecurityException( 18131 "Cannot call " + tag + " from UID " + callingUid); 18132 } 18133 } 18134 18135 boolean isHistoricalPackageUsageAvailable() { 18136 return mPackageUsage.isHistoricalPackageUsageAvailable(); 18137 } 18138} 18139