PackageManagerService.java revision eb84b1843a3f6805c6109c1d9d023550229a3fc5
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.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 65import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 67import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 68import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 69import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 70import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 71import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 72import static android.content.pm.PackageManager.PERMISSION_DENIED; 73import static android.content.pm.PackageManager.PERMISSION_GRANTED; 74import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 75import static android.content.pm.PackageParser.isApkFile; 76import static android.os.Process.PACKAGE_INFO_GID; 77import static android.os.Process.SYSTEM_UID; 78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 79import static android.system.OsConstants.O_CREAT; 80import static android.system.OsConstants.O_RDWR; 81 82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 86import static com.android.internal.util.ArrayUtils.appendInt; 87import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 93import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 94import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 95import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 96 97import android.Manifest; 98import android.annotation.NonNull; 99import android.annotation.Nullable; 100import android.app.ActivityManager; 101import android.app.ActivityManagerNative; 102import android.app.IActivityManager; 103import android.app.admin.IDevicePolicyManager; 104import android.app.backup.IBackupManager; 105import android.content.BroadcastReceiver; 106import android.content.ComponentName; 107import android.content.Context; 108import android.content.IIntentReceiver; 109import android.content.Intent; 110import android.content.IntentFilter; 111import android.content.IntentSender; 112import android.content.IntentSender.SendIntentException; 113import android.content.ServiceConnection; 114import android.content.pm.ActivityInfo; 115import android.content.pm.ApplicationInfo; 116import android.content.pm.AppsQueryHelper; 117import android.content.pm.ComponentInfo; 118import android.content.pm.EphemeralApplicationInfo; 119import android.content.pm.EphemeralResolveInfo; 120import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 121import android.content.pm.FeatureInfo; 122import android.content.pm.IOnPermissionsChangeListener; 123import android.content.pm.IPackageDataObserver; 124import android.content.pm.IPackageDeleteObserver; 125import android.content.pm.IPackageDeleteObserver2; 126import android.content.pm.IPackageInstallObserver2; 127import android.content.pm.IPackageInstaller; 128import android.content.pm.IPackageManager; 129import android.content.pm.IPackageMoveObserver; 130import android.content.pm.IPackageStatsObserver; 131import android.content.pm.InstrumentationInfo; 132import android.content.pm.IntentFilterVerificationInfo; 133import android.content.pm.KeySet; 134import android.content.pm.PackageCleanItem; 135import android.content.pm.PackageInfo; 136import android.content.pm.PackageInfoLite; 137import android.content.pm.PackageInstaller; 138import android.content.pm.PackageManager; 139import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 140import android.content.pm.PackageManagerInternal; 141import android.content.pm.PackageParser; 142import android.content.pm.PackageParser.ActivityIntentInfo; 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.PrintWriter; 267import java.nio.charset.StandardCharsets; 268import java.security.MessageDigest; 269import java.security.NoSuchAlgorithmException; 270import java.security.PublicKey; 271import java.security.cert.CertificateEncodingException; 272import java.security.cert.CertificateException; 273import java.text.SimpleDateFormat; 274import java.util.ArrayList; 275import java.util.Arrays; 276import java.util.Collection; 277import java.util.Collections; 278import java.util.Comparator; 279import java.util.Date; 280import java.util.HashSet; 281import java.util.Iterator; 282import java.util.List; 283import java.util.Map; 284import java.util.Objects; 285import java.util.Set; 286import java.util.concurrent.CountDownLatch; 287import java.util.concurrent.TimeUnit; 288import java.util.concurrent.atomic.AtomicBoolean; 289import java.util.concurrent.atomic.AtomicInteger; 290import java.util.concurrent.atomic.AtomicLong; 291 292/** 293 * Keep track of all those .apks everywhere. 294 * 295 * This is very central to the platform's security; please run the unit 296 * tests whenever making modifications here: 297 * 298runtest -c android.content.pm.PackageManagerTests frameworks-core 299 * 300 * {@hide} 301 */ 302public class PackageManagerService extends IPackageManager.Stub { 303 static final String TAG = "PackageManager"; 304 static final boolean DEBUG_SETTINGS = false; 305 static final boolean DEBUG_PREFERRED = false; 306 static final boolean DEBUG_UPGRADE = false; 307 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 308 private static final boolean DEBUG_BACKUP = false; 309 private static final boolean DEBUG_INSTALL = false; 310 private static final boolean DEBUG_REMOVE = false; 311 private static final boolean DEBUG_BROADCASTS = false; 312 private static final boolean DEBUG_SHOW_INFO = false; 313 private static final boolean DEBUG_PACKAGE_INFO = false; 314 private static final boolean DEBUG_INTENT_MATCHING = false; 315 private static final boolean DEBUG_PACKAGE_SCANNING = false; 316 private static final boolean DEBUG_VERIFY = false; 317 318 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 319 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 320 // user, but by default initialize to this. 321 static final boolean DEBUG_DEXOPT = false; 322 323 private static final boolean DEBUG_ABI_SELECTION = false; 324 private static final boolean DEBUG_EPHEMERAL = false; 325 private static final boolean DEBUG_TRIAGED_MISSING = false; 326 private static final boolean DEBUG_APP_DATA = false; 327 328 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 329 330 private static final boolean DISABLE_EPHEMERAL_APPS = true; 331 332 private static final int RADIO_UID = Process.PHONE_UID; 333 private static final int LOG_UID = Process.LOG_UID; 334 private static final int NFC_UID = Process.NFC_UID; 335 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 336 private static final int SHELL_UID = Process.SHELL_UID; 337 338 // Cap the size of permission trees that 3rd party apps can define 339 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 340 341 // Suffix used during package installation when copying/moving 342 // package apks to install directory. 343 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 344 345 static final int SCAN_NO_DEX = 1<<1; 346 static final int SCAN_FORCE_DEX = 1<<2; 347 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 348 static final int SCAN_NEW_INSTALL = 1<<4; 349 static final int SCAN_NO_PATHS = 1<<5; 350 static final int SCAN_UPDATE_TIME = 1<<6; 351 static final int SCAN_DEFER_DEX = 1<<7; 352 static final int SCAN_BOOTING = 1<<8; 353 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 354 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 355 static final int SCAN_REPLACING = 1<<11; 356 static final int SCAN_REQUIRE_KNOWN = 1<<12; 357 static final int SCAN_MOVE = 1<<13; 358 static final int SCAN_INITIAL = 1<<14; 359 static final int SCAN_CHECK_ONLY = 1<<15; 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 1422 if (data != null) { 1423 InstallArgs args = data.args; 1424 PackageInstalledInfo parentRes = data.res; 1425 1426 final boolean grantPermissions = (args.installFlags 1427 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1428 final String[] grantedPermissions = args.installGrantPermissions; 1429 1430 // Handle the parent package 1431 handlePackagePostInstall(parentRes, grantPermissions, grantedPermissions, 1432 args.observer); 1433 1434 // Handle the child packages 1435 final int childCount = (parentRes.addedChildPackages != null) 1436 ? parentRes.addedChildPackages.size() : 0; 1437 for (int i = 0; i < childCount; i++) { 1438 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1439 handlePackagePostInstall(childRes, grantPermissions, grantedPermissions, 1440 args.observer); 1441 } 1442 1443 // Log tracing if needed 1444 if (args.traceMethod != null) { 1445 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1446 args.traceCookie); 1447 } 1448 } else { 1449 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1450 } 1451 1452 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1453 } break; 1454 case UPDATED_MEDIA_STATUS: { 1455 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1456 boolean reportStatus = msg.arg1 == 1; 1457 boolean doGc = msg.arg2 == 1; 1458 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1459 if (doGc) { 1460 // Force a gc to clear up stale containers. 1461 Runtime.getRuntime().gc(); 1462 } 1463 if (msg.obj != null) { 1464 @SuppressWarnings("unchecked") 1465 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1466 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1467 // Unload containers 1468 unloadAllContainers(args); 1469 } 1470 if (reportStatus) { 1471 try { 1472 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1473 PackageHelper.getMountService().finishMediaUpdate(); 1474 } catch (RemoteException e) { 1475 Log.e(TAG, "MountService not running?"); 1476 } 1477 } 1478 } break; 1479 case WRITE_SETTINGS: { 1480 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1481 synchronized (mPackages) { 1482 removeMessages(WRITE_SETTINGS); 1483 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1484 mSettings.writeLPr(); 1485 mDirtyUsers.clear(); 1486 } 1487 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1488 } break; 1489 case WRITE_PACKAGE_RESTRICTIONS: { 1490 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1491 synchronized (mPackages) { 1492 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1493 for (int userId : mDirtyUsers) { 1494 mSettings.writePackageRestrictionsLPr(userId); 1495 } 1496 mDirtyUsers.clear(); 1497 } 1498 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1499 } break; 1500 case CHECK_PENDING_VERIFICATION: { 1501 final int verificationId = msg.arg1; 1502 final PackageVerificationState state = mPendingVerification.get(verificationId); 1503 1504 if ((state != null) && !state.timeoutExtended()) { 1505 final InstallArgs args = state.getInstallArgs(); 1506 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1507 1508 Slog.i(TAG, "Verification timed out for " + originUri); 1509 mPendingVerification.remove(verificationId); 1510 1511 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1512 1513 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1514 Slog.i(TAG, "Continuing with installation of " + originUri); 1515 state.setVerifierResponse(Binder.getCallingUid(), 1516 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1517 broadcastPackageVerified(verificationId, originUri, 1518 PackageManager.VERIFICATION_ALLOW, 1519 state.getInstallArgs().getUser()); 1520 try { 1521 ret = args.copyApk(mContainerService, true); 1522 } catch (RemoteException e) { 1523 Slog.e(TAG, "Could not contact the ContainerService"); 1524 } 1525 } else { 1526 broadcastPackageVerified(verificationId, originUri, 1527 PackageManager.VERIFICATION_REJECT, 1528 state.getInstallArgs().getUser()); 1529 } 1530 1531 Trace.asyncTraceEnd( 1532 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1533 1534 processPendingInstall(args, ret); 1535 mHandler.sendEmptyMessage(MCS_UNBIND); 1536 } 1537 break; 1538 } 1539 case PACKAGE_VERIFIED: { 1540 final int verificationId = msg.arg1; 1541 1542 final PackageVerificationState state = mPendingVerification.get(verificationId); 1543 if (state == null) { 1544 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1545 break; 1546 } 1547 1548 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1549 1550 state.setVerifierResponse(response.callerUid, response.code); 1551 1552 if (state.isVerificationComplete()) { 1553 mPendingVerification.remove(verificationId); 1554 1555 final InstallArgs args = state.getInstallArgs(); 1556 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1557 1558 int ret; 1559 if (state.isInstallAllowed()) { 1560 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1561 broadcastPackageVerified(verificationId, originUri, 1562 response.code, state.getInstallArgs().getUser()); 1563 try { 1564 ret = args.copyApk(mContainerService, true); 1565 } catch (RemoteException e) { 1566 Slog.e(TAG, "Could not contact the ContainerService"); 1567 } 1568 } else { 1569 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1570 } 1571 1572 Trace.asyncTraceEnd( 1573 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1574 1575 processPendingInstall(args, ret); 1576 mHandler.sendEmptyMessage(MCS_UNBIND); 1577 } 1578 1579 break; 1580 } 1581 case START_INTENT_FILTER_VERIFICATIONS: { 1582 IFVerificationParams params = (IFVerificationParams) msg.obj; 1583 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1584 params.replacing, params.pkg); 1585 break; 1586 } 1587 case INTENT_FILTER_VERIFIED: { 1588 final int verificationId = msg.arg1; 1589 1590 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1591 verificationId); 1592 if (state == null) { 1593 Slog.w(TAG, "Invalid IntentFilter verification token " 1594 + verificationId + " received"); 1595 break; 1596 } 1597 1598 final int userId = state.getUserId(); 1599 1600 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1601 "Processing IntentFilter verification with token:" 1602 + verificationId + " and userId:" + userId); 1603 1604 final IntentFilterVerificationResponse response = 1605 (IntentFilterVerificationResponse) msg.obj; 1606 1607 state.setVerifierResponse(response.callerUid, response.code); 1608 1609 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1610 "IntentFilter verification with token:" + verificationId 1611 + " and userId:" + userId 1612 + " is settings verifier response with response code:" 1613 + response.code); 1614 1615 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1616 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1617 + response.getFailedDomainsString()); 1618 } 1619 1620 if (state.isVerificationComplete()) { 1621 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1622 } else { 1623 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1624 "IntentFilter verification with token:" + verificationId 1625 + " was not said to be complete"); 1626 } 1627 1628 break; 1629 } 1630 } 1631 } 1632 } 1633 1634 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1635 String[] grantedPermissions, IPackageInstallObserver2 installObserver) { 1636 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1637 // Send the removed broadcasts 1638 if (res.removedInfo != null) { 1639 res.removedInfo.sendPackageRemovedBroadcasts(); 1640 } 1641 1642 // Now that we successfully installed the package, grant runtime 1643 // permissions if requested before broadcasting the install. 1644 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1645 >= Build.VERSION_CODES.M) { 1646 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1647 } 1648 1649 final boolean update = res.removedInfo != null 1650 && res.removedInfo.removedPackage != null; 1651 1652 // If this is the first time we have child packages for a disabled privileged 1653 // app that had no children, we grant requested runtime permissions to the new 1654 // children if the parent on the system image had them already granted. 1655 if (res.pkg.parentPackage != null) { 1656 synchronized (mPackages) { 1657 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1658 } 1659 } 1660 1661 synchronized (mPackages) { 1662 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1663 } 1664 1665 final String packageName = res.pkg.applicationInfo.packageName; 1666 Bundle extras = new Bundle(1); 1667 extras.putInt(Intent.EXTRA_UID, res.uid); 1668 1669 // Determine the set of users who are adding this package for 1670 // the first time vs. those who are seeing an update. 1671 int[] firstUsers = EMPTY_INT_ARRAY; 1672 int[] updateUsers = EMPTY_INT_ARRAY; 1673 if (res.origUsers == null || res.origUsers.length == 0) { 1674 firstUsers = res.newUsers; 1675 } else { 1676 for (int newUser : res.newUsers) { 1677 boolean isNew = true; 1678 for (int origUser : res.origUsers) { 1679 if (origUser == newUser) { 1680 isNew = false; 1681 break; 1682 } 1683 } 1684 if (isNew) { 1685 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1686 } else { 1687 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1688 } 1689 } 1690 } 1691 1692 // Send installed broadcasts if the install/update is not ephemeral 1693 if (!isEphemeral(res.pkg)) { 1694 // Send added for users that see the package for the first time 1695 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1696 extras, 0 /*flags*/, null /*targetPackage*/, 1697 null /*finishedReceiver*/, firstUsers); 1698 1699 // Send added for users that don't see the package for the first time 1700 if (update) { 1701 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1702 } 1703 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1704 extras, 0 /*flags*/, null /*targetPackage*/, 1705 null /*finishedReceiver*/, updateUsers); 1706 1707 // Send replaced for users that don't see the package for the first time 1708 if (update) { 1709 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1710 packageName, extras, 0 /*flags*/, 1711 null /*targetPackage*/, null /*finishedReceiver*/, 1712 updateUsers); 1713 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1714 null /*package*/, null /*extras*/, 0 /*flags*/, 1715 packageName /*targetPackage*/, 1716 null /*finishedReceiver*/, updateUsers); 1717 } 1718 1719 // Send broadcast package appeared if forward locked/external for all users 1720 // treat asec-hosted packages like removable media on upgrade 1721 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1722 if (DEBUG_INSTALL) { 1723 Slog.i(TAG, "upgrading pkg " + res.pkg 1724 + " is ASEC-hosted -> AVAILABLE"); 1725 } 1726 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1727 ArrayList<String> pkgList = new ArrayList<>(1); 1728 pkgList.add(packageName); 1729 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1730 } 1731 } 1732 1733 // Work that needs to happen on first install within each user 1734 if (firstUsers != null && firstUsers.length > 0) { 1735 synchronized (mPackages) { 1736 for (int userId : firstUsers) { 1737 // If this app is a browser and it's newly-installed for some 1738 // users, clear any default-browser state in those users. The 1739 // app's nature doesn't depend on the user, so we can just check 1740 // its browser nature in any user and generalize. 1741 if (packageIsBrowser(packageName, userId)) { 1742 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1743 } 1744 1745 // We may also need to apply pending (restored) runtime 1746 // permission grants within these users. 1747 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1748 } 1749 } 1750 } 1751 1752 // Log current value of "unknown sources" setting 1753 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1754 getUnknownSourcesSettings()); 1755 1756 // Force a gc to clear up things 1757 Runtime.getRuntime().gc(); 1758 1759 // Remove the replaced package's older resources safely now 1760 // We delete after a gc for applications on sdcard. 1761 if (res.removedInfo != null && res.removedInfo.args != null) { 1762 synchronized (mInstallLock) { 1763 res.removedInfo.args.doPostDeleteLI(true); 1764 } 1765 } 1766 } 1767 1768 // If someone is watching installs - notify them 1769 if (installObserver != null) { 1770 try { 1771 Bundle extras = extrasForInstallResult(res); 1772 installObserver.onPackageInstalled(res.name, res.returnCode, 1773 res.returnMsg, extras); 1774 } catch (RemoteException e) { 1775 Slog.i(TAG, "Observer no longer exists."); 1776 } 1777 } 1778 } 1779 1780 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1781 PackageParser.Package pkg) { 1782 if (pkg.parentPackage == null) { 1783 return; 1784 } 1785 if (pkg.requestedPermissions == null) { 1786 return; 1787 } 1788 final PackageSetting disabledSysParentPs = mSettings 1789 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1790 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1791 || !disabledSysParentPs.isPrivileged() 1792 || (disabledSysParentPs.childPackageNames != null 1793 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1794 return; 1795 } 1796 final int[] allUserIds = sUserManager.getUserIds(); 1797 final int permCount = pkg.requestedPermissions.size(); 1798 for (int i = 0; i < permCount; i++) { 1799 String permission = pkg.requestedPermissions.get(i); 1800 BasePermission bp = mSettings.mPermissions.get(permission); 1801 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1802 continue; 1803 } 1804 for (int userId : allUserIds) { 1805 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1806 permission, userId)) { 1807 grantRuntimePermission(pkg.packageName, permission, userId); 1808 } 1809 } 1810 } 1811 } 1812 1813 private StorageEventListener mStorageListener = new StorageEventListener() { 1814 @Override 1815 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1816 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1817 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1818 final String volumeUuid = vol.getFsUuid(); 1819 1820 // Clean up any users or apps that were removed or recreated 1821 // while this volume was missing 1822 reconcileUsers(volumeUuid); 1823 reconcileApps(volumeUuid); 1824 1825 // Clean up any install sessions that expired or were 1826 // cancelled while this volume was missing 1827 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1828 1829 loadPrivatePackages(vol); 1830 1831 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1832 unloadPrivatePackages(vol); 1833 } 1834 } 1835 1836 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1837 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1838 updateExternalMediaStatus(true, false); 1839 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1840 updateExternalMediaStatus(false, false); 1841 } 1842 } 1843 } 1844 1845 @Override 1846 public void onVolumeForgotten(String fsUuid) { 1847 if (TextUtils.isEmpty(fsUuid)) { 1848 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1849 return; 1850 } 1851 1852 // Remove any apps installed on the forgotten volume 1853 synchronized (mPackages) { 1854 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1855 for (PackageSetting ps : packages) { 1856 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1857 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1858 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1859 } 1860 1861 mSettings.onVolumeForgotten(fsUuid); 1862 mSettings.writeLPr(); 1863 } 1864 } 1865 }; 1866 1867 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1868 String[] grantedPermissions) { 1869 for (int userId : userIds) { 1870 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1871 } 1872 1873 // We could have touched GID membership, so flush out packages.list 1874 synchronized (mPackages) { 1875 mSettings.writePackageListLPr(); 1876 } 1877 } 1878 1879 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1880 String[] grantedPermissions) { 1881 SettingBase sb = (SettingBase) pkg.mExtras; 1882 if (sb == null) { 1883 return; 1884 } 1885 1886 PermissionsState permissionsState = sb.getPermissionsState(); 1887 1888 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1889 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1890 1891 synchronized (mPackages) { 1892 for (String permission : pkg.requestedPermissions) { 1893 BasePermission bp = mSettings.mPermissions.get(permission); 1894 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1895 && (grantedPermissions == null 1896 || ArrayUtils.contains(grantedPermissions, permission))) { 1897 final int flags = permissionsState.getPermissionFlags(permission, userId); 1898 // Installer cannot change immutable permissions. 1899 if ((flags & immutableFlags) == 0) { 1900 grantRuntimePermission(pkg.packageName, permission, userId); 1901 } 1902 } 1903 } 1904 } 1905 } 1906 1907 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1908 Bundle extras = null; 1909 switch (res.returnCode) { 1910 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1911 extras = new Bundle(); 1912 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1913 res.origPermission); 1914 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1915 res.origPackage); 1916 break; 1917 } 1918 case PackageManager.INSTALL_SUCCEEDED: { 1919 extras = new Bundle(); 1920 extras.putBoolean(Intent.EXTRA_REPLACING, 1921 res.removedInfo != null && res.removedInfo.removedPackage != null); 1922 break; 1923 } 1924 } 1925 return extras; 1926 } 1927 1928 void scheduleWriteSettingsLocked() { 1929 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1930 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1931 } 1932 } 1933 1934 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1935 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1936 scheduleWritePackageRestrictionsLocked(userId); 1937 } 1938 1939 void scheduleWritePackageRestrictionsLocked(int userId) { 1940 final int[] userIds = (userId == UserHandle.USER_ALL) 1941 ? sUserManager.getUserIds() : new int[]{userId}; 1942 for (int nextUserId : userIds) { 1943 if (!sUserManager.exists(nextUserId)) return; 1944 mDirtyUsers.add(nextUserId); 1945 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1946 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1947 } 1948 } 1949 } 1950 1951 public static PackageManagerService main(Context context, Installer installer, 1952 boolean factoryTest, boolean onlyCore) { 1953 PackageManagerService m = new PackageManagerService(context, installer, 1954 factoryTest, onlyCore); 1955 m.enableSystemUserPackages(); 1956 ServiceManager.addService("package", m); 1957 return m; 1958 } 1959 1960 private void enableSystemUserPackages() { 1961 if (!UserManager.isSplitSystemUser()) { 1962 return; 1963 } 1964 // For system user, enable apps based on the following conditions: 1965 // - app is whitelisted or belong to one of these groups: 1966 // -- system app which has no launcher icons 1967 // -- system app which has INTERACT_ACROSS_USERS permission 1968 // -- system IME app 1969 // - app is not in the blacklist 1970 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1971 Set<String> enableApps = new ArraySet<>(); 1972 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1973 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1974 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1975 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1976 enableApps.addAll(wlApps); 1977 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1978 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1979 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1980 enableApps.removeAll(blApps); 1981 Log.i(TAG, "Applications installed for system user: " + enableApps); 1982 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1983 UserHandle.SYSTEM); 1984 final int allAppsSize = allAps.size(); 1985 synchronized (mPackages) { 1986 for (int i = 0; i < allAppsSize; i++) { 1987 String pName = allAps.get(i); 1988 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1989 // Should not happen, but we shouldn't be failing if it does 1990 if (pkgSetting == null) { 1991 continue; 1992 } 1993 boolean install = enableApps.contains(pName); 1994 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 1995 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 1996 + " for system user"); 1997 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 1998 } 1999 } 2000 } 2001 } 2002 2003 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2004 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2005 Context.DISPLAY_SERVICE); 2006 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2007 } 2008 2009 public PackageManagerService(Context context, Installer installer, 2010 boolean factoryTest, boolean onlyCore) { 2011 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2012 SystemClock.uptimeMillis()); 2013 2014 if (mSdkVersion <= 0) { 2015 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2016 } 2017 2018 mContext = context; 2019 mFactoryTest = factoryTest; 2020 mOnlyCore = onlyCore; 2021 mMetrics = new DisplayMetrics(); 2022 mSettings = new Settings(mPackages); 2023 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2024 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2025 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2026 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2027 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2028 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2029 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2030 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2031 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2032 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2033 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2034 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2035 2036 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2037 if (separateProcesses != null && separateProcesses.length() > 0) { 2038 if ("*".equals(separateProcesses)) { 2039 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2040 mSeparateProcesses = null; 2041 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2042 } else { 2043 mDefParseFlags = 0; 2044 mSeparateProcesses = separateProcesses.split(","); 2045 Slog.w(TAG, "Running with debug.separate_processes: " 2046 + separateProcesses); 2047 } 2048 } else { 2049 mDefParseFlags = 0; 2050 mSeparateProcesses = null; 2051 } 2052 2053 mInstaller = installer; 2054 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2055 "*dexopt*"); 2056 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2057 2058 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2059 FgThread.get().getLooper()); 2060 2061 getDefaultDisplayMetrics(context, mMetrics); 2062 2063 SystemConfig systemConfig = SystemConfig.getInstance(); 2064 mGlobalGids = systemConfig.getGlobalGids(); 2065 mSystemPermissions = systemConfig.getSystemPermissions(); 2066 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2067 2068 synchronized (mInstallLock) { 2069 // writer 2070 synchronized (mPackages) { 2071 mHandlerThread = new ServiceThread(TAG, 2072 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2073 mHandlerThread.start(); 2074 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2075 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2076 2077 File dataDir = Environment.getDataDirectory(); 2078 mAppInstallDir = new File(dataDir, "app"); 2079 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2080 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2081 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2082 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2083 2084 sUserManager = new UserManagerService(context, this, mPackages); 2085 2086 // Propagate permission configuration in to package manager. 2087 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2088 = systemConfig.getPermissions(); 2089 for (int i=0; i<permConfig.size(); i++) { 2090 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2091 BasePermission bp = mSettings.mPermissions.get(perm.name); 2092 if (bp == null) { 2093 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2094 mSettings.mPermissions.put(perm.name, bp); 2095 } 2096 if (perm.gids != null) { 2097 bp.setGids(perm.gids, perm.perUser); 2098 } 2099 } 2100 2101 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2102 for (int i=0; i<libConfig.size(); i++) { 2103 mSharedLibraries.put(libConfig.keyAt(i), 2104 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2105 } 2106 2107 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2108 2109 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2110 2111 String customResolverActivity = Resources.getSystem().getString( 2112 R.string.config_customResolverActivity); 2113 if (TextUtils.isEmpty(customResolverActivity)) { 2114 customResolverActivity = null; 2115 } else { 2116 mCustomResolverComponentName = ComponentName.unflattenFromString( 2117 customResolverActivity); 2118 } 2119 2120 long startTime = SystemClock.uptimeMillis(); 2121 2122 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2123 startTime); 2124 2125 // Set flag to monitor and not change apk file paths when 2126 // scanning install directories. 2127 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2128 2129 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2130 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2131 2132 if (bootClassPath == null) { 2133 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2134 } 2135 2136 if (systemServerClassPath == null) { 2137 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2138 } 2139 2140 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2141 final String[] dexCodeInstructionSets = 2142 getDexCodeInstructionSets( 2143 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2144 2145 /** 2146 * Ensure all external libraries have had dexopt run on them. 2147 */ 2148 if (mSharedLibraries.size() > 0) { 2149 // NOTE: For now, we're compiling these system "shared libraries" 2150 // (and framework jars) into all available architectures. It's possible 2151 // to compile them only when we come across an app that uses them (there's 2152 // already logic for that in scanPackageLI) but that adds some complexity. 2153 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2154 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2155 final String lib = libEntry.path; 2156 if (lib == null) { 2157 continue; 2158 } 2159 2160 try { 2161 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2162 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2163 // Shared libraries do not have profiles so we perform a full 2164 // AOT compilation. 2165 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2166 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2167 StorageManager.UUID_PRIVATE_INTERNAL, 2168 false /*useProfiles*/); 2169 } 2170 } catch (FileNotFoundException e) { 2171 Slog.w(TAG, "Library not found: " + lib); 2172 } catch (IOException | InstallerException e) { 2173 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2174 + e.getMessage()); 2175 } 2176 } 2177 } 2178 } 2179 2180 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2181 2182 final VersionInfo ver = mSettings.getInternalVersion(); 2183 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2184 // when upgrading from pre-M, promote system app permissions from install to runtime 2185 mPromoteSystemApps = 2186 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2187 2188 // save off the names of pre-existing system packages prior to scanning; we don't 2189 // want to automatically grant runtime permissions for new system apps 2190 if (mPromoteSystemApps) { 2191 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2192 while (pkgSettingIter.hasNext()) { 2193 PackageSetting ps = pkgSettingIter.next(); 2194 if (isSystemApp(ps)) { 2195 mExistingSystemPackages.add(ps.name); 2196 } 2197 } 2198 } 2199 2200 // Collect vendor overlay packages. 2201 // (Do this before scanning any apps.) 2202 // For security and version matching reason, only consider 2203 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2204 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2205 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2206 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2207 2208 // Find base frameworks (resource packages without code). 2209 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2210 | PackageParser.PARSE_IS_SYSTEM_DIR 2211 | PackageParser.PARSE_IS_PRIVILEGED, 2212 scanFlags | SCAN_NO_DEX, 0); 2213 2214 // Collected privileged system packages. 2215 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2216 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2217 | PackageParser.PARSE_IS_SYSTEM_DIR 2218 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2219 2220 // Collect ordinary system packages. 2221 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2222 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2223 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2224 2225 // Collect all vendor packages. 2226 File vendorAppDir = new File("/vendor/app"); 2227 try { 2228 vendorAppDir = vendorAppDir.getCanonicalFile(); 2229 } catch (IOException e) { 2230 // failed to look up canonical path, continue with original one 2231 } 2232 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2233 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2234 2235 // Collect all OEM packages. 2236 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2237 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2238 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2239 2240 // Prune any system packages that no longer exist. 2241 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2242 if (!mOnlyCore) { 2243 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2244 while (psit.hasNext()) { 2245 PackageSetting ps = psit.next(); 2246 2247 /* 2248 * If this is not a system app, it can't be a 2249 * disable system app. 2250 */ 2251 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2252 continue; 2253 } 2254 2255 /* 2256 * If the package is scanned, it's not erased. 2257 */ 2258 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2259 if (scannedPkg != null) { 2260 /* 2261 * If the system app is both scanned and in the 2262 * disabled packages list, then it must have been 2263 * added via OTA. Remove it from the currently 2264 * scanned package so the previously user-installed 2265 * application can be scanned. 2266 */ 2267 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2268 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2269 + ps.name + "; removing system app. Last known codePath=" 2270 + ps.codePathString + ", installStatus=" + ps.installStatus 2271 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2272 + scannedPkg.mVersionCode); 2273 removePackageLI(scannedPkg, true); 2274 mExpectingBetter.put(ps.name, ps.codePath); 2275 } 2276 2277 continue; 2278 } 2279 2280 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2281 psit.remove(); 2282 logCriticalInfo(Log.WARN, "System package " + ps.name 2283 + " no longer exists; wiping its data"); 2284 removeDataDirsLI(null, ps.name); 2285 } else { 2286 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2287 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2288 possiblyDeletedUpdatedSystemApps.add(ps.name); 2289 } 2290 } 2291 } 2292 } 2293 2294 //look for any incomplete package installations 2295 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2296 //clean up list 2297 for(int i = 0; i < deletePkgsList.size(); i++) { 2298 //clean up here 2299 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2300 } 2301 //delete tmp files 2302 deleteTempPackageFiles(); 2303 2304 // Remove any shared userIDs that have no associated packages 2305 mSettings.pruneSharedUsersLPw(); 2306 2307 if (!mOnlyCore) { 2308 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2309 SystemClock.uptimeMillis()); 2310 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2311 2312 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2313 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2314 2315 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2316 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2317 2318 /** 2319 * Remove disable package settings for any updated system 2320 * apps that were removed via an OTA. If they're not a 2321 * previously-updated app, remove them completely. 2322 * Otherwise, just revoke their system-level permissions. 2323 */ 2324 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2325 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2326 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2327 2328 String msg; 2329 if (deletedPkg == null) { 2330 msg = "Updated system package " + deletedAppName 2331 + " no longer exists; wiping its data"; 2332 removeDataDirsLI(null, deletedAppName); 2333 } else { 2334 msg = "Updated system app + " + deletedAppName 2335 + " no longer present; removing system privileges for " 2336 + deletedAppName; 2337 2338 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2339 2340 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2341 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2342 } 2343 logCriticalInfo(Log.WARN, msg); 2344 } 2345 2346 /** 2347 * Make sure all system apps that we expected to appear on 2348 * the userdata partition actually showed up. If they never 2349 * appeared, crawl back and revive the system version. 2350 */ 2351 for (int i = 0; i < mExpectingBetter.size(); i++) { 2352 final String packageName = mExpectingBetter.keyAt(i); 2353 if (!mPackages.containsKey(packageName)) { 2354 final File scanFile = mExpectingBetter.valueAt(i); 2355 2356 logCriticalInfo(Log.WARN, "Expected better " + packageName 2357 + " but never showed up; reverting to system"); 2358 2359 final int reparseFlags; 2360 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2361 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2362 | PackageParser.PARSE_IS_SYSTEM_DIR 2363 | PackageParser.PARSE_IS_PRIVILEGED; 2364 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2365 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2366 | PackageParser.PARSE_IS_SYSTEM_DIR; 2367 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2368 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2369 | PackageParser.PARSE_IS_SYSTEM_DIR; 2370 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2371 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2372 | PackageParser.PARSE_IS_SYSTEM_DIR; 2373 } else { 2374 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2375 continue; 2376 } 2377 2378 mSettings.enableSystemPackageLPw(packageName); 2379 2380 try { 2381 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2382 } catch (PackageManagerException e) { 2383 Slog.e(TAG, "Failed to parse original system package: " 2384 + e.getMessage()); 2385 } 2386 } 2387 } 2388 } 2389 mExpectingBetter.clear(); 2390 2391 // Now that we know all of the shared libraries, update all clients to have 2392 // the correct library paths. 2393 updateAllSharedLibrariesLPw(); 2394 2395 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2396 // NOTE: We ignore potential failures here during a system scan (like 2397 // the rest of the commands above) because there's precious little we 2398 // can do about it. A settings error is reported, though. 2399 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2400 false /* boot complete */); 2401 } 2402 2403 // Now that we know all the packages we are keeping, 2404 // read and update their last usage times. 2405 mPackageUsage.readLP(); 2406 2407 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2408 SystemClock.uptimeMillis()); 2409 Slog.i(TAG, "Time to scan packages: " 2410 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2411 + " seconds"); 2412 2413 // If the platform SDK has changed since the last time we booted, 2414 // we need to re-grant app permission to catch any new ones that 2415 // appear. This is really a hack, and means that apps can in some 2416 // cases get permissions that the user didn't initially explicitly 2417 // allow... it would be nice to have some better way to handle 2418 // this situation. 2419 int updateFlags = UPDATE_PERMISSIONS_ALL; 2420 if (ver.sdkVersion != mSdkVersion) { 2421 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2422 + mSdkVersion + "; regranting permissions for internal storage"); 2423 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2424 } 2425 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2426 ver.sdkVersion = mSdkVersion; 2427 2428 // If this is the first boot or an update from pre-M, and it is a normal 2429 // boot, then we need to initialize the default preferred apps across 2430 // all defined users. 2431 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2432 for (UserInfo user : sUserManager.getUsers(true)) { 2433 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2434 applyFactoryDefaultBrowserLPw(user.id); 2435 primeDomainVerificationsLPw(user.id); 2436 } 2437 } 2438 2439 // Prepare storage for system user really early during boot, 2440 // since core system apps like SettingsProvider and SystemUI 2441 // can't wait for user to start 2442 final int storageFlags; 2443 if (StorageManager.isFileBasedEncryptionEnabled()) { 2444 storageFlags = StorageManager.FLAG_STORAGE_DE; 2445 } else { 2446 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2447 } 2448 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2449 storageFlags); 2450 2451 if (!StorageManager.isFileBasedEncryptionEnabled() 2452 && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) { 2453 // When upgrading a non-FBE device, we might need to shuffle 2454 // around the default storage location of system apps 2455 final List<UserInfo> users = sUserManager.getUsers(true); 2456 for (PackageSetting ps : mSettings.mPackages.values()) { 2457 if (ps.pkg == null || !ps.isSystem()) continue; 2458 final int storageTarget = ps.pkg.applicationInfo.isForceDeviceEncrypted() 2459 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 2460 for (UserInfo user : users) { 2461 if (ps.getInstalled(user.id)) { 2462 try { 2463 mInstaller.migrateAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2464 ps.name, user.id, storageTarget); 2465 } catch (InstallerException e) { 2466 logCriticalInfo(Log.WARN, 2467 "Failed to migrate " + ps.name + ": " + e.getMessage()); 2468 } 2469 // We may have just shuffled around app data 2470 // directories, so prepare it one more time 2471 prepareAppData(StorageManager.UUID_PRIVATE_INTERNAL, user.id, 2472 storageFlags, ps.pkg, false); 2473 } 2474 } 2475 } 2476 } 2477 2478 // If this is first boot after an OTA, and a normal boot, then 2479 // we need to clear code cache directories. 2480 if (mIsUpgrade && !onlyCore) { 2481 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2482 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2483 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2484 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2485 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2486 } 2487 } 2488 ver.fingerprint = Build.FINGERPRINT; 2489 } 2490 2491 checkDefaultBrowser(); 2492 2493 // clear only after permissions and other defaults have been updated 2494 mExistingSystemPackages.clear(); 2495 mPromoteSystemApps = false; 2496 2497 // All the changes are done during package scanning. 2498 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2499 2500 // can downgrade to reader 2501 mSettings.writeLPr(); 2502 2503 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2504 SystemClock.uptimeMillis()); 2505 2506 if (!mOnlyCore) { 2507 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2508 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2509 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2510 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2511 mIntentFilterVerifierComponent); 2512 } else { 2513 mRequiredVerifierPackage = null; 2514 mRequiredInstallerPackage = null; 2515 mIntentFilterVerifierComponent = null; 2516 mIntentFilterVerifier = null; 2517 } 2518 2519 mInstallerService = new PackageInstallerService(context, this); 2520 2521 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2522 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2523 // both the installer and resolver must be present to enable ephemeral 2524 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2525 if (DEBUG_EPHEMERAL) { 2526 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2527 + " installer:" + ephemeralInstallerComponent); 2528 } 2529 mEphemeralResolverComponent = ephemeralResolverComponent; 2530 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2531 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2532 mEphemeralResolverConnection = 2533 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2534 } else { 2535 if (DEBUG_EPHEMERAL) { 2536 final String missingComponent = 2537 (ephemeralResolverComponent == null) 2538 ? (ephemeralInstallerComponent == null) 2539 ? "resolver and installer" 2540 : "resolver" 2541 : "installer"; 2542 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2543 } 2544 mEphemeralResolverComponent = null; 2545 mEphemeralInstallerComponent = null; 2546 mEphemeralResolverConnection = null; 2547 } 2548 2549 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2550 } // synchronized (mPackages) 2551 } // synchronized (mInstallLock) 2552 2553 // Now after opening every single application zip, make sure they 2554 // are all flushed. Not really needed, but keeps things nice and 2555 // tidy. 2556 Runtime.getRuntime().gc(); 2557 2558 // The initial scanning above does many calls into installd while 2559 // holding the mPackages lock, but we're mostly interested in yelling 2560 // once we have a booted system. 2561 mInstaller.setWarnIfHeld(mPackages); 2562 2563 // Expose private service for system components to use. 2564 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2565 } 2566 2567 @Override 2568 public boolean isFirstBoot() { 2569 return !mRestoredSettings; 2570 } 2571 2572 @Override 2573 public boolean isOnlyCoreApps() { 2574 return mOnlyCore; 2575 } 2576 2577 @Override 2578 public boolean isUpgrade() { 2579 return mIsUpgrade; 2580 } 2581 2582 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2583 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2584 2585 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2586 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2587 if (matches.size() == 1) { 2588 return matches.get(0).getComponentInfo().packageName; 2589 } else { 2590 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2591 return null; 2592 } 2593 } 2594 2595 private @NonNull String getRequiredInstallerLPr() { 2596 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2597 intent.addCategory(Intent.CATEGORY_DEFAULT); 2598 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2599 2600 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2601 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2602 if (matches.size() == 1) { 2603 return matches.get(0).getComponentInfo().packageName; 2604 } else { 2605 throw new RuntimeException("There must be exactly one installer; found " + matches); 2606 } 2607 } 2608 2609 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2610 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2611 2612 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2613 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2614 ResolveInfo best = null; 2615 final int N = matches.size(); 2616 for (int i = 0; i < N; i++) { 2617 final ResolveInfo cur = matches.get(i); 2618 final String packageName = cur.getComponentInfo().packageName; 2619 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2620 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2621 continue; 2622 } 2623 2624 if (best == null || cur.priority > best.priority) { 2625 best = cur; 2626 } 2627 } 2628 2629 if (best != null) { 2630 return best.getComponentInfo().getComponentName(); 2631 } else { 2632 throw new RuntimeException("There must be at least one intent filter verifier"); 2633 } 2634 } 2635 2636 private @Nullable ComponentName getEphemeralResolverLPr() { 2637 final String[] packageArray = 2638 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2639 if (packageArray.length == 0) { 2640 if (DEBUG_EPHEMERAL) { 2641 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2642 } 2643 return null; 2644 } 2645 2646 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2647 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null, 2648 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2649 2650 final int N = resolvers.size(); 2651 if (N == 0) { 2652 if (DEBUG_EPHEMERAL) { 2653 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2654 } 2655 return null; 2656 } 2657 2658 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2659 for (int i = 0; i < N; i++) { 2660 final ResolveInfo info = resolvers.get(i); 2661 2662 if (info.serviceInfo == null) { 2663 continue; 2664 } 2665 2666 final String packageName = info.serviceInfo.packageName; 2667 if (!possiblePackages.contains(packageName)) { 2668 if (DEBUG_EPHEMERAL) { 2669 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2670 + " pkg: " + packageName + ", info:" + info); 2671 } 2672 continue; 2673 } 2674 2675 if (DEBUG_EPHEMERAL) { 2676 Slog.v(TAG, "Ephemeral resolver found;" 2677 + " pkg: " + packageName + ", info:" + info); 2678 } 2679 return new ComponentName(packageName, info.serviceInfo.name); 2680 } 2681 if (DEBUG_EPHEMERAL) { 2682 Slog.v(TAG, "Ephemeral resolver NOT found"); 2683 } 2684 return null; 2685 } 2686 2687 private @Nullable ComponentName getEphemeralInstallerLPr() { 2688 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2689 intent.addCategory(Intent.CATEGORY_DEFAULT); 2690 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2691 2692 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2693 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2694 if (matches.size() == 0) { 2695 return null; 2696 } else if (matches.size() == 1) { 2697 return matches.get(0).getComponentInfo().getComponentName(); 2698 } else { 2699 throw new RuntimeException( 2700 "There must be at most one ephemeral installer; found " + matches); 2701 } 2702 } 2703 2704 private void primeDomainVerificationsLPw(int userId) { 2705 if (DEBUG_DOMAIN_VERIFICATION) { 2706 Slog.d(TAG, "Priming domain verifications in user " + userId); 2707 } 2708 2709 SystemConfig systemConfig = SystemConfig.getInstance(); 2710 ArraySet<String> packages = systemConfig.getLinkedApps(); 2711 ArraySet<String> domains = new ArraySet<String>(); 2712 2713 for (String packageName : packages) { 2714 PackageParser.Package pkg = mPackages.get(packageName); 2715 if (pkg != null) { 2716 if (!pkg.isSystemApp()) { 2717 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2718 continue; 2719 } 2720 2721 domains.clear(); 2722 for (PackageParser.Activity a : pkg.activities) { 2723 for (ActivityIntentInfo filter : a.intents) { 2724 if (hasValidDomains(filter)) { 2725 domains.addAll(filter.getHostsList()); 2726 } 2727 } 2728 } 2729 2730 if (domains.size() > 0) { 2731 if (DEBUG_DOMAIN_VERIFICATION) { 2732 Slog.v(TAG, " + " + packageName); 2733 } 2734 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2735 // state w.r.t. the formal app-linkage "no verification attempted" state; 2736 // and then 'always' in the per-user state actually used for intent resolution. 2737 final IntentFilterVerificationInfo ivi; 2738 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2739 new ArrayList<String>(domains)); 2740 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2741 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2742 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2743 } else { 2744 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2745 + "' does not handle web links"); 2746 } 2747 } else { 2748 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2749 } 2750 } 2751 2752 scheduleWritePackageRestrictionsLocked(userId); 2753 scheduleWriteSettingsLocked(); 2754 } 2755 2756 private void applyFactoryDefaultBrowserLPw(int userId) { 2757 // The default browser app's package name is stored in a string resource, 2758 // with a product-specific overlay used for vendor customization. 2759 String browserPkg = mContext.getResources().getString( 2760 com.android.internal.R.string.default_browser); 2761 if (!TextUtils.isEmpty(browserPkg)) { 2762 // non-empty string => required to be a known package 2763 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2764 if (ps == null) { 2765 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2766 browserPkg = null; 2767 } else { 2768 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2769 } 2770 } 2771 2772 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2773 // default. If there's more than one, just leave everything alone. 2774 if (browserPkg == null) { 2775 calculateDefaultBrowserLPw(userId); 2776 } 2777 } 2778 2779 private void calculateDefaultBrowserLPw(int userId) { 2780 List<String> allBrowsers = resolveAllBrowserApps(userId); 2781 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2782 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2783 } 2784 2785 private List<String> resolveAllBrowserApps(int userId) { 2786 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2787 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2788 PackageManager.MATCH_ALL, userId); 2789 2790 final int count = list.size(); 2791 List<String> result = new ArrayList<String>(count); 2792 for (int i=0; i<count; i++) { 2793 ResolveInfo info = list.get(i); 2794 if (info.activityInfo == null 2795 || !info.handleAllWebDataURI 2796 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2797 || result.contains(info.activityInfo.packageName)) { 2798 continue; 2799 } 2800 result.add(info.activityInfo.packageName); 2801 } 2802 2803 return result; 2804 } 2805 2806 private boolean packageIsBrowser(String packageName, int userId) { 2807 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2808 PackageManager.MATCH_ALL, userId); 2809 final int N = list.size(); 2810 for (int i = 0; i < N; i++) { 2811 ResolveInfo info = list.get(i); 2812 if (packageName.equals(info.activityInfo.packageName)) { 2813 return true; 2814 } 2815 } 2816 return false; 2817 } 2818 2819 private void checkDefaultBrowser() { 2820 final int myUserId = UserHandle.myUserId(); 2821 final String packageName = getDefaultBrowserPackageName(myUserId); 2822 if (packageName != null) { 2823 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2824 if (info == null) { 2825 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2826 synchronized (mPackages) { 2827 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2828 } 2829 } 2830 } 2831 } 2832 2833 @Override 2834 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2835 throws RemoteException { 2836 try { 2837 return super.onTransact(code, data, reply, flags); 2838 } catch (RuntimeException e) { 2839 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2840 Slog.wtf(TAG, "Package Manager Crash", e); 2841 } 2842 throw e; 2843 } 2844 } 2845 2846 void cleanupInstallFailedPackage(PackageSetting ps) { 2847 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2848 2849 removeDataDirsLI(ps.volumeUuid, ps.name); 2850 if (ps.codePath != null) { 2851 removeCodePathLI(ps.codePath); 2852 } 2853 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2854 if (ps.resourcePath.isDirectory()) { 2855 FileUtils.deleteContents(ps.resourcePath); 2856 } 2857 ps.resourcePath.delete(); 2858 } 2859 mSettings.removePackageLPw(ps.name); 2860 } 2861 2862 static int[] appendInts(int[] cur, int[] add) { 2863 if (add == null) return cur; 2864 if (cur == null) return add; 2865 final int N = add.length; 2866 for (int i=0; i<N; i++) { 2867 cur = appendInt(cur, add[i]); 2868 } 2869 return cur; 2870 } 2871 2872 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2873 if (!sUserManager.exists(userId)) return null; 2874 final PackageSetting ps = (PackageSetting) p.mExtras; 2875 if (ps == null) { 2876 return null; 2877 } 2878 2879 final PermissionsState permissionsState = ps.getPermissionsState(); 2880 2881 final int[] gids = permissionsState.computeGids(userId); 2882 final Set<String> permissions = permissionsState.getPermissions(userId); 2883 final PackageUserState state = ps.readUserState(userId); 2884 2885 return PackageParser.generatePackageInfo(p, gids, flags, 2886 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2887 } 2888 2889 @Override 2890 public void checkPackageStartable(String packageName, int userId) { 2891 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2892 2893 synchronized (mPackages) { 2894 final PackageSetting ps = mSettings.mPackages.get(packageName); 2895 if (ps == null) { 2896 throw new SecurityException("Package " + packageName + " was not found!"); 2897 } 2898 2899 if (mSafeMode && !ps.isSystem()) { 2900 throw new SecurityException("Package " + packageName + " not a system app!"); 2901 } 2902 2903 if (ps.frozen) { 2904 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2905 } 2906 2907 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2908 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2909 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2910 } 2911 } 2912 } 2913 2914 @Override 2915 public boolean isPackageAvailable(String packageName, int userId) { 2916 if (!sUserManager.exists(userId)) return false; 2917 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2918 synchronized (mPackages) { 2919 PackageParser.Package p = mPackages.get(packageName); 2920 if (p != null) { 2921 final PackageSetting ps = (PackageSetting) p.mExtras; 2922 if (ps != null) { 2923 final PackageUserState state = ps.readUserState(userId); 2924 if (state != null) { 2925 return PackageParser.isAvailable(state); 2926 } 2927 } 2928 } 2929 } 2930 return false; 2931 } 2932 2933 @Override 2934 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2935 if (!sUserManager.exists(userId)) return null; 2936 flags = updateFlagsForPackage(flags, userId, packageName); 2937 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2938 // reader 2939 synchronized (mPackages) { 2940 PackageParser.Package p = mPackages.get(packageName); 2941 if (DEBUG_PACKAGE_INFO) 2942 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2943 if (p != null) { 2944 return generatePackageInfo(p, flags, userId); 2945 } 2946 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2947 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2948 } 2949 } 2950 return null; 2951 } 2952 2953 @Override 2954 public String[] currentToCanonicalPackageNames(String[] names) { 2955 String[] out = new String[names.length]; 2956 // reader 2957 synchronized (mPackages) { 2958 for (int i=names.length-1; i>=0; i--) { 2959 PackageSetting ps = mSettings.mPackages.get(names[i]); 2960 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2961 } 2962 } 2963 return out; 2964 } 2965 2966 @Override 2967 public String[] canonicalToCurrentPackageNames(String[] names) { 2968 String[] out = new String[names.length]; 2969 // reader 2970 synchronized (mPackages) { 2971 for (int i=names.length-1; i>=0; i--) { 2972 String cur = mSettings.mRenamedPackages.get(names[i]); 2973 out[i] = cur != null ? cur : names[i]; 2974 } 2975 } 2976 return out; 2977 } 2978 2979 @Override 2980 public int getPackageUid(String packageName, int flags, int userId) { 2981 if (!sUserManager.exists(userId)) return -1; 2982 flags = updateFlagsForPackage(flags, userId, packageName); 2983 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2984 2985 // reader 2986 synchronized (mPackages) { 2987 final PackageParser.Package p = mPackages.get(packageName); 2988 if (p != null && p.isMatch(flags)) { 2989 return UserHandle.getUid(userId, p.applicationInfo.uid); 2990 } 2991 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2992 final PackageSetting ps = mSettings.mPackages.get(packageName); 2993 if (ps != null && ps.isMatch(flags)) { 2994 return UserHandle.getUid(userId, ps.appId); 2995 } 2996 } 2997 } 2998 2999 return -1; 3000 } 3001 3002 @Override 3003 public int[] getPackageGids(String packageName, int flags, int userId) { 3004 if (!sUserManager.exists(userId)) return null; 3005 flags = updateFlagsForPackage(flags, userId, packageName); 3006 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3007 "getPackageGids"); 3008 3009 // reader 3010 synchronized (mPackages) { 3011 final PackageParser.Package p = mPackages.get(packageName); 3012 if (p != null && p.isMatch(flags)) { 3013 PackageSetting ps = (PackageSetting) p.mExtras; 3014 return ps.getPermissionsState().computeGids(userId); 3015 } 3016 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3017 final PackageSetting ps = mSettings.mPackages.get(packageName); 3018 if (ps != null && ps.isMatch(flags)) { 3019 return ps.getPermissionsState().computeGids(userId); 3020 } 3021 } 3022 } 3023 3024 return null; 3025 } 3026 3027 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3028 if (bp.perm != null) { 3029 return PackageParser.generatePermissionInfo(bp.perm, flags); 3030 } 3031 PermissionInfo pi = new PermissionInfo(); 3032 pi.name = bp.name; 3033 pi.packageName = bp.sourcePackage; 3034 pi.nonLocalizedLabel = bp.name; 3035 pi.protectionLevel = bp.protectionLevel; 3036 return pi; 3037 } 3038 3039 @Override 3040 public PermissionInfo getPermissionInfo(String name, int flags) { 3041 // reader 3042 synchronized (mPackages) { 3043 final BasePermission p = mSettings.mPermissions.get(name); 3044 if (p != null) { 3045 return generatePermissionInfo(p, flags); 3046 } 3047 return null; 3048 } 3049 } 3050 3051 @Override 3052 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 3053 // reader 3054 synchronized (mPackages) { 3055 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3056 for (BasePermission p : mSettings.mPermissions.values()) { 3057 if (group == null) { 3058 if (p.perm == null || p.perm.info.group == null) { 3059 out.add(generatePermissionInfo(p, flags)); 3060 } 3061 } else { 3062 if (p.perm != null && group.equals(p.perm.info.group)) { 3063 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3064 } 3065 } 3066 } 3067 3068 if (out.size() > 0) { 3069 return out; 3070 } 3071 return mPermissionGroups.containsKey(group) ? out : null; 3072 } 3073 } 3074 3075 @Override 3076 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3077 // reader 3078 synchronized (mPackages) { 3079 return PackageParser.generatePermissionGroupInfo( 3080 mPermissionGroups.get(name), flags); 3081 } 3082 } 3083 3084 @Override 3085 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3086 // reader 3087 synchronized (mPackages) { 3088 final int N = mPermissionGroups.size(); 3089 ArrayList<PermissionGroupInfo> out 3090 = new ArrayList<PermissionGroupInfo>(N); 3091 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3092 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3093 } 3094 return out; 3095 } 3096 } 3097 3098 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3099 int userId) { 3100 if (!sUserManager.exists(userId)) return null; 3101 PackageSetting ps = mSettings.mPackages.get(packageName); 3102 if (ps != null) { 3103 if (ps.pkg == null) { 3104 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3105 flags, userId); 3106 if (pInfo != null) { 3107 return pInfo.applicationInfo; 3108 } 3109 return null; 3110 } 3111 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3112 ps.readUserState(userId), userId); 3113 } 3114 return null; 3115 } 3116 3117 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3118 int userId) { 3119 if (!sUserManager.exists(userId)) return null; 3120 PackageSetting ps = mSettings.mPackages.get(packageName); 3121 if (ps != null) { 3122 PackageParser.Package pkg = ps.pkg; 3123 if (pkg == null) { 3124 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3125 return null; 3126 } 3127 // Only data remains, so we aren't worried about code paths 3128 pkg = new PackageParser.Package(packageName); 3129 pkg.applicationInfo.packageName = packageName; 3130 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3131 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3132 pkg.applicationInfo.uid = ps.appId; 3133 pkg.applicationInfo.initForUser(userId); 3134 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3135 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3136 } 3137 return generatePackageInfo(pkg, flags, userId); 3138 } 3139 return null; 3140 } 3141 3142 @Override 3143 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3144 if (!sUserManager.exists(userId)) return null; 3145 flags = updateFlagsForApplication(flags, userId, packageName); 3146 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3147 // writer 3148 synchronized (mPackages) { 3149 PackageParser.Package p = mPackages.get(packageName); 3150 if (DEBUG_PACKAGE_INFO) Log.v( 3151 TAG, "getApplicationInfo " + packageName 3152 + ": " + p); 3153 if (p != null) { 3154 PackageSetting ps = mSettings.mPackages.get(packageName); 3155 if (ps == null) return null; 3156 // Note: isEnabledLP() does not apply here - always return info 3157 return PackageParser.generateApplicationInfo( 3158 p, flags, ps.readUserState(userId), userId); 3159 } 3160 if ("android".equals(packageName)||"system".equals(packageName)) { 3161 return mAndroidApplication; 3162 } 3163 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3164 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3165 } 3166 } 3167 return null; 3168 } 3169 3170 @Override 3171 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3172 final IPackageDataObserver observer) { 3173 mContext.enforceCallingOrSelfPermission( 3174 android.Manifest.permission.CLEAR_APP_CACHE, null); 3175 // Queue up an async operation since clearing cache may take a little while. 3176 mHandler.post(new Runnable() { 3177 public void run() { 3178 mHandler.removeCallbacks(this); 3179 boolean success = true; 3180 synchronized (mInstallLock) { 3181 try { 3182 mInstaller.freeCache(volumeUuid, freeStorageSize); 3183 } catch (InstallerException e) { 3184 Slog.w(TAG, "Couldn't clear application caches: " + e); 3185 success = false; 3186 } 3187 } 3188 if (observer != null) { 3189 try { 3190 observer.onRemoveCompleted(null, success); 3191 } catch (RemoteException e) { 3192 Slog.w(TAG, "RemoveException when invoking call back"); 3193 } 3194 } 3195 } 3196 }); 3197 } 3198 3199 @Override 3200 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3201 final IntentSender pi) { 3202 mContext.enforceCallingOrSelfPermission( 3203 android.Manifest.permission.CLEAR_APP_CACHE, null); 3204 // Queue up an async operation since clearing cache may take a little while. 3205 mHandler.post(new Runnable() { 3206 public void run() { 3207 mHandler.removeCallbacks(this); 3208 boolean success = true; 3209 synchronized (mInstallLock) { 3210 try { 3211 mInstaller.freeCache(volumeUuid, freeStorageSize); 3212 } catch (InstallerException e) { 3213 Slog.w(TAG, "Couldn't clear application caches: " + e); 3214 success = false; 3215 } 3216 } 3217 if(pi != null) { 3218 try { 3219 // Callback via pending intent 3220 int code = success ? 1 : 0; 3221 pi.sendIntent(null, code, null, 3222 null, null); 3223 } catch (SendIntentException e1) { 3224 Slog.i(TAG, "Failed to send pending intent"); 3225 } 3226 } 3227 } 3228 }); 3229 } 3230 3231 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3232 synchronized (mInstallLock) { 3233 try { 3234 mInstaller.freeCache(volumeUuid, freeStorageSize); 3235 } catch (InstallerException e) { 3236 throw new IOException("Failed to free enough space", e); 3237 } 3238 } 3239 } 3240 3241 /** 3242 * Return if the user key is currently unlocked. 3243 */ 3244 private boolean isUserKeyUnlocked(int userId) { 3245 if (StorageManager.isFileBasedEncryptionEnabled()) { 3246 final IMountService mount = IMountService.Stub 3247 .asInterface(ServiceManager.getService("mount")); 3248 if (mount == null) { 3249 Slog.w(TAG, "Early during boot, assuming locked"); 3250 return false; 3251 } 3252 final long token = Binder.clearCallingIdentity(); 3253 try { 3254 return mount.isUserKeyUnlocked(userId); 3255 } catch (RemoteException e) { 3256 throw e.rethrowAsRuntimeException(); 3257 } finally { 3258 Binder.restoreCallingIdentity(token); 3259 } 3260 } else { 3261 return true; 3262 } 3263 } 3264 3265 /** 3266 * Update given flags based on encryption status of current user. 3267 */ 3268 private int updateFlags(int flags, int userId) { 3269 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3270 | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) { 3271 // Caller expressed an explicit opinion about what encryption 3272 // aware/unaware components they want to see, so fall through and 3273 // give them what they want 3274 } else { 3275 // Caller expressed no opinion, so match based on user state 3276 if (isUserKeyUnlocked(userId)) { 3277 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 3278 } else { 3279 flags |= PackageManager.MATCH_ENCRYPTION_AWARE; 3280 } 3281 } 3282 return flags; 3283 } 3284 3285 /** 3286 * Update given flags when being used to request {@link PackageInfo}. 3287 */ 3288 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3289 boolean triaged = true; 3290 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3291 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3292 // Caller is asking for component details, so they'd better be 3293 // asking for specific encryption matching behavior, or be triaged 3294 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3295 | PackageManager.MATCH_ENCRYPTION_AWARE 3296 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3297 triaged = false; 3298 } 3299 } 3300 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3301 | PackageManager.MATCH_SYSTEM_ONLY 3302 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3303 triaged = false; 3304 } 3305 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3306 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3307 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3308 } 3309 return updateFlags(flags, userId); 3310 } 3311 3312 /** 3313 * Update given flags when being used to request {@link ApplicationInfo}. 3314 */ 3315 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3316 return updateFlagsForPackage(flags, userId, cookie); 3317 } 3318 3319 /** 3320 * Update given flags when being used to request {@link ComponentInfo}. 3321 */ 3322 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3323 if (cookie instanceof Intent) { 3324 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3325 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3326 } 3327 } 3328 3329 boolean triaged = true; 3330 // Caller is asking for component details, so they'd better be 3331 // asking for specific encryption matching behavior, or be triaged 3332 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3333 | PackageManager.MATCH_ENCRYPTION_AWARE 3334 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3335 triaged = false; 3336 } 3337 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3338 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3339 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3340 } 3341 3342 // Safe mode means we shouldn't match any third-party components 3343 if (mSafeMode) { 3344 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3345 } 3346 3347 return updateFlags(flags, userId); 3348 } 3349 3350 /** 3351 * Update given flags when being used to request {@link ResolveInfo}. 3352 */ 3353 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3354 return updateFlagsForComponent(flags, userId, cookie); 3355 } 3356 3357 @Override 3358 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3359 if (!sUserManager.exists(userId)) return null; 3360 flags = updateFlagsForComponent(flags, userId, component); 3361 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3362 synchronized (mPackages) { 3363 PackageParser.Activity a = mActivities.mActivities.get(component); 3364 3365 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3366 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3367 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3368 if (ps == null) return null; 3369 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3370 userId); 3371 } 3372 if (mResolveComponentName.equals(component)) { 3373 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3374 new PackageUserState(), userId); 3375 } 3376 } 3377 return null; 3378 } 3379 3380 @Override 3381 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3382 String resolvedType) { 3383 synchronized (mPackages) { 3384 if (component.equals(mResolveComponentName)) { 3385 // The resolver supports EVERYTHING! 3386 return true; 3387 } 3388 PackageParser.Activity a = mActivities.mActivities.get(component); 3389 if (a == null) { 3390 return false; 3391 } 3392 for (int i=0; i<a.intents.size(); i++) { 3393 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3394 intent.getData(), intent.getCategories(), TAG) >= 0) { 3395 return true; 3396 } 3397 } 3398 return false; 3399 } 3400 } 3401 3402 @Override 3403 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3404 if (!sUserManager.exists(userId)) return null; 3405 flags = updateFlagsForComponent(flags, userId, component); 3406 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3407 synchronized (mPackages) { 3408 PackageParser.Activity a = mReceivers.mActivities.get(component); 3409 if (DEBUG_PACKAGE_INFO) Log.v( 3410 TAG, "getReceiverInfo " + component + ": " + a); 3411 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3412 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3413 if (ps == null) return null; 3414 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3415 userId); 3416 } 3417 } 3418 return null; 3419 } 3420 3421 @Override 3422 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3423 if (!sUserManager.exists(userId)) return null; 3424 flags = updateFlagsForComponent(flags, userId, component); 3425 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3426 synchronized (mPackages) { 3427 PackageParser.Service s = mServices.mServices.get(component); 3428 if (DEBUG_PACKAGE_INFO) Log.v( 3429 TAG, "getServiceInfo " + component + ": " + s); 3430 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3431 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3432 if (ps == null) return null; 3433 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3434 userId); 3435 } 3436 } 3437 return null; 3438 } 3439 3440 @Override 3441 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3442 if (!sUserManager.exists(userId)) return null; 3443 flags = updateFlagsForComponent(flags, userId, component); 3444 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3445 synchronized (mPackages) { 3446 PackageParser.Provider p = mProviders.mProviders.get(component); 3447 if (DEBUG_PACKAGE_INFO) Log.v( 3448 TAG, "getProviderInfo " + component + ": " + p); 3449 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3450 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3451 if (ps == null) return null; 3452 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3453 userId); 3454 } 3455 } 3456 return null; 3457 } 3458 3459 @Override 3460 public String[] getSystemSharedLibraryNames() { 3461 Set<String> libSet; 3462 synchronized (mPackages) { 3463 libSet = mSharedLibraries.keySet(); 3464 int size = libSet.size(); 3465 if (size > 0) { 3466 String[] libs = new String[size]; 3467 libSet.toArray(libs); 3468 return libs; 3469 } 3470 } 3471 return null; 3472 } 3473 3474 @Override 3475 public @Nullable String getServicesSystemSharedLibraryPackageName() { 3476 synchronized (mPackages) { 3477 SharedLibraryEntry libraryEntry = mSharedLibraries.get( 3478 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 3479 if (libraryEntry != null) { 3480 return libraryEntry.apk; 3481 } 3482 } 3483 return null; 3484 } 3485 3486 @Override 3487 public FeatureInfo[] getSystemAvailableFeatures() { 3488 Collection<FeatureInfo> featSet; 3489 synchronized (mPackages) { 3490 featSet = mAvailableFeatures.values(); 3491 int size = featSet.size(); 3492 if (size > 0) { 3493 FeatureInfo[] features = new FeatureInfo[size+1]; 3494 featSet.toArray(features); 3495 FeatureInfo fi = new FeatureInfo(); 3496 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3497 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3498 features[size] = fi; 3499 return features; 3500 } 3501 } 3502 return null; 3503 } 3504 3505 @Override 3506 public boolean hasSystemFeature(String name, int version) { 3507 synchronized (mPackages) { 3508 final FeatureInfo feat = mAvailableFeatures.get(name); 3509 if (feat == null) { 3510 return false; 3511 } else { 3512 return feat.version >= version; 3513 } 3514 } 3515 } 3516 3517 @Override 3518 public int checkPermission(String permName, String pkgName, int userId) { 3519 if (!sUserManager.exists(userId)) { 3520 return PackageManager.PERMISSION_DENIED; 3521 } 3522 3523 synchronized (mPackages) { 3524 final PackageParser.Package p = mPackages.get(pkgName); 3525 if (p != null && p.mExtras != null) { 3526 final PackageSetting ps = (PackageSetting) p.mExtras; 3527 final PermissionsState permissionsState = ps.getPermissionsState(); 3528 if (permissionsState.hasPermission(permName, userId)) { 3529 return PackageManager.PERMISSION_GRANTED; 3530 } 3531 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3532 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3533 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3534 return PackageManager.PERMISSION_GRANTED; 3535 } 3536 } 3537 } 3538 3539 return PackageManager.PERMISSION_DENIED; 3540 } 3541 3542 @Override 3543 public int checkUidPermission(String permName, int uid) { 3544 final int userId = UserHandle.getUserId(uid); 3545 3546 if (!sUserManager.exists(userId)) { 3547 return PackageManager.PERMISSION_DENIED; 3548 } 3549 3550 synchronized (mPackages) { 3551 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3552 if (obj != null) { 3553 final SettingBase ps = (SettingBase) obj; 3554 final PermissionsState permissionsState = ps.getPermissionsState(); 3555 if (permissionsState.hasPermission(permName, userId)) { 3556 return PackageManager.PERMISSION_GRANTED; 3557 } 3558 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3559 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3560 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3561 return PackageManager.PERMISSION_GRANTED; 3562 } 3563 } else { 3564 ArraySet<String> perms = mSystemPermissions.get(uid); 3565 if (perms != null) { 3566 if (perms.contains(permName)) { 3567 return PackageManager.PERMISSION_GRANTED; 3568 } 3569 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3570 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3571 return PackageManager.PERMISSION_GRANTED; 3572 } 3573 } 3574 } 3575 } 3576 3577 return PackageManager.PERMISSION_DENIED; 3578 } 3579 3580 @Override 3581 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3582 if (UserHandle.getCallingUserId() != userId) { 3583 mContext.enforceCallingPermission( 3584 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3585 "isPermissionRevokedByPolicy for user " + userId); 3586 } 3587 3588 if (checkPermission(permission, packageName, userId) 3589 == PackageManager.PERMISSION_GRANTED) { 3590 return false; 3591 } 3592 3593 final long identity = Binder.clearCallingIdentity(); 3594 try { 3595 final int flags = getPermissionFlags(permission, packageName, userId); 3596 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3597 } finally { 3598 Binder.restoreCallingIdentity(identity); 3599 } 3600 } 3601 3602 @Override 3603 public String getPermissionControllerPackageName() { 3604 synchronized (mPackages) { 3605 return mRequiredInstallerPackage; 3606 } 3607 } 3608 3609 /** 3610 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3611 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3612 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3613 * @param message the message to log on security exception 3614 */ 3615 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3616 boolean checkShell, String message) { 3617 if (userId < 0) { 3618 throw new IllegalArgumentException("Invalid userId " + userId); 3619 } 3620 if (checkShell) { 3621 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3622 } 3623 if (userId == UserHandle.getUserId(callingUid)) return; 3624 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3625 if (requireFullPermission) { 3626 mContext.enforceCallingOrSelfPermission( 3627 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3628 } else { 3629 try { 3630 mContext.enforceCallingOrSelfPermission( 3631 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3632 } catch (SecurityException se) { 3633 mContext.enforceCallingOrSelfPermission( 3634 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3635 } 3636 } 3637 } 3638 } 3639 3640 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3641 if (callingUid == Process.SHELL_UID) { 3642 if (userHandle >= 0 3643 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3644 throw new SecurityException("Shell does not have permission to access user " 3645 + userHandle); 3646 } else if (userHandle < 0) { 3647 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3648 + Debug.getCallers(3)); 3649 } 3650 } 3651 } 3652 3653 private BasePermission findPermissionTreeLP(String permName) { 3654 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3655 if (permName.startsWith(bp.name) && 3656 permName.length() > bp.name.length() && 3657 permName.charAt(bp.name.length()) == '.') { 3658 return bp; 3659 } 3660 } 3661 return null; 3662 } 3663 3664 private BasePermission checkPermissionTreeLP(String permName) { 3665 if (permName != null) { 3666 BasePermission bp = findPermissionTreeLP(permName); 3667 if (bp != null) { 3668 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3669 return bp; 3670 } 3671 throw new SecurityException("Calling uid " 3672 + Binder.getCallingUid() 3673 + " is not allowed to add to permission tree " 3674 + bp.name + " owned by uid " + bp.uid); 3675 } 3676 } 3677 throw new SecurityException("No permission tree found for " + permName); 3678 } 3679 3680 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3681 if (s1 == null) { 3682 return s2 == null; 3683 } 3684 if (s2 == null) { 3685 return false; 3686 } 3687 if (s1.getClass() != s2.getClass()) { 3688 return false; 3689 } 3690 return s1.equals(s2); 3691 } 3692 3693 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3694 if (pi1.icon != pi2.icon) return false; 3695 if (pi1.logo != pi2.logo) return false; 3696 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3697 if (!compareStrings(pi1.name, pi2.name)) return false; 3698 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3699 // We'll take care of setting this one. 3700 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3701 // These are not currently stored in settings. 3702 //if (!compareStrings(pi1.group, pi2.group)) return false; 3703 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3704 //if (pi1.labelRes != pi2.labelRes) return false; 3705 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3706 return true; 3707 } 3708 3709 int permissionInfoFootprint(PermissionInfo info) { 3710 int size = info.name.length(); 3711 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3712 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3713 return size; 3714 } 3715 3716 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3717 int size = 0; 3718 for (BasePermission perm : mSettings.mPermissions.values()) { 3719 if (perm.uid == tree.uid) { 3720 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3721 } 3722 } 3723 return size; 3724 } 3725 3726 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3727 // We calculate the max size of permissions defined by this uid and throw 3728 // if that plus the size of 'info' would exceed our stated maximum. 3729 if (tree.uid != Process.SYSTEM_UID) { 3730 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3731 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3732 throw new SecurityException("Permission tree size cap exceeded"); 3733 } 3734 } 3735 } 3736 3737 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3738 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3739 throw new SecurityException("Label must be specified in permission"); 3740 } 3741 BasePermission tree = checkPermissionTreeLP(info.name); 3742 BasePermission bp = mSettings.mPermissions.get(info.name); 3743 boolean added = bp == null; 3744 boolean changed = true; 3745 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3746 if (added) { 3747 enforcePermissionCapLocked(info, tree); 3748 bp = new BasePermission(info.name, tree.sourcePackage, 3749 BasePermission.TYPE_DYNAMIC); 3750 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3751 throw new SecurityException( 3752 "Not allowed to modify non-dynamic permission " 3753 + info.name); 3754 } else { 3755 if (bp.protectionLevel == fixedLevel 3756 && bp.perm.owner.equals(tree.perm.owner) 3757 && bp.uid == tree.uid 3758 && comparePermissionInfos(bp.perm.info, info)) { 3759 changed = false; 3760 } 3761 } 3762 bp.protectionLevel = fixedLevel; 3763 info = new PermissionInfo(info); 3764 info.protectionLevel = fixedLevel; 3765 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3766 bp.perm.info.packageName = tree.perm.info.packageName; 3767 bp.uid = tree.uid; 3768 if (added) { 3769 mSettings.mPermissions.put(info.name, bp); 3770 } 3771 if (changed) { 3772 if (!async) { 3773 mSettings.writeLPr(); 3774 } else { 3775 scheduleWriteSettingsLocked(); 3776 } 3777 } 3778 return added; 3779 } 3780 3781 @Override 3782 public boolean addPermission(PermissionInfo info) { 3783 synchronized (mPackages) { 3784 return addPermissionLocked(info, false); 3785 } 3786 } 3787 3788 @Override 3789 public boolean addPermissionAsync(PermissionInfo info) { 3790 synchronized (mPackages) { 3791 return addPermissionLocked(info, true); 3792 } 3793 } 3794 3795 @Override 3796 public void removePermission(String name) { 3797 synchronized (mPackages) { 3798 checkPermissionTreeLP(name); 3799 BasePermission bp = mSettings.mPermissions.get(name); 3800 if (bp != null) { 3801 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3802 throw new SecurityException( 3803 "Not allowed to modify non-dynamic permission " 3804 + name); 3805 } 3806 mSettings.mPermissions.remove(name); 3807 mSettings.writeLPr(); 3808 } 3809 } 3810 } 3811 3812 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3813 BasePermission bp) { 3814 int index = pkg.requestedPermissions.indexOf(bp.name); 3815 if (index == -1) { 3816 throw new SecurityException("Package " + pkg.packageName 3817 + " has not requested permission " + bp.name); 3818 } 3819 if (!bp.isRuntime() && !bp.isDevelopment()) { 3820 throw new SecurityException("Permission " + bp.name 3821 + " is not a changeable permission type"); 3822 } 3823 } 3824 3825 @Override 3826 public void grantRuntimePermission(String packageName, String name, final int userId) { 3827 if (!sUserManager.exists(userId)) { 3828 Log.e(TAG, "No such user:" + userId); 3829 return; 3830 } 3831 3832 mContext.enforceCallingOrSelfPermission( 3833 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3834 "grantRuntimePermission"); 3835 3836 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3837 "grantRuntimePermission"); 3838 3839 final int uid; 3840 final SettingBase sb; 3841 3842 synchronized (mPackages) { 3843 final PackageParser.Package pkg = mPackages.get(packageName); 3844 if (pkg == null) { 3845 throw new IllegalArgumentException("Unknown package: " + packageName); 3846 } 3847 3848 final BasePermission bp = mSettings.mPermissions.get(name); 3849 if (bp == null) { 3850 throw new IllegalArgumentException("Unknown permission: " + name); 3851 } 3852 3853 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3854 3855 // If a permission review is required for legacy apps we represent 3856 // their permissions as always granted runtime ones since we need 3857 // to keep the review required permission flag per user while an 3858 // install permission's state is shared across all users. 3859 if (Build.PERMISSIONS_REVIEW_REQUIRED 3860 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3861 && bp.isRuntime()) { 3862 return; 3863 } 3864 3865 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3866 sb = (SettingBase) pkg.mExtras; 3867 if (sb == null) { 3868 throw new IllegalArgumentException("Unknown package: " + packageName); 3869 } 3870 3871 final PermissionsState permissionsState = sb.getPermissionsState(); 3872 3873 final int flags = permissionsState.getPermissionFlags(name, userId); 3874 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3875 throw new SecurityException("Cannot grant system fixed permission " 3876 + name + " for package " + packageName); 3877 } 3878 3879 if (bp.isDevelopment()) { 3880 // Development permissions must be handled specially, since they are not 3881 // normal runtime permissions. For now they apply to all users. 3882 if (permissionsState.grantInstallPermission(bp) != 3883 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3884 scheduleWriteSettingsLocked(); 3885 } 3886 return; 3887 } 3888 3889 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3890 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3891 return; 3892 } 3893 3894 final int result = permissionsState.grantRuntimePermission(bp, userId); 3895 switch (result) { 3896 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3897 return; 3898 } 3899 3900 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3901 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3902 mHandler.post(new Runnable() { 3903 @Override 3904 public void run() { 3905 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3906 } 3907 }); 3908 } 3909 break; 3910 } 3911 3912 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3913 3914 // Not critical if that is lost - app has to request again. 3915 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3916 } 3917 3918 // Only need to do this if user is initialized. Otherwise it's a new user 3919 // and there are no processes running as the user yet and there's no need 3920 // to make an expensive call to remount processes for the changed permissions. 3921 if (READ_EXTERNAL_STORAGE.equals(name) 3922 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3923 final long token = Binder.clearCallingIdentity(); 3924 try { 3925 if (sUserManager.isInitialized(userId)) { 3926 MountServiceInternal mountServiceInternal = LocalServices.getService( 3927 MountServiceInternal.class); 3928 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3929 } 3930 } finally { 3931 Binder.restoreCallingIdentity(token); 3932 } 3933 } 3934 } 3935 3936 @Override 3937 public void revokeRuntimePermission(String packageName, String name, int userId) { 3938 if (!sUserManager.exists(userId)) { 3939 Log.e(TAG, "No such user:" + userId); 3940 return; 3941 } 3942 3943 mContext.enforceCallingOrSelfPermission( 3944 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3945 "revokeRuntimePermission"); 3946 3947 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3948 "revokeRuntimePermission"); 3949 3950 final int appId; 3951 3952 synchronized (mPackages) { 3953 final PackageParser.Package pkg = mPackages.get(packageName); 3954 if (pkg == null) { 3955 throw new IllegalArgumentException("Unknown package: " + packageName); 3956 } 3957 3958 final BasePermission bp = mSettings.mPermissions.get(name); 3959 if (bp == null) { 3960 throw new IllegalArgumentException("Unknown permission: " + name); 3961 } 3962 3963 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3964 3965 // If a permission review is required for legacy apps we represent 3966 // their permissions as always granted runtime ones since we need 3967 // to keep the review required permission flag per user while an 3968 // install permission's state is shared across all users. 3969 if (Build.PERMISSIONS_REVIEW_REQUIRED 3970 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3971 && bp.isRuntime()) { 3972 return; 3973 } 3974 3975 SettingBase sb = (SettingBase) pkg.mExtras; 3976 if (sb == null) { 3977 throw new IllegalArgumentException("Unknown package: " + packageName); 3978 } 3979 3980 final PermissionsState permissionsState = sb.getPermissionsState(); 3981 3982 final int flags = permissionsState.getPermissionFlags(name, userId); 3983 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3984 throw new SecurityException("Cannot revoke system fixed permission " 3985 + name + " for package " + packageName); 3986 } 3987 3988 if (bp.isDevelopment()) { 3989 // Development permissions must be handled specially, since they are not 3990 // normal runtime permissions. For now they apply to all users. 3991 if (permissionsState.revokeInstallPermission(bp) != 3992 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3993 scheduleWriteSettingsLocked(); 3994 } 3995 return; 3996 } 3997 3998 if (permissionsState.revokeRuntimePermission(bp, userId) == 3999 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4000 return; 4001 } 4002 4003 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4004 4005 // Critical, after this call app should never have the permission. 4006 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4007 4008 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4009 } 4010 4011 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4012 } 4013 4014 @Override 4015 public void resetRuntimePermissions() { 4016 mContext.enforceCallingOrSelfPermission( 4017 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4018 "revokeRuntimePermission"); 4019 4020 int callingUid = Binder.getCallingUid(); 4021 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4022 mContext.enforceCallingOrSelfPermission( 4023 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4024 "resetRuntimePermissions"); 4025 } 4026 4027 synchronized (mPackages) { 4028 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4029 for (int userId : UserManagerService.getInstance().getUserIds()) { 4030 final int packageCount = mPackages.size(); 4031 for (int i = 0; i < packageCount; i++) { 4032 PackageParser.Package pkg = mPackages.valueAt(i); 4033 if (!(pkg.mExtras instanceof PackageSetting)) { 4034 continue; 4035 } 4036 PackageSetting ps = (PackageSetting) pkg.mExtras; 4037 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4038 } 4039 } 4040 } 4041 } 4042 4043 @Override 4044 public int getPermissionFlags(String name, String packageName, int userId) { 4045 if (!sUserManager.exists(userId)) { 4046 return 0; 4047 } 4048 4049 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4050 4051 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4052 "getPermissionFlags"); 4053 4054 synchronized (mPackages) { 4055 final PackageParser.Package pkg = mPackages.get(packageName); 4056 if (pkg == null) { 4057 throw new IllegalArgumentException("Unknown package: " + packageName); 4058 } 4059 4060 final BasePermission bp = mSettings.mPermissions.get(name); 4061 if (bp == null) { 4062 throw new IllegalArgumentException("Unknown permission: " + name); 4063 } 4064 4065 SettingBase sb = (SettingBase) pkg.mExtras; 4066 if (sb == null) { 4067 throw new IllegalArgumentException("Unknown package: " + packageName); 4068 } 4069 4070 PermissionsState permissionsState = sb.getPermissionsState(); 4071 return permissionsState.getPermissionFlags(name, userId); 4072 } 4073 } 4074 4075 @Override 4076 public void updatePermissionFlags(String name, String packageName, int flagMask, 4077 int flagValues, int userId) { 4078 if (!sUserManager.exists(userId)) { 4079 return; 4080 } 4081 4082 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4083 4084 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4085 "updatePermissionFlags"); 4086 4087 // Only the system can change these flags and nothing else. 4088 if (getCallingUid() != Process.SYSTEM_UID) { 4089 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4090 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4091 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4092 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4093 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4094 } 4095 4096 synchronized (mPackages) { 4097 final PackageParser.Package pkg = mPackages.get(packageName); 4098 if (pkg == null) { 4099 throw new IllegalArgumentException("Unknown package: " + packageName); 4100 } 4101 4102 final BasePermission bp = mSettings.mPermissions.get(name); 4103 if (bp == null) { 4104 throw new IllegalArgumentException("Unknown permission: " + name); 4105 } 4106 4107 SettingBase sb = (SettingBase) pkg.mExtras; 4108 if (sb == null) { 4109 throw new IllegalArgumentException("Unknown package: " + packageName); 4110 } 4111 4112 PermissionsState permissionsState = sb.getPermissionsState(); 4113 4114 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4115 4116 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4117 // Install and runtime permissions are stored in different places, 4118 // so figure out what permission changed and persist the change. 4119 if (permissionsState.getInstallPermissionState(name) != null) { 4120 scheduleWriteSettingsLocked(); 4121 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4122 || hadState) { 4123 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4124 } 4125 } 4126 } 4127 } 4128 4129 /** 4130 * Update the permission flags for all packages and runtime permissions of a user in order 4131 * to allow device or profile owner to remove POLICY_FIXED. 4132 */ 4133 @Override 4134 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4135 if (!sUserManager.exists(userId)) { 4136 return; 4137 } 4138 4139 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4140 4141 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4142 "updatePermissionFlagsForAllApps"); 4143 4144 // Only the system can change system fixed flags. 4145 if (getCallingUid() != Process.SYSTEM_UID) { 4146 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4147 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4148 } 4149 4150 synchronized (mPackages) { 4151 boolean changed = false; 4152 final int packageCount = mPackages.size(); 4153 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4154 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4155 SettingBase sb = (SettingBase) pkg.mExtras; 4156 if (sb == null) { 4157 continue; 4158 } 4159 PermissionsState permissionsState = sb.getPermissionsState(); 4160 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4161 userId, flagMask, flagValues); 4162 } 4163 if (changed) { 4164 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4165 } 4166 } 4167 } 4168 4169 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4170 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4171 != PackageManager.PERMISSION_GRANTED 4172 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4173 != PackageManager.PERMISSION_GRANTED) { 4174 throw new SecurityException(message + " requires " 4175 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4176 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4177 } 4178 } 4179 4180 @Override 4181 public boolean shouldShowRequestPermissionRationale(String permissionName, 4182 String packageName, int userId) { 4183 if (UserHandle.getCallingUserId() != userId) { 4184 mContext.enforceCallingPermission( 4185 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4186 "canShowRequestPermissionRationale for user " + userId); 4187 } 4188 4189 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4190 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4191 return false; 4192 } 4193 4194 if (checkPermission(permissionName, packageName, userId) 4195 == PackageManager.PERMISSION_GRANTED) { 4196 return false; 4197 } 4198 4199 final int flags; 4200 4201 final long identity = Binder.clearCallingIdentity(); 4202 try { 4203 flags = getPermissionFlags(permissionName, 4204 packageName, userId); 4205 } finally { 4206 Binder.restoreCallingIdentity(identity); 4207 } 4208 4209 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4210 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4211 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4212 4213 if ((flags & fixedFlags) != 0) { 4214 return false; 4215 } 4216 4217 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4218 } 4219 4220 @Override 4221 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4222 mContext.enforceCallingOrSelfPermission( 4223 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4224 "addOnPermissionsChangeListener"); 4225 4226 synchronized (mPackages) { 4227 mOnPermissionChangeListeners.addListenerLocked(listener); 4228 } 4229 } 4230 4231 @Override 4232 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4233 synchronized (mPackages) { 4234 mOnPermissionChangeListeners.removeListenerLocked(listener); 4235 } 4236 } 4237 4238 @Override 4239 public boolean isProtectedBroadcast(String actionName) { 4240 synchronized (mPackages) { 4241 if (mProtectedBroadcasts.contains(actionName)) { 4242 return true; 4243 } else if (actionName != null) { 4244 // TODO: remove these terrible hacks 4245 if (actionName.startsWith("android.net.netmon.lingerExpired") 4246 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4247 || actionName.startsWith("com.android.internal.telephony.data-reconnect")) { 4248 return true; 4249 } 4250 } 4251 } 4252 return false; 4253 } 4254 4255 @Override 4256 public int checkSignatures(String pkg1, String pkg2) { 4257 synchronized (mPackages) { 4258 final PackageParser.Package p1 = mPackages.get(pkg1); 4259 final PackageParser.Package p2 = mPackages.get(pkg2); 4260 if (p1 == null || p1.mExtras == null 4261 || p2 == null || p2.mExtras == null) { 4262 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4263 } 4264 return compareSignatures(p1.mSignatures, p2.mSignatures); 4265 } 4266 } 4267 4268 @Override 4269 public int checkUidSignatures(int uid1, int uid2) { 4270 // Map to base uids. 4271 uid1 = UserHandle.getAppId(uid1); 4272 uid2 = UserHandle.getAppId(uid2); 4273 // reader 4274 synchronized (mPackages) { 4275 Signature[] s1; 4276 Signature[] s2; 4277 Object obj = mSettings.getUserIdLPr(uid1); 4278 if (obj != null) { 4279 if (obj instanceof SharedUserSetting) { 4280 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4281 } else if (obj instanceof PackageSetting) { 4282 s1 = ((PackageSetting)obj).signatures.mSignatures; 4283 } else { 4284 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4285 } 4286 } else { 4287 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4288 } 4289 obj = mSettings.getUserIdLPr(uid2); 4290 if (obj != null) { 4291 if (obj instanceof SharedUserSetting) { 4292 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4293 } else if (obj instanceof PackageSetting) { 4294 s2 = ((PackageSetting)obj).signatures.mSignatures; 4295 } else { 4296 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4297 } 4298 } else { 4299 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4300 } 4301 return compareSignatures(s1, s2); 4302 } 4303 } 4304 4305 private void killUid(int appId, int userId, String reason) { 4306 final long identity = Binder.clearCallingIdentity(); 4307 try { 4308 IActivityManager am = ActivityManagerNative.getDefault(); 4309 if (am != null) { 4310 try { 4311 am.killUid(appId, userId, reason); 4312 } catch (RemoteException e) { 4313 /* ignore - same process */ 4314 } 4315 } 4316 } finally { 4317 Binder.restoreCallingIdentity(identity); 4318 } 4319 } 4320 4321 /** 4322 * Compares two sets of signatures. Returns: 4323 * <br /> 4324 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4325 * <br /> 4326 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4327 * <br /> 4328 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4329 * <br /> 4330 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4331 * <br /> 4332 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4333 */ 4334 static int compareSignatures(Signature[] s1, Signature[] s2) { 4335 if (s1 == null) { 4336 return s2 == null 4337 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4338 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4339 } 4340 4341 if (s2 == null) { 4342 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4343 } 4344 4345 if (s1.length != s2.length) { 4346 return PackageManager.SIGNATURE_NO_MATCH; 4347 } 4348 4349 // Since both signature sets are of size 1, we can compare without HashSets. 4350 if (s1.length == 1) { 4351 return s1[0].equals(s2[0]) ? 4352 PackageManager.SIGNATURE_MATCH : 4353 PackageManager.SIGNATURE_NO_MATCH; 4354 } 4355 4356 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4357 for (Signature sig : s1) { 4358 set1.add(sig); 4359 } 4360 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4361 for (Signature sig : s2) { 4362 set2.add(sig); 4363 } 4364 // Make sure s2 contains all signatures in s1. 4365 if (set1.equals(set2)) { 4366 return PackageManager.SIGNATURE_MATCH; 4367 } 4368 return PackageManager.SIGNATURE_NO_MATCH; 4369 } 4370 4371 /** 4372 * If the database version for this type of package (internal storage or 4373 * external storage) is less than the version where package signatures 4374 * were updated, return true. 4375 */ 4376 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4377 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4378 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4379 } 4380 4381 /** 4382 * Used for backward compatibility to make sure any packages with 4383 * certificate chains get upgraded to the new style. {@code existingSigs} 4384 * will be in the old format (since they were stored on disk from before the 4385 * system upgrade) and {@code scannedSigs} will be in the newer format. 4386 */ 4387 private int compareSignaturesCompat(PackageSignatures existingSigs, 4388 PackageParser.Package scannedPkg) { 4389 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4390 return PackageManager.SIGNATURE_NO_MATCH; 4391 } 4392 4393 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4394 for (Signature sig : existingSigs.mSignatures) { 4395 existingSet.add(sig); 4396 } 4397 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4398 for (Signature sig : scannedPkg.mSignatures) { 4399 try { 4400 Signature[] chainSignatures = sig.getChainSignatures(); 4401 for (Signature chainSig : chainSignatures) { 4402 scannedCompatSet.add(chainSig); 4403 } 4404 } catch (CertificateEncodingException e) { 4405 scannedCompatSet.add(sig); 4406 } 4407 } 4408 /* 4409 * Make sure the expanded scanned set contains all signatures in the 4410 * existing one. 4411 */ 4412 if (scannedCompatSet.equals(existingSet)) { 4413 // Migrate the old signatures to the new scheme. 4414 existingSigs.assignSignatures(scannedPkg.mSignatures); 4415 // The new KeySets will be re-added later in the scanning process. 4416 synchronized (mPackages) { 4417 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4418 } 4419 return PackageManager.SIGNATURE_MATCH; 4420 } 4421 return PackageManager.SIGNATURE_NO_MATCH; 4422 } 4423 4424 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4425 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4426 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4427 } 4428 4429 private int compareSignaturesRecover(PackageSignatures existingSigs, 4430 PackageParser.Package scannedPkg) { 4431 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4432 return PackageManager.SIGNATURE_NO_MATCH; 4433 } 4434 4435 String msg = null; 4436 try { 4437 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4438 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4439 + scannedPkg.packageName); 4440 return PackageManager.SIGNATURE_MATCH; 4441 } 4442 } catch (CertificateException e) { 4443 msg = e.getMessage(); 4444 } 4445 4446 logCriticalInfo(Log.INFO, 4447 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4448 return PackageManager.SIGNATURE_NO_MATCH; 4449 } 4450 4451 @Override 4452 public String[] getPackagesForUid(int uid) { 4453 uid = UserHandle.getAppId(uid); 4454 // reader 4455 synchronized (mPackages) { 4456 Object obj = mSettings.getUserIdLPr(uid); 4457 if (obj instanceof SharedUserSetting) { 4458 final SharedUserSetting sus = (SharedUserSetting) obj; 4459 final int N = sus.packages.size(); 4460 final String[] res = new String[N]; 4461 final Iterator<PackageSetting> it = sus.packages.iterator(); 4462 int i = 0; 4463 while (it.hasNext()) { 4464 res[i++] = it.next().name; 4465 } 4466 return res; 4467 } else if (obj instanceof PackageSetting) { 4468 final PackageSetting ps = (PackageSetting) obj; 4469 return new String[] { ps.name }; 4470 } 4471 } 4472 return null; 4473 } 4474 4475 @Override 4476 public String getNameForUid(int uid) { 4477 // reader 4478 synchronized (mPackages) { 4479 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4480 if (obj instanceof SharedUserSetting) { 4481 final SharedUserSetting sus = (SharedUserSetting) obj; 4482 return sus.name + ":" + sus.userId; 4483 } else if (obj instanceof PackageSetting) { 4484 final PackageSetting ps = (PackageSetting) obj; 4485 return ps.name; 4486 } 4487 } 4488 return null; 4489 } 4490 4491 @Override 4492 public int getUidForSharedUser(String sharedUserName) { 4493 if(sharedUserName == null) { 4494 return -1; 4495 } 4496 // reader 4497 synchronized (mPackages) { 4498 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4499 if (suid == null) { 4500 return -1; 4501 } 4502 return suid.userId; 4503 } 4504 } 4505 4506 @Override 4507 public int getFlagsForUid(int uid) { 4508 synchronized (mPackages) { 4509 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4510 if (obj instanceof SharedUserSetting) { 4511 final SharedUserSetting sus = (SharedUserSetting) obj; 4512 return sus.pkgFlags; 4513 } else if (obj instanceof PackageSetting) { 4514 final PackageSetting ps = (PackageSetting) obj; 4515 return ps.pkgFlags; 4516 } 4517 } 4518 return 0; 4519 } 4520 4521 @Override 4522 public int getPrivateFlagsForUid(int uid) { 4523 synchronized (mPackages) { 4524 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4525 if (obj instanceof SharedUserSetting) { 4526 final SharedUserSetting sus = (SharedUserSetting) obj; 4527 return sus.pkgPrivateFlags; 4528 } else if (obj instanceof PackageSetting) { 4529 final PackageSetting ps = (PackageSetting) obj; 4530 return ps.pkgPrivateFlags; 4531 } 4532 } 4533 return 0; 4534 } 4535 4536 @Override 4537 public boolean isUidPrivileged(int uid) { 4538 uid = UserHandle.getAppId(uid); 4539 // reader 4540 synchronized (mPackages) { 4541 Object obj = mSettings.getUserIdLPr(uid); 4542 if (obj instanceof SharedUserSetting) { 4543 final SharedUserSetting sus = (SharedUserSetting) obj; 4544 final Iterator<PackageSetting> it = sus.packages.iterator(); 4545 while (it.hasNext()) { 4546 if (it.next().isPrivileged()) { 4547 return true; 4548 } 4549 } 4550 } else if (obj instanceof PackageSetting) { 4551 final PackageSetting ps = (PackageSetting) obj; 4552 return ps.isPrivileged(); 4553 } 4554 } 4555 return false; 4556 } 4557 4558 @Override 4559 public String[] getAppOpPermissionPackages(String permissionName) { 4560 synchronized (mPackages) { 4561 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4562 if (pkgs == null) { 4563 return null; 4564 } 4565 return pkgs.toArray(new String[pkgs.size()]); 4566 } 4567 } 4568 4569 @Override 4570 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4571 int flags, int userId) { 4572 if (!sUserManager.exists(userId)) return null; 4573 flags = updateFlagsForResolve(flags, userId, intent); 4574 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4575 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4576 final ResolveInfo bestChoice = 4577 chooseBestActivity(intent, resolvedType, flags, query, userId); 4578 4579 if (isEphemeralAllowed(intent, query, userId)) { 4580 final EphemeralResolveInfo ai = 4581 getEphemeralResolveInfo(intent, resolvedType, userId); 4582 if (ai != null) { 4583 if (DEBUG_EPHEMERAL) { 4584 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4585 } 4586 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4587 bestChoice.ephemeralResolveInfo = ai; 4588 } 4589 } 4590 return bestChoice; 4591 } 4592 4593 @Override 4594 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4595 IntentFilter filter, int match, ComponentName activity) { 4596 final int userId = UserHandle.getCallingUserId(); 4597 if (DEBUG_PREFERRED) { 4598 Log.v(TAG, "setLastChosenActivity intent=" + intent 4599 + " resolvedType=" + resolvedType 4600 + " flags=" + flags 4601 + " filter=" + filter 4602 + " match=" + match 4603 + " activity=" + activity); 4604 filter.dump(new PrintStreamPrinter(System.out), " "); 4605 } 4606 intent.setComponent(null); 4607 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4608 // Find any earlier preferred or last chosen entries and nuke them 4609 findPreferredActivity(intent, resolvedType, 4610 flags, query, 0, false, true, false, userId); 4611 // Add the new activity as the last chosen for this filter 4612 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4613 "Setting last chosen"); 4614 } 4615 4616 @Override 4617 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4618 final int userId = UserHandle.getCallingUserId(); 4619 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4620 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4621 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4622 false, false, false, userId); 4623 } 4624 4625 4626 private boolean isEphemeralAllowed( 4627 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4628 // Short circuit and return early if possible. 4629 if (DISABLE_EPHEMERAL_APPS) { 4630 return false; 4631 } 4632 final int callingUser = UserHandle.getCallingUserId(); 4633 if (callingUser != UserHandle.USER_SYSTEM) { 4634 return false; 4635 } 4636 if (mEphemeralResolverConnection == null) { 4637 return false; 4638 } 4639 if (intent.getComponent() != null) { 4640 return false; 4641 } 4642 if (intent.getPackage() != null) { 4643 return false; 4644 } 4645 final boolean isWebUri = hasWebURI(intent); 4646 if (!isWebUri) { 4647 return false; 4648 } 4649 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4650 synchronized (mPackages) { 4651 final int count = resolvedActivites.size(); 4652 for (int n = 0; n < count; n++) { 4653 ResolveInfo info = resolvedActivites.get(n); 4654 String packageName = info.activityInfo.packageName; 4655 PackageSetting ps = mSettings.mPackages.get(packageName); 4656 if (ps != null) { 4657 // Try to get the status from User settings first 4658 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4659 int status = (int) (packedStatus >> 32); 4660 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4661 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4662 if (DEBUG_EPHEMERAL) { 4663 Slog.v(TAG, "DENY ephemeral apps;" 4664 + " pkg: " + packageName + ", status: " + status); 4665 } 4666 return false; 4667 } 4668 } 4669 } 4670 } 4671 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4672 return true; 4673 } 4674 4675 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4676 int userId) { 4677 MessageDigest digest = null; 4678 try { 4679 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4680 } catch (NoSuchAlgorithmException e) { 4681 // If we can't create a digest, ignore ephemeral apps. 4682 return null; 4683 } 4684 4685 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4686 final byte[] digestBytes = digest.digest(hostBytes); 4687 int shaPrefix = 4688 digestBytes[0] << 24 4689 | digestBytes[1] << 16 4690 | digestBytes[2] << 8 4691 | digestBytes[3] << 0; 4692 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4693 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4694 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4695 // No hash prefix match; there are no ephemeral apps for this domain. 4696 return null; 4697 } 4698 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4699 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4700 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4701 continue; 4702 } 4703 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4704 // No filters; this should never happen. 4705 if (filters.isEmpty()) { 4706 continue; 4707 } 4708 // We have a domain match; resolve the filters to see if anything matches. 4709 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4710 for (int j = filters.size() - 1; j >= 0; --j) { 4711 final EphemeralResolveIntentInfo intentInfo = 4712 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4713 ephemeralResolver.addFilter(intentInfo); 4714 } 4715 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4716 intent, resolvedType, false /*defaultOnly*/, userId); 4717 if (!matchedResolveInfoList.isEmpty()) { 4718 return matchedResolveInfoList.get(0); 4719 } 4720 } 4721 // Hash or filter mis-match; no ephemeral apps for this domain. 4722 return null; 4723 } 4724 4725 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4726 int flags, List<ResolveInfo> query, int userId) { 4727 if (query != null) { 4728 final int N = query.size(); 4729 if (N == 1) { 4730 return query.get(0); 4731 } else if (N > 1) { 4732 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4733 // If there is more than one activity with the same priority, 4734 // then let the user decide between them. 4735 ResolveInfo r0 = query.get(0); 4736 ResolveInfo r1 = query.get(1); 4737 if (DEBUG_INTENT_MATCHING || debug) { 4738 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4739 + r1.activityInfo.name + "=" + r1.priority); 4740 } 4741 // If the first activity has a higher priority, or a different 4742 // default, then it is always desirable to pick it. 4743 if (r0.priority != r1.priority 4744 || r0.preferredOrder != r1.preferredOrder 4745 || r0.isDefault != r1.isDefault) { 4746 return query.get(0); 4747 } 4748 // If we have saved a preference for a preferred activity for 4749 // this Intent, use that. 4750 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4751 flags, query, r0.priority, true, false, debug, userId); 4752 if (ri != null) { 4753 return ri; 4754 } 4755 ri = new ResolveInfo(mResolveInfo); 4756 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4757 ri.activityInfo.applicationInfo = new ApplicationInfo( 4758 ri.activityInfo.applicationInfo); 4759 if (userId != 0) { 4760 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4761 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4762 } 4763 // Make sure that the resolver is displayable in car mode 4764 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4765 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4766 return ri; 4767 } 4768 } 4769 return null; 4770 } 4771 4772 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4773 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4774 final int N = query.size(); 4775 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4776 .get(userId); 4777 // Get the list of persistent preferred activities that handle the intent 4778 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4779 List<PersistentPreferredActivity> pprefs = ppir != null 4780 ? ppir.queryIntent(intent, resolvedType, 4781 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4782 : null; 4783 if (pprefs != null && pprefs.size() > 0) { 4784 final int M = pprefs.size(); 4785 for (int i=0; i<M; i++) { 4786 final PersistentPreferredActivity ppa = pprefs.get(i); 4787 if (DEBUG_PREFERRED || debug) { 4788 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4789 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4790 + "\n component=" + ppa.mComponent); 4791 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4792 } 4793 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4794 flags | MATCH_DISABLED_COMPONENTS, userId); 4795 if (DEBUG_PREFERRED || debug) { 4796 Slog.v(TAG, "Found persistent preferred activity:"); 4797 if (ai != null) { 4798 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4799 } else { 4800 Slog.v(TAG, " null"); 4801 } 4802 } 4803 if (ai == null) { 4804 // This previously registered persistent preferred activity 4805 // component is no longer known. Ignore it and do NOT remove it. 4806 continue; 4807 } 4808 for (int j=0; j<N; j++) { 4809 final ResolveInfo ri = query.get(j); 4810 if (!ri.activityInfo.applicationInfo.packageName 4811 .equals(ai.applicationInfo.packageName)) { 4812 continue; 4813 } 4814 if (!ri.activityInfo.name.equals(ai.name)) { 4815 continue; 4816 } 4817 // Found a persistent preference that can handle the intent. 4818 if (DEBUG_PREFERRED || debug) { 4819 Slog.v(TAG, "Returning persistent preferred activity: " + 4820 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4821 } 4822 return ri; 4823 } 4824 } 4825 } 4826 return null; 4827 } 4828 4829 // TODO: handle preferred activities missing while user has amnesia 4830 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4831 List<ResolveInfo> query, int priority, boolean always, 4832 boolean removeMatches, boolean debug, int userId) { 4833 if (!sUserManager.exists(userId)) return null; 4834 flags = updateFlagsForResolve(flags, userId, intent); 4835 // writer 4836 synchronized (mPackages) { 4837 if (intent.getSelector() != null) { 4838 intent = intent.getSelector(); 4839 } 4840 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4841 4842 // Try to find a matching persistent preferred activity. 4843 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4844 debug, userId); 4845 4846 // If a persistent preferred activity matched, use it. 4847 if (pri != null) { 4848 return pri; 4849 } 4850 4851 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4852 // Get the list of preferred activities that handle the intent 4853 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4854 List<PreferredActivity> prefs = pir != null 4855 ? pir.queryIntent(intent, resolvedType, 4856 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4857 : null; 4858 if (prefs != null && prefs.size() > 0) { 4859 boolean changed = false; 4860 try { 4861 // First figure out how good the original match set is. 4862 // We will only allow preferred activities that came 4863 // from the same match quality. 4864 int match = 0; 4865 4866 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4867 4868 final int N = query.size(); 4869 for (int j=0; j<N; j++) { 4870 final ResolveInfo ri = query.get(j); 4871 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4872 + ": 0x" + Integer.toHexString(match)); 4873 if (ri.match > match) { 4874 match = ri.match; 4875 } 4876 } 4877 4878 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4879 + Integer.toHexString(match)); 4880 4881 match &= IntentFilter.MATCH_CATEGORY_MASK; 4882 final int M = prefs.size(); 4883 for (int i=0; i<M; i++) { 4884 final PreferredActivity pa = prefs.get(i); 4885 if (DEBUG_PREFERRED || debug) { 4886 Slog.v(TAG, "Checking PreferredActivity ds=" 4887 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4888 + "\n component=" + pa.mPref.mComponent); 4889 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4890 } 4891 if (pa.mPref.mMatch != match) { 4892 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4893 + Integer.toHexString(pa.mPref.mMatch)); 4894 continue; 4895 } 4896 // If it's not an "always" type preferred activity and that's what we're 4897 // looking for, skip it. 4898 if (always && !pa.mPref.mAlways) { 4899 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4900 continue; 4901 } 4902 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4903 flags | MATCH_DISABLED_COMPONENTS, userId); 4904 if (DEBUG_PREFERRED || debug) { 4905 Slog.v(TAG, "Found preferred activity:"); 4906 if (ai != null) { 4907 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4908 } else { 4909 Slog.v(TAG, " null"); 4910 } 4911 } 4912 if (ai == null) { 4913 // This previously registered preferred activity 4914 // component is no longer known. Most likely an update 4915 // to the app was installed and in the new version this 4916 // component no longer exists. Clean it up by removing 4917 // it from the preferred activities list, and skip it. 4918 Slog.w(TAG, "Removing dangling preferred activity: " 4919 + pa.mPref.mComponent); 4920 pir.removeFilter(pa); 4921 changed = true; 4922 continue; 4923 } 4924 for (int j=0; j<N; j++) { 4925 final ResolveInfo ri = query.get(j); 4926 if (!ri.activityInfo.applicationInfo.packageName 4927 .equals(ai.applicationInfo.packageName)) { 4928 continue; 4929 } 4930 if (!ri.activityInfo.name.equals(ai.name)) { 4931 continue; 4932 } 4933 4934 if (removeMatches) { 4935 pir.removeFilter(pa); 4936 changed = true; 4937 if (DEBUG_PREFERRED) { 4938 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4939 } 4940 break; 4941 } 4942 4943 // Okay we found a previously set preferred or last chosen app. 4944 // If the result set is different from when this 4945 // was created, we need to clear it and re-ask the 4946 // user their preference, if we're looking for an "always" type entry. 4947 if (always && !pa.mPref.sameSet(query)) { 4948 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4949 + intent + " type " + resolvedType); 4950 if (DEBUG_PREFERRED) { 4951 Slog.v(TAG, "Removing preferred activity since set changed " 4952 + pa.mPref.mComponent); 4953 } 4954 pir.removeFilter(pa); 4955 // Re-add the filter as a "last chosen" entry (!always) 4956 PreferredActivity lastChosen = new PreferredActivity( 4957 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4958 pir.addFilter(lastChosen); 4959 changed = true; 4960 return null; 4961 } 4962 4963 // Yay! Either the set matched or we're looking for the last chosen 4964 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4965 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4966 return ri; 4967 } 4968 } 4969 } finally { 4970 if (changed) { 4971 if (DEBUG_PREFERRED) { 4972 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4973 } 4974 scheduleWritePackageRestrictionsLocked(userId); 4975 } 4976 } 4977 } 4978 } 4979 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4980 return null; 4981 } 4982 4983 /* 4984 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4985 */ 4986 @Override 4987 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4988 int targetUserId) { 4989 mContext.enforceCallingOrSelfPermission( 4990 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4991 List<CrossProfileIntentFilter> matches = 4992 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4993 if (matches != null) { 4994 int size = matches.size(); 4995 for (int i = 0; i < size; i++) { 4996 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4997 } 4998 } 4999 if (hasWebURI(intent)) { 5000 // cross-profile app linking works only towards the parent. 5001 final UserInfo parent = getProfileParent(sourceUserId); 5002 synchronized(mPackages) { 5003 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5004 intent, resolvedType, 0, sourceUserId, parent.id); 5005 return xpDomainInfo != null; 5006 } 5007 } 5008 return false; 5009 } 5010 5011 private UserInfo getProfileParent(int userId) { 5012 final long identity = Binder.clearCallingIdentity(); 5013 try { 5014 return sUserManager.getProfileParent(userId); 5015 } finally { 5016 Binder.restoreCallingIdentity(identity); 5017 } 5018 } 5019 5020 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5021 String resolvedType, int userId) { 5022 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5023 if (resolver != null) { 5024 return resolver.queryIntent(intent, resolvedType, false, userId); 5025 } 5026 return null; 5027 } 5028 5029 @Override 5030 public List<ResolveInfo> queryIntentActivities(Intent intent, 5031 String resolvedType, int flags, int userId) { 5032 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5033 flags = updateFlagsForResolve(flags, userId, intent); 5034 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 5035 ComponentName comp = intent.getComponent(); 5036 if (comp == null) { 5037 if (intent.getSelector() != null) { 5038 intent = intent.getSelector(); 5039 comp = intent.getComponent(); 5040 } 5041 } 5042 5043 if (comp != null) { 5044 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5045 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5046 if (ai != null) { 5047 final ResolveInfo ri = new ResolveInfo(); 5048 ri.activityInfo = ai; 5049 list.add(ri); 5050 } 5051 return list; 5052 } 5053 5054 // reader 5055 synchronized (mPackages) { 5056 final String pkgName = intent.getPackage(); 5057 if (pkgName == null) { 5058 List<CrossProfileIntentFilter> matchingFilters = 5059 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5060 // Check for results that need to skip the current profile. 5061 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5062 resolvedType, flags, userId); 5063 if (xpResolveInfo != null) { 5064 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5065 result.add(xpResolveInfo); 5066 return filterIfNotSystemUser(result, userId); 5067 } 5068 5069 // Check for results in the current profile. 5070 List<ResolveInfo> result = mActivities.queryIntent( 5071 intent, resolvedType, flags, userId); 5072 result = filterIfNotSystemUser(result, userId); 5073 5074 // Check for cross profile results. 5075 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5076 xpResolveInfo = queryCrossProfileIntents( 5077 matchingFilters, intent, resolvedType, flags, userId, 5078 hasNonNegativePriorityResult); 5079 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5080 boolean isVisibleToUser = filterIfNotSystemUser( 5081 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5082 if (isVisibleToUser) { 5083 result.add(xpResolveInfo); 5084 Collections.sort(result, mResolvePrioritySorter); 5085 } 5086 } 5087 if (hasWebURI(intent)) { 5088 CrossProfileDomainInfo xpDomainInfo = null; 5089 final UserInfo parent = getProfileParent(userId); 5090 if (parent != null) { 5091 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5092 flags, userId, parent.id); 5093 } 5094 if (xpDomainInfo != null) { 5095 if (xpResolveInfo != null) { 5096 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5097 // in the result. 5098 result.remove(xpResolveInfo); 5099 } 5100 if (result.size() == 0) { 5101 result.add(xpDomainInfo.resolveInfo); 5102 return result; 5103 } 5104 } else if (result.size() <= 1) { 5105 return result; 5106 } 5107 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5108 xpDomainInfo, userId); 5109 Collections.sort(result, mResolvePrioritySorter); 5110 } 5111 return result; 5112 } 5113 final PackageParser.Package pkg = mPackages.get(pkgName); 5114 if (pkg != null) { 5115 return filterIfNotSystemUser( 5116 mActivities.queryIntentForPackage( 5117 intent, resolvedType, flags, pkg.activities, userId), 5118 userId); 5119 } 5120 return new ArrayList<ResolveInfo>(); 5121 } 5122 } 5123 5124 private static class CrossProfileDomainInfo { 5125 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5126 ResolveInfo resolveInfo; 5127 /* Best domain verification status of the activities found in the other profile */ 5128 int bestDomainVerificationStatus; 5129 } 5130 5131 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5132 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5133 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5134 sourceUserId)) { 5135 return null; 5136 } 5137 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5138 resolvedType, flags, parentUserId); 5139 5140 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5141 return null; 5142 } 5143 CrossProfileDomainInfo result = null; 5144 int size = resultTargetUser.size(); 5145 for (int i = 0; i < size; i++) { 5146 ResolveInfo riTargetUser = resultTargetUser.get(i); 5147 // Intent filter verification is only for filters that specify a host. So don't return 5148 // those that handle all web uris. 5149 if (riTargetUser.handleAllWebDataURI) { 5150 continue; 5151 } 5152 String packageName = riTargetUser.activityInfo.packageName; 5153 PackageSetting ps = mSettings.mPackages.get(packageName); 5154 if (ps == null) { 5155 continue; 5156 } 5157 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5158 int status = (int)(verificationState >> 32); 5159 if (result == null) { 5160 result = new CrossProfileDomainInfo(); 5161 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5162 sourceUserId, parentUserId); 5163 result.bestDomainVerificationStatus = status; 5164 } else { 5165 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5166 result.bestDomainVerificationStatus); 5167 } 5168 } 5169 // Don't consider matches with status NEVER across profiles. 5170 if (result != null && result.bestDomainVerificationStatus 5171 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5172 return null; 5173 } 5174 return result; 5175 } 5176 5177 /** 5178 * Verification statuses are ordered from the worse to the best, except for 5179 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5180 */ 5181 private int bestDomainVerificationStatus(int status1, int status2) { 5182 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5183 return status2; 5184 } 5185 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5186 return status1; 5187 } 5188 return (int) MathUtils.max(status1, status2); 5189 } 5190 5191 private boolean isUserEnabled(int userId) { 5192 long callingId = Binder.clearCallingIdentity(); 5193 try { 5194 UserInfo userInfo = sUserManager.getUserInfo(userId); 5195 return userInfo != null && userInfo.isEnabled(); 5196 } finally { 5197 Binder.restoreCallingIdentity(callingId); 5198 } 5199 } 5200 5201 /** 5202 * Filter out activities with systemUserOnly flag set, when current user is not System. 5203 * 5204 * @return filtered list 5205 */ 5206 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5207 if (userId == UserHandle.USER_SYSTEM) { 5208 return resolveInfos; 5209 } 5210 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5211 ResolveInfo info = resolveInfos.get(i); 5212 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5213 resolveInfos.remove(i); 5214 } 5215 } 5216 return resolveInfos; 5217 } 5218 5219 /** 5220 * @param resolveInfos list of resolve infos in descending priority order 5221 * @return if the list contains a resolve info with non-negative priority 5222 */ 5223 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5224 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5225 } 5226 5227 private static boolean hasWebURI(Intent intent) { 5228 if (intent.getData() == null) { 5229 return false; 5230 } 5231 final String scheme = intent.getScheme(); 5232 if (TextUtils.isEmpty(scheme)) { 5233 return false; 5234 } 5235 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5236 } 5237 5238 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5239 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5240 int userId) { 5241 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5242 5243 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5244 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5245 candidates.size()); 5246 } 5247 5248 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5249 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5250 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5251 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5252 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5253 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5254 5255 synchronized (mPackages) { 5256 final int count = candidates.size(); 5257 // First, try to use linked apps. Partition the candidates into four lists: 5258 // one for the final results, one for the "do not use ever", one for "undefined status" 5259 // and finally one for "browser app type". 5260 for (int n=0; n<count; n++) { 5261 ResolveInfo info = candidates.get(n); 5262 String packageName = info.activityInfo.packageName; 5263 PackageSetting ps = mSettings.mPackages.get(packageName); 5264 if (ps != null) { 5265 // Add to the special match all list (Browser use case) 5266 if (info.handleAllWebDataURI) { 5267 matchAllList.add(info); 5268 continue; 5269 } 5270 // Try to get the status from User settings first 5271 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5272 int status = (int)(packedStatus >> 32); 5273 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5274 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5275 if (DEBUG_DOMAIN_VERIFICATION) { 5276 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5277 + " : linkgen=" + linkGeneration); 5278 } 5279 // Use link-enabled generation as preferredOrder, i.e. 5280 // prefer newly-enabled over earlier-enabled. 5281 info.preferredOrder = linkGeneration; 5282 alwaysList.add(info); 5283 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5284 if (DEBUG_DOMAIN_VERIFICATION) { 5285 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5286 } 5287 neverList.add(info); 5288 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5289 if (DEBUG_DOMAIN_VERIFICATION) { 5290 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5291 } 5292 alwaysAskList.add(info); 5293 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5294 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5295 if (DEBUG_DOMAIN_VERIFICATION) { 5296 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5297 } 5298 undefinedList.add(info); 5299 } 5300 } 5301 } 5302 5303 // We'll want to include browser possibilities in a few cases 5304 boolean includeBrowser = false; 5305 5306 // First try to add the "always" resolution(s) for the current user, if any 5307 if (alwaysList.size() > 0) { 5308 result.addAll(alwaysList); 5309 } else { 5310 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5311 result.addAll(undefinedList); 5312 // Maybe add one for the other profile. 5313 if (xpDomainInfo != null && ( 5314 xpDomainInfo.bestDomainVerificationStatus 5315 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5316 result.add(xpDomainInfo.resolveInfo); 5317 } 5318 includeBrowser = true; 5319 } 5320 5321 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5322 // If there were 'always' entries their preferred order has been set, so we also 5323 // back that off to make the alternatives equivalent 5324 if (alwaysAskList.size() > 0) { 5325 for (ResolveInfo i : result) { 5326 i.preferredOrder = 0; 5327 } 5328 result.addAll(alwaysAskList); 5329 includeBrowser = true; 5330 } 5331 5332 if (includeBrowser) { 5333 // Also add browsers (all of them or only the default one) 5334 if (DEBUG_DOMAIN_VERIFICATION) { 5335 Slog.v(TAG, " ...including browsers in candidate set"); 5336 } 5337 if ((matchFlags & MATCH_ALL) != 0) { 5338 result.addAll(matchAllList); 5339 } else { 5340 // Browser/generic handling case. If there's a default browser, go straight 5341 // to that (but only if there is no other higher-priority match). 5342 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5343 int maxMatchPrio = 0; 5344 ResolveInfo defaultBrowserMatch = null; 5345 final int numCandidates = matchAllList.size(); 5346 for (int n = 0; n < numCandidates; n++) { 5347 ResolveInfo info = matchAllList.get(n); 5348 // track the highest overall match priority... 5349 if (info.priority > maxMatchPrio) { 5350 maxMatchPrio = info.priority; 5351 } 5352 // ...and the highest-priority default browser match 5353 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5354 if (defaultBrowserMatch == null 5355 || (defaultBrowserMatch.priority < info.priority)) { 5356 if (debug) { 5357 Slog.v(TAG, "Considering default browser match " + info); 5358 } 5359 defaultBrowserMatch = info; 5360 } 5361 } 5362 } 5363 if (defaultBrowserMatch != null 5364 && defaultBrowserMatch.priority >= maxMatchPrio 5365 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5366 { 5367 if (debug) { 5368 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5369 } 5370 result.add(defaultBrowserMatch); 5371 } else { 5372 result.addAll(matchAllList); 5373 } 5374 } 5375 5376 // If there is nothing selected, add all candidates and remove the ones that the user 5377 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5378 if (result.size() == 0) { 5379 result.addAll(candidates); 5380 result.removeAll(neverList); 5381 } 5382 } 5383 } 5384 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5385 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5386 result.size()); 5387 for (ResolveInfo info : result) { 5388 Slog.v(TAG, " + " + info.activityInfo); 5389 } 5390 } 5391 return result; 5392 } 5393 5394 // Returns a packed value as a long: 5395 // 5396 // high 'int'-sized word: link status: undefined/ask/never/always. 5397 // low 'int'-sized word: relative priority among 'always' results. 5398 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5399 long result = ps.getDomainVerificationStatusForUser(userId); 5400 // if none available, get the master status 5401 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5402 if (ps.getIntentFilterVerificationInfo() != null) { 5403 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5404 } 5405 } 5406 return result; 5407 } 5408 5409 private ResolveInfo querySkipCurrentProfileIntents( 5410 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5411 int flags, int sourceUserId) { 5412 if (matchingFilters != null) { 5413 int size = matchingFilters.size(); 5414 for (int i = 0; i < size; i ++) { 5415 CrossProfileIntentFilter filter = matchingFilters.get(i); 5416 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5417 // Checking if there are activities in the target user that can handle the 5418 // intent. 5419 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5420 resolvedType, flags, sourceUserId); 5421 if (resolveInfo != null) { 5422 return resolveInfo; 5423 } 5424 } 5425 } 5426 } 5427 return null; 5428 } 5429 5430 // Return matching ResolveInfo in target user if any. 5431 private ResolveInfo queryCrossProfileIntents( 5432 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5433 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5434 if (matchingFilters != null) { 5435 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5436 // match the same intent. For performance reasons, it is better not to 5437 // run queryIntent twice for the same userId 5438 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5439 int size = matchingFilters.size(); 5440 for (int i = 0; i < size; i++) { 5441 CrossProfileIntentFilter filter = matchingFilters.get(i); 5442 int targetUserId = filter.getTargetUserId(); 5443 boolean skipCurrentProfile = 5444 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5445 boolean skipCurrentProfileIfNoMatchFound = 5446 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5447 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5448 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5449 // Checking if there are activities in the target user that can handle the 5450 // intent. 5451 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5452 resolvedType, flags, sourceUserId); 5453 if (resolveInfo != null) return resolveInfo; 5454 alreadyTriedUserIds.put(targetUserId, true); 5455 } 5456 } 5457 } 5458 return null; 5459 } 5460 5461 /** 5462 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5463 * will forward the intent to the filter's target user. 5464 * Otherwise, returns null. 5465 */ 5466 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5467 String resolvedType, int flags, int sourceUserId) { 5468 int targetUserId = filter.getTargetUserId(); 5469 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5470 resolvedType, flags, targetUserId); 5471 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5472 // If all the matches in the target profile are suspended, return null. 5473 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5474 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5475 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5476 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5477 targetUserId); 5478 } 5479 } 5480 } 5481 return null; 5482 } 5483 5484 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5485 int sourceUserId, int targetUserId) { 5486 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5487 long ident = Binder.clearCallingIdentity(); 5488 boolean targetIsProfile; 5489 try { 5490 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5491 } finally { 5492 Binder.restoreCallingIdentity(ident); 5493 } 5494 String className; 5495 if (targetIsProfile) { 5496 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5497 } else { 5498 className = FORWARD_INTENT_TO_PARENT; 5499 } 5500 ComponentName forwardingActivityComponentName = new ComponentName( 5501 mAndroidApplication.packageName, className); 5502 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5503 sourceUserId); 5504 if (!targetIsProfile) { 5505 forwardingActivityInfo.showUserIcon = targetUserId; 5506 forwardingResolveInfo.noResourceId = true; 5507 } 5508 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5509 forwardingResolveInfo.priority = 0; 5510 forwardingResolveInfo.preferredOrder = 0; 5511 forwardingResolveInfo.match = 0; 5512 forwardingResolveInfo.isDefault = true; 5513 forwardingResolveInfo.filter = filter; 5514 forwardingResolveInfo.targetUserId = targetUserId; 5515 return forwardingResolveInfo; 5516 } 5517 5518 @Override 5519 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5520 Intent[] specifics, String[] specificTypes, Intent intent, 5521 String resolvedType, int flags, int userId) { 5522 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5523 flags = updateFlagsForResolve(flags, userId, intent); 5524 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5525 false, "query intent activity options"); 5526 final String resultsAction = intent.getAction(); 5527 5528 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5529 | PackageManager.GET_RESOLVED_FILTER, userId); 5530 5531 if (DEBUG_INTENT_MATCHING) { 5532 Log.v(TAG, "Query " + intent + ": " + results); 5533 } 5534 5535 int specificsPos = 0; 5536 int N; 5537 5538 // todo: note that the algorithm used here is O(N^2). This 5539 // isn't a problem in our current environment, but if we start running 5540 // into situations where we have more than 5 or 10 matches then this 5541 // should probably be changed to something smarter... 5542 5543 // First we go through and resolve each of the specific items 5544 // that were supplied, taking care of removing any corresponding 5545 // duplicate items in the generic resolve list. 5546 if (specifics != null) { 5547 for (int i=0; i<specifics.length; i++) { 5548 final Intent sintent = specifics[i]; 5549 if (sintent == null) { 5550 continue; 5551 } 5552 5553 if (DEBUG_INTENT_MATCHING) { 5554 Log.v(TAG, "Specific #" + i + ": " + sintent); 5555 } 5556 5557 String action = sintent.getAction(); 5558 if (resultsAction != null && resultsAction.equals(action)) { 5559 // If this action was explicitly requested, then don't 5560 // remove things that have it. 5561 action = null; 5562 } 5563 5564 ResolveInfo ri = null; 5565 ActivityInfo ai = null; 5566 5567 ComponentName comp = sintent.getComponent(); 5568 if (comp == null) { 5569 ri = resolveIntent( 5570 sintent, 5571 specificTypes != null ? specificTypes[i] : null, 5572 flags, userId); 5573 if (ri == null) { 5574 continue; 5575 } 5576 if (ri == mResolveInfo) { 5577 // ACK! Must do something better with this. 5578 } 5579 ai = ri.activityInfo; 5580 comp = new ComponentName(ai.applicationInfo.packageName, 5581 ai.name); 5582 } else { 5583 ai = getActivityInfo(comp, flags, userId); 5584 if (ai == null) { 5585 continue; 5586 } 5587 } 5588 5589 // Look for any generic query activities that are duplicates 5590 // of this specific one, and remove them from the results. 5591 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5592 N = results.size(); 5593 int j; 5594 for (j=specificsPos; j<N; j++) { 5595 ResolveInfo sri = results.get(j); 5596 if ((sri.activityInfo.name.equals(comp.getClassName()) 5597 && sri.activityInfo.applicationInfo.packageName.equals( 5598 comp.getPackageName())) 5599 || (action != null && sri.filter.matchAction(action))) { 5600 results.remove(j); 5601 if (DEBUG_INTENT_MATCHING) Log.v( 5602 TAG, "Removing duplicate item from " + j 5603 + " due to specific " + specificsPos); 5604 if (ri == null) { 5605 ri = sri; 5606 } 5607 j--; 5608 N--; 5609 } 5610 } 5611 5612 // Add this specific item to its proper place. 5613 if (ri == null) { 5614 ri = new ResolveInfo(); 5615 ri.activityInfo = ai; 5616 } 5617 results.add(specificsPos, ri); 5618 ri.specificIndex = i; 5619 specificsPos++; 5620 } 5621 } 5622 5623 // Now we go through the remaining generic results and remove any 5624 // duplicate actions that are found here. 5625 N = results.size(); 5626 for (int i=specificsPos; i<N-1; i++) { 5627 final ResolveInfo rii = results.get(i); 5628 if (rii.filter == null) { 5629 continue; 5630 } 5631 5632 // Iterate over all of the actions of this result's intent 5633 // filter... typically this should be just one. 5634 final Iterator<String> it = rii.filter.actionsIterator(); 5635 if (it == null) { 5636 continue; 5637 } 5638 while (it.hasNext()) { 5639 final String action = it.next(); 5640 if (resultsAction != null && resultsAction.equals(action)) { 5641 // If this action was explicitly requested, then don't 5642 // remove things that have it. 5643 continue; 5644 } 5645 for (int j=i+1; j<N; j++) { 5646 final ResolveInfo rij = results.get(j); 5647 if (rij.filter != null && rij.filter.hasAction(action)) { 5648 results.remove(j); 5649 if (DEBUG_INTENT_MATCHING) Log.v( 5650 TAG, "Removing duplicate item from " + j 5651 + " due to action " + action + " at " + i); 5652 j--; 5653 N--; 5654 } 5655 } 5656 } 5657 5658 // If the caller didn't request filter information, drop it now 5659 // so we don't have to marshall/unmarshall it. 5660 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5661 rii.filter = null; 5662 } 5663 } 5664 5665 // Filter out the caller activity if so requested. 5666 if (caller != null) { 5667 N = results.size(); 5668 for (int i=0; i<N; i++) { 5669 ActivityInfo ainfo = results.get(i).activityInfo; 5670 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5671 && caller.getClassName().equals(ainfo.name)) { 5672 results.remove(i); 5673 break; 5674 } 5675 } 5676 } 5677 5678 // If the caller didn't request filter information, 5679 // drop them now so we don't have to 5680 // marshall/unmarshall it. 5681 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5682 N = results.size(); 5683 for (int i=0; i<N; i++) { 5684 results.get(i).filter = null; 5685 } 5686 } 5687 5688 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5689 return results; 5690 } 5691 5692 @Override 5693 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5694 int userId) { 5695 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5696 flags = updateFlagsForResolve(flags, userId, intent); 5697 ComponentName comp = intent.getComponent(); 5698 if (comp == null) { 5699 if (intent.getSelector() != null) { 5700 intent = intent.getSelector(); 5701 comp = intent.getComponent(); 5702 } 5703 } 5704 if (comp != null) { 5705 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5706 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5707 if (ai != null) { 5708 ResolveInfo ri = new ResolveInfo(); 5709 ri.activityInfo = ai; 5710 list.add(ri); 5711 } 5712 return list; 5713 } 5714 5715 // reader 5716 synchronized (mPackages) { 5717 String pkgName = intent.getPackage(); 5718 if (pkgName == null) { 5719 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5720 } 5721 final PackageParser.Package pkg = mPackages.get(pkgName); 5722 if (pkg != null) { 5723 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5724 userId); 5725 } 5726 return null; 5727 } 5728 } 5729 5730 @Override 5731 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5732 if (!sUserManager.exists(userId)) return null; 5733 flags = updateFlagsForResolve(flags, userId, intent); 5734 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5735 if (query != null) { 5736 if (query.size() >= 1) { 5737 // If there is more than one service with the same priority, 5738 // just arbitrarily pick the first one. 5739 return query.get(0); 5740 } 5741 } 5742 return null; 5743 } 5744 5745 @Override 5746 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5747 int userId) { 5748 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5749 flags = updateFlagsForResolve(flags, userId, intent); 5750 ComponentName comp = intent.getComponent(); 5751 if (comp == null) { 5752 if (intent.getSelector() != null) { 5753 intent = intent.getSelector(); 5754 comp = intent.getComponent(); 5755 } 5756 } 5757 if (comp != null) { 5758 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5759 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5760 if (si != null) { 5761 final ResolveInfo ri = new ResolveInfo(); 5762 ri.serviceInfo = si; 5763 list.add(ri); 5764 } 5765 return list; 5766 } 5767 5768 // reader 5769 synchronized (mPackages) { 5770 String pkgName = intent.getPackage(); 5771 if (pkgName == null) { 5772 return mServices.queryIntent(intent, resolvedType, flags, userId); 5773 } 5774 final PackageParser.Package pkg = mPackages.get(pkgName); 5775 if (pkg != null) { 5776 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5777 userId); 5778 } 5779 return null; 5780 } 5781 } 5782 5783 @Override 5784 public List<ResolveInfo> queryIntentContentProviders( 5785 Intent intent, String resolvedType, int flags, int userId) { 5786 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5787 flags = updateFlagsForResolve(flags, userId, intent); 5788 ComponentName comp = intent.getComponent(); 5789 if (comp == null) { 5790 if (intent.getSelector() != null) { 5791 intent = intent.getSelector(); 5792 comp = intent.getComponent(); 5793 } 5794 } 5795 if (comp != null) { 5796 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5797 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5798 if (pi != null) { 5799 final ResolveInfo ri = new ResolveInfo(); 5800 ri.providerInfo = pi; 5801 list.add(ri); 5802 } 5803 return list; 5804 } 5805 5806 // reader 5807 synchronized (mPackages) { 5808 String pkgName = intent.getPackage(); 5809 if (pkgName == null) { 5810 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5811 } 5812 final PackageParser.Package pkg = mPackages.get(pkgName); 5813 if (pkg != null) { 5814 return mProviders.queryIntentForPackage( 5815 intent, resolvedType, flags, pkg.providers, userId); 5816 } 5817 return null; 5818 } 5819 } 5820 5821 @Override 5822 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5823 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5824 flags = updateFlagsForPackage(flags, userId, null); 5825 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5826 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5827 5828 // writer 5829 synchronized (mPackages) { 5830 ArrayList<PackageInfo> list; 5831 if (listUninstalled) { 5832 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5833 for (PackageSetting ps : mSettings.mPackages.values()) { 5834 PackageInfo pi; 5835 if (ps.pkg != null) { 5836 pi = generatePackageInfo(ps.pkg, flags, userId); 5837 } else { 5838 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5839 } 5840 if (pi != null) { 5841 list.add(pi); 5842 } 5843 } 5844 } else { 5845 list = new ArrayList<PackageInfo>(mPackages.size()); 5846 for (PackageParser.Package p : mPackages.values()) { 5847 PackageInfo pi = generatePackageInfo(p, flags, userId); 5848 if (pi != null) { 5849 list.add(pi); 5850 } 5851 } 5852 } 5853 5854 return new ParceledListSlice<PackageInfo>(list); 5855 } 5856 } 5857 5858 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5859 String[] permissions, boolean[] tmp, int flags, int userId) { 5860 int numMatch = 0; 5861 final PermissionsState permissionsState = ps.getPermissionsState(); 5862 for (int i=0; i<permissions.length; i++) { 5863 final String permission = permissions[i]; 5864 if (permissionsState.hasPermission(permission, userId)) { 5865 tmp[i] = true; 5866 numMatch++; 5867 } else { 5868 tmp[i] = false; 5869 } 5870 } 5871 if (numMatch == 0) { 5872 return; 5873 } 5874 PackageInfo pi; 5875 if (ps.pkg != null) { 5876 pi = generatePackageInfo(ps.pkg, flags, userId); 5877 } else { 5878 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5879 } 5880 // The above might return null in cases of uninstalled apps or install-state 5881 // skew across users/profiles. 5882 if (pi != null) { 5883 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5884 if (numMatch == permissions.length) { 5885 pi.requestedPermissions = permissions; 5886 } else { 5887 pi.requestedPermissions = new String[numMatch]; 5888 numMatch = 0; 5889 for (int i=0; i<permissions.length; i++) { 5890 if (tmp[i]) { 5891 pi.requestedPermissions[numMatch] = permissions[i]; 5892 numMatch++; 5893 } 5894 } 5895 } 5896 } 5897 list.add(pi); 5898 } 5899 } 5900 5901 @Override 5902 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5903 String[] permissions, int flags, int userId) { 5904 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5905 flags = updateFlagsForPackage(flags, userId, permissions); 5906 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5907 5908 // writer 5909 synchronized (mPackages) { 5910 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5911 boolean[] tmpBools = new boolean[permissions.length]; 5912 if (listUninstalled) { 5913 for (PackageSetting ps : mSettings.mPackages.values()) { 5914 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5915 } 5916 } else { 5917 for (PackageParser.Package pkg : mPackages.values()) { 5918 PackageSetting ps = (PackageSetting)pkg.mExtras; 5919 if (ps != null) { 5920 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5921 userId); 5922 } 5923 } 5924 } 5925 5926 return new ParceledListSlice<PackageInfo>(list); 5927 } 5928 } 5929 5930 @Override 5931 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5932 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5933 flags = updateFlagsForApplication(flags, userId, null); 5934 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5935 5936 // writer 5937 synchronized (mPackages) { 5938 ArrayList<ApplicationInfo> list; 5939 if (listUninstalled) { 5940 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5941 for (PackageSetting ps : mSettings.mPackages.values()) { 5942 ApplicationInfo ai; 5943 if (ps.pkg != null) { 5944 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5945 ps.readUserState(userId), userId); 5946 } else { 5947 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5948 } 5949 if (ai != null) { 5950 list.add(ai); 5951 } 5952 } 5953 } else { 5954 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5955 for (PackageParser.Package p : mPackages.values()) { 5956 if (p.mExtras != null) { 5957 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5958 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5959 if (ai != null) { 5960 list.add(ai); 5961 } 5962 } 5963 } 5964 } 5965 5966 return new ParceledListSlice<ApplicationInfo>(list); 5967 } 5968 } 5969 5970 @Override 5971 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5972 if (DISABLE_EPHEMERAL_APPS) { 5973 return null; 5974 } 5975 5976 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5977 "getEphemeralApplications"); 5978 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5979 "getEphemeralApplications"); 5980 synchronized (mPackages) { 5981 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5982 .getEphemeralApplicationsLPw(userId); 5983 if (ephemeralApps != null) { 5984 return new ParceledListSlice<>(ephemeralApps); 5985 } 5986 } 5987 return null; 5988 } 5989 5990 @Override 5991 public boolean isEphemeralApplication(String packageName, int userId) { 5992 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5993 "isEphemeral"); 5994 if (DISABLE_EPHEMERAL_APPS) { 5995 return false; 5996 } 5997 5998 if (!isCallerSameApp(packageName)) { 5999 return false; 6000 } 6001 synchronized (mPackages) { 6002 PackageParser.Package pkg = mPackages.get(packageName); 6003 if (pkg != null) { 6004 return pkg.applicationInfo.isEphemeralApp(); 6005 } 6006 } 6007 return false; 6008 } 6009 6010 @Override 6011 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6012 if (DISABLE_EPHEMERAL_APPS) { 6013 return null; 6014 } 6015 6016 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 6017 "getCookie"); 6018 if (!isCallerSameApp(packageName)) { 6019 return null; 6020 } 6021 synchronized (mPackages) { 6022 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6023 packageName, userId); 6024 } 6025 } 6026 6027 @Override 6028 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6029 if (DISABLE_EPHEMERAL_APPS) { 6030 return true; 6031 } 6032 6033 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 6034 "setCookie"); 6035 if (!isCallerSameApp(packageName)) { 6036 return false; 6037 } 6038 synchronized (mPackages) { 6039 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6040 packageName, cookie, userId); 6041 } 6042 } 6043 6044 @Override 6045 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6046 if (DISABLE_EPHEMERAL_APPS) { 6047 return null; 6048 } 6049 6050 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6051 "getEphemeralApplicationIcon"); 6052 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 6053 "getEphemeralApplicationIcon"); 6054 synchronized (mPackages) { 6055 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6056 packageName, userId); 6057 } 6058 } 6059 6060 private boolean isCallerSameApp(String packageName) { 6061 PackageParser.Package pkg = mPackages.get(packageName); 6062 return pkg != null 6063 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6064 } 6065 6066 public List<ApplicationInfo> getPersistentApplications(int flags) { 6067 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6068 6069 // reader 6070 synchronized (mPackages) { 6071 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6072 final int userId = UserHandle.getCallingUserId(); 6073 while (i.hasNext()) { 6074 final PackageParser.Package p = i.next(); 6075 if (p.applicationInfo != null 6076 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 6077 && (!mSafeMode || isSystemApp(p))) { 6078 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6079 if (ps != null) { 6080 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6081 ps.readUserState(userId), userId); 6082 if (ai != null) { 6083 finalList.add(ai); 6084 } 6085 } 6086 } 6087 } 6088 } 6089 6090 return finalList; 6091 } 6092 6093 @Override 6094 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6095 if (!sUserManager.exists(userId)) return null; 6096 flags = updateFlagsForComponent(flags, userId, name); 6097 // reader 6098 synchronized (mPackages) { 6099 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6100 PackageSetting ps = provider != null 6101 ? mSettings.mPackages.get(provider.owner.packageName) 6102 : null; 6103 return ps != null 6104 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6105 ? PackageParser.generateProviderInfo(provider, flags, 6106 ps.readUserState(userId), userId) 6107 : null; 6108 } 6109 } 6110 6111 /** 6112 * @deprecated 6113 */ 6114 @Deprecated 6115 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6116 // reader 6117 synchronized (mPackages) { 6118 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6119 .entrySet().iterator(); 6120 final int userId = UserHandle.getCallingUserId(); 6121 while (i.hasNext()) { 6122 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6123 PackageParser.Provider p = entry.getValue(); 6124 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6125 6126 if (ps != null && p.syncable 6127 && (!mSafeMode || (p.info.applicationInfo.flags 6128 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6129 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6130 ps.readUserState(userId), userId); 6131 if (info != null) { 6132 outNames.add(entry.getKey()); 6133 outInfo.add(info); 6134 } 6135 } 6136 } 6137 } 6138 } 6139 6140 @Override 6141 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6142 int uid, int flags) { 6143 final int userId = processName != null ? UserHandle.getUserId(uid) 6144 : UserHandle.getCallingUserId(); 6145 if (!sUserManager.exists(userId)) return null; 6146 flags = updateFlagsForComponent(flags, userId, processName); 6147 6148 ArrayList<ProviderInfo> finalList = null; 6149 // reader 6150 synchronized (mPackages) { 6151 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6152 while (i.hasNext()) { 6153 final PackageParser.Provider p = i.next(); 6154 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6155 if (ps != null && p.info.authority != null 6156 && (processName == null 6157 || (p.info.processName.equals(processName) 6158 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6159 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6160 if (finalList == null) { 6161 finalList = new ArrayList<ProviderInfo>(3); 6162 } 6163 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6164 ps.readUserState(userId), userId); 6165 if (info != null) { 6166 finalList.add(info); 6167 } 6168 } 6169 } 6170 } 6171 6172 if (finalList != null) { 6173 Collections.sort(finalList, mProviderInitOrderSorter); 6174 return new ParceledListSlice<ProviderInfo>(finalList); 6175 } 6176 6177 return null; 6178 } 6179 6180 @Override 6181 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6182 // reader 6183 synchronized (mPackages) { 6184 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6185 return PackageParser.generateInstrumentationInfo(i, flags); 6186 } 6187 } 6188 6189 @Override 6190 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6191 int flags) { 6192 ArrayList<InstrumentationInfo> finalList = 6193 new ArrayList<InstrumentationInfo>(); 6194 6195 // reader 6196 synchronized (mPackages) { 6197 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6198 while (i.hasNext()) { 6199 final PackageParser.Instrumentation p = i.next(); 6200 if (targetPackage == null 6201 || targetPackage.equals(p.info.targetPackage)) { 6202 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6203 flags); 6204 if (ii != null) { 6205 finalList.add(ii); 6206 } 6207 } 6208 } 6209 } 6210 6211 return finalList; 6212 } 6213 6214 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6215 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6216 if (overlays == null) { 6217 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6218 return; 6219 } 6220 for (PackageParser.Package opkg : overlays.values()) { 6221 // Not much to do if idmap fails: we already logged the error 6222 // and we certainly don't want to abort installation of pkg simply 6223 // because an overlay didn't fit properly. For these reasons, 6224 // ignore the return value of createIdmapForPackagePairLI. 6225 createIdmapForPackagePairLI(pkg, opkg); 6226 } 6227 } 6228 6229 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6230 PackageParser.Package opkg) { 6231 if (!opkg.mTrustedOverlay) { 6232 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6233 opkg.baseCodePath + ": overlay not trusted"); 6234 return false; 6235 } 6236 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6237 if (overlaySet == null) { 6238 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6239 opkg.baseCodePath + " but target package has no known overlays"); 6240 return false; 6241 } 6242 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6243 // TODO: generate idmap for split APKs 6244 try { 6245 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6246 } catch (InstallerException e) { 6247 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6248 + opkg.baseCodePath); 6249 return false; 6250 } 6251 PackageParser.Package[] overlayArray = 6252 overlaySet.values().toArray(new PackageParser.Package[0]); 6253 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6254 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6255 return p1.mOverlayPriority - p2.mOverlayPriority; 6256 } 6257 }; 6258 Arrays.sort(overlayArray, cmp); 6259 6260 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6261 int i = 0; 6262 for (PackageParser.Package p : overlayArray) { 6263 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6264 } 6265 return true; 6266 } 6267 6268 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6269 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6270 try { 6271 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6272 } finally { 6273 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6274 } 6275 } 6276 6277 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6278 final File[] files = dir.listFiles(); 6279 if (ArrayUtils.isEmpty(files)) { 6280 Log.d(TAG, "No files in app dir " + dir); 6281 return; 6282 } 6283 6284 if (DEBUG_PACKAGE_SCANNING) { 6285 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6286 + " flags=0x" + Integer.toHexString(parseFlags)); 6287 } 6288 6289 for (File file : files) { 6290 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6291 && !PackageInstallerService.isStageName(file.getName()); 6292 if (!isPackage) { 6293 // Ignore entries which are not packages 6294 continue; 6295 } 6296 try { 6297 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6298 scanFlags, currentTime, null); 6299 } catch (PackageManagerException e) { 6300 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6301 6302 // Delete invalid userdata apps 6303 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6304 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6305 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6306 removeCodePathLI(file); 6307 } 6308 } 6309 } 6310 } 6311 6312 private static File getSettingsProblemFile() { 6313 File dataDir = Environment.getDataDirectory(); 6314 File systemDir = new File(dataDir, "system"); 6315 File fname = new File(systemDir, "uiderrors.txt"); 6316 return fname; 6317 } 6318 6319 static void reportSettingsProblem(int priority, String msg) { 6320 logCriticalInfo(priority, msg); 6321 } 6322 6323 static void logCriticalInfo(int priority, String msg) { 6324 Slog.println(priority, TAG, msg); 6325 EventLogTags.writePmCriticalInfo(msg); 6326 try { 6327 File fname = getSettingsProblemFile(); 6328 FileOutputStream out = new FileOutputStream(fname, true); 6329 PrintWriter pw = new FastPrintWriter(out); 6330 SimpleDateFormat formatter = new SimpleDateFormat(); 6331 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6332 pw.println(dateString + ": " + msg); 6333 pw.close(); 6334 FileUtils.setPermissions( 6335 fname.toString(), 6336 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6337 -1, -1); 6338 } catch (java.io.IOException e) { 6339 } 6340 } 6341 6342 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6343 int parseFlags) throws PackageManagerException { 6344 if (ps != null 6345 && ps.codePath.equals(srcFile) 6346 && ps.timeStamp == srcFile.lastModified() 6347 && !isCompatSignatureUpdateNeeded(pkg) 6348 && !isRecoverSignatureUpdateNeeded(pkg)) { 6349 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6350 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6351 ArraySet<PublicKey> signingKs; 6352 synchronized (mPackages) { 6353 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6354 } 6355 if (ps.signatures.mSignatures != null 6356 && ps.signatures.mSignatures.length != 0 6357 && signingKs != null) { 6358 // Optimization: reuse the existing cached certificates 6359 // if the package appears to be unchanged. 6360 pkg.mSignatures = ps.signatures.mSignatures; 6361 pkg.mSigningKeys = signingKs; 6362 return; 6363 } 6364 6365 Slog.w(TAG, "PackageSetting for " + ps.name 6366 + " is missing signatures. Collecting certs again to recover them."); 6367 } else { 6368 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6369 } 6370 6371 try { 6372 PackageParser.collectCertificates(pkg, parseFlags); 6373 } catch (PackageParserException e) { 6374 throw PackageManagerException.from(e); 6375 } 6376 } 6377 6378 /** 6379 * Traces a package scan. 6380 * @see #scanPackageLI(File, int, int, long, UserHandle) 6381 */ 6382 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6383 long currentTime, UserHandle user) throws PackageManagerException { 6384 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6385 try { 6386 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6387 } finally { 6388 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6389 } 6390 } 6391 6392 /** 6393 * Scans a package and returns the newly parsed package. 6394 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6395 */ 6396 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6397 long currentTime, UserHandle user) throws PackageManagerException { 6398 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6399 parseFlags |= mDefParseFlags; 6400 PackageParser pp = new PackageParser(); 6401 pp.setSeparateProcesses(mSeparateProcesses); 6402 pp.setOnlyCoreApps(mOnlyCore); 6403 pp.setDisplayMetrics(mMetrics); 6404 6405 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6406 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6407 } 6408 6409 final PackageParser.Package pkg; 6410 try { 6411 pkg = pp.parsePackage(scanFile, parseFlags); 6412 } catch (PackageParserException e) { 6413 throw PackageManagerException.from(e); 6414 } 6415 6416 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6417 } 6418 6419 /** 6420 * Scans a package and returns the newly parsed package. 6421 * @throws PackageManagerException on a parse error. 6422 */ 6423 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6424 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6425 throws PackageManagerException { 6426 // If the package has children and this is the first dive in the function 6427 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6428 // packages (parent and children) would be successfully scanned before the 6429 // actual scan since scanning mutates internal state and we want to atomically 6430 // install the package and its children. 6431 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6432 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6433 scanFlags |= SCAN_CHECK_ONLY; 6434 } 6435 } else { 6436 scanFlags &= ~SCAN_CHECK_ONLY; 6437 } 6438 6439 // Scan the parent 6440 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6441 scanFlags, currentTime, user); 6442 6443 // Scan the children 6444 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6445 for (int i = 0; i < childCount; i++) { 6446 PackageParser.Package childPackage = pkg.childPackages.get(i); 6447 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6448 currentTime, user); 6449 } 6450 6451 6452 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6453 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6454 } 6455 6456 return scannedPkg; 6457 } 6458 6459 /** 6460 * Scans a package and returns the newly parsed package. 6461 * @throws PackageManagerException on a parse error. 6462 */ 6463 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6464 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6465 throws PackageManagerException { 6466 PackageSetting ps = null; 6467 PackageSetting updatedPkg; 6468 // reader 6469 synchronized (mPackages) { 6470 // Look to see if we already know about this package. 6471 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6472 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6473 // This package has been renamed to its original name. Let's 6474 // use that. 6475 ps = mSettings.peekPackageLPr(oldName); 6476 } 6477 // If there was no original package, see one for the real package name. 6478 if (ps == null) { 6479 ps = mSettings.peekPackageLPr(pkg.packageName); 6480 } 6481 // Check to see if this package could be hiding/updating a system 6482 // package. Must look for it either under the original or real 6483 // package name depending on our state. 6484 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6485 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6486 6487 // If this is a package we don't know about on the system partition, we 6488 // may need to remove disabled child packages on the system partition 6489 // or may need to not add child packages if the parent apk is updated 6490 // on the data partition and no longer defines this child package. 6491 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6492 // If this is a parent package for an updated system app and this system 6493 // app got an OTA update which no longer defines some of the child packages 6494 // we have to prune them from the disabled system packages. 6495 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6496 if (disabledPs != null) { 6497 final int scannedChildCount = (pkg.childPackages != null) 6498 ? pkg.childPackages.size() : 0; 6499 final int disabledChildCount = disabledPs.childPackageNames != null 6500 ? disabledPs.childPackageNames.size() : 0; 6501 for (int i = 0; i < disabledChildCount; i++) { 6502 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6503 boolean disabledPackageAvailable = false; 6504 for (int j = 0; j < scannedChildCount; j++) { 6505 PackageParser.Package childPkg = pkg.childPackages.get(j); 6506 if (childPkg.packageName.equals(disabledChildPackageName)) { 6507 disabledPackageAvailable = true; 6508 break; 6509 } 6510 } 6511 if (!disabledPackageAvailable) { 6512 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6513 } 6514 } 6515 } 6516 } 6517 } 6518 6519 boolean updatedPkgBetter = false; 6520 // First check if this is a system package that may involve an update 6521 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6522 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6523 // it needs to drop FLAG_PRIVILEGED. 6524 if (locationIsPrivileged(scanFile)) { 6525 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6526 } else { 6527 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6528 } 6529 6530 if (ps != null && !ps.codePath.equals(scanFile)) { 6531 // The path has changed from what was last scanned... check the 6532 // version of the new path against what we have stored to determine 6533 // what to do. 6534 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6535 if (pkg.mVersionCode <= ps.versionCode) { 6536 // The system package has been updated and the code path does not match 6537 // Ignore entry. Skip it. 6538 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6539 + " ignored: updated version " + ps.versionCode 6540 + " better than this " + pkg.mVersionCode); 6541 if (!updatedPkg.codePath.equals(scanFile)) { 6542 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6543 + ps.name + " changing from " + updatedPkg.codePathString 6544 + " to " + scanFile); 6545 updatedPkg.codePath = scanFile; 6546 updatedPkg.codePathString = scanFile.toString(); 6547 updatedPkg.resourcePath = scanFile; 6548 updatedPkg.resourcePathString = scanFile.toString(); 6549 } 6550 updatedPkg.pkg = pkg; 6551 updatedPkg.versionCode = pkg.mVersionCode; 6552 6553 // Update the disabled system child packages to point to the package too. 6554 final int childCount = updatedPkg.childPackageNames != null 6555 ? updatedPkg.childPackageNames.size() : 0; 6556 for (int i = 0; i < childCount; i++) { 6557 String childPackageName = updatedPkg.childPackageNames.get(i); 6558 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6559 childPackageName); 6560 if (updatedChildPkg != null) { 6561 updatedChildPkg.pkg = pkg; 6562 updatedChildPkg.versionCode = pkg.mVersionCode; 6563 } 6564 } 6565 6566 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6567 + scanFile + " ignored: updated version " + ps.versionCode 6568 + " better than this " + pkg.mVersionCode); 6569 } else { 6570 // The current app on the system partition is better than 6571 // what we have updated to on the data partition; switch 6572 // back to the system partition version. 6573 // At this point, its safely assumed that package installation for 6574 // apps in system partition will go through. If not there won't be a working 6575 // version of the app 6576 // writer 6577 synchronized (mPackages) { 6578 // Just remove the loaded entries from package lists. 6579 mPackages.remove(ps.name); 6580 } 6581 6582 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6583 + " reverting from " + ps.codePathString 6584 + ": new version " + pkg.mVersionCode 6585 + " better than installed " + ps.versionCode); 6586 6587 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6588 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6589 synchronized (mInstallLock) { 6590 args.cleanUpResourcesLI(); 6591 } 6592 synchronized (mPackages) { 6593 mSettings.enableSystemPackageLPw(ps.name); 6594 } 6595 updatedPkgBetter = true; 6596 } 6597 } 6598 } 6599 6600 if (updatedPkg != null) { 6601 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6602 // initially 6603 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6604 6605 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6606 // flag set initially 6607 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6608 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6609 } 6610 } 6611 6612 // Verify certificates against what was last scanned 6613 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6614 6615 /* 6616 * A new system app appeared, but we already had a non-system one of the 6617 * same name installed earlier. 6618 */ 6619 boolean shouldHideSystemApp = false; 6620 if (updatedPkg == null && ps != null 6621 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6622 /* 6623 * Check to make sure the signatures match first. If they don't, 6624 * wipe the installed application and its data. 6625 */ 6626 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6627 != PackageManager.SIGNATURE_MATCH) { 6628 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6629 + " signatures don't match existing userdata copy; removing"); 6630 deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null); 6631 ps = null; 6632 } else { 6633 /* 6634 * If the newly-added system app is an older version than the 6635 * already installed version, hide it. It will be scanned later 6636 * and re-added like an update. 6637 */ 6638 if (pkg.mVersionCode <= ps.versionCode) { 6639 shouldHideSystemApp = true; 6640 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6641 + " but new version " + pkg.mVersionCode + " better than installed " 6642 + ps.versionCode + "; hiding system"); 6643 } else { 6644 /* 6645 * The newly found system app is a newer version that the 6646 * one previously installed. Simply remove the 6647 * already-installed application and replace it with our own 6648 * while keeping the application data. 6649 */ 6650 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6651 + " reverting from " + ps.codePathString + ": new version " 6652 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6653 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6654 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6655 synchronized (mInstallLock) { 6656 args.cleanUpResourcesLI(); 6657 } 6658 } 6659 } 6660 } 6661 6662 // The apk is forward locked (not public) if its code and resources 6663 // are kept in different files. (except for app in either system or 6664 // vendor path). 6665 // TODO grab this value from PackageSettings 6666 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6667 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6668 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6669 } 6670 } 6671 6672 // TODO: extend to support forward-locked splits 6673 String resourcePath = null; 6674 String baseResourcePath = null; 6675 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6676 if (ps != null && ps.resourcePathString != null) { 6677 resourcePath = ps.resourcePathString; 6678 baseResourcePath = ps.resourcePathString; 6679 } else { 6680 // Should not happen at all. Just log an error. 6681 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6682 } 6683 } else { 6684 resourcePath = pkg.codePath; 6685 baseResourcePath = pkg.baseCodePath; 6686 } 6687 6688 // Set application objects path explicitly. 6689 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6690 pkg.setApplicationInfoCodePath(pkg.codePath); 6691 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6692 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6693 pkg.setApplicationInfoResourcePath(resourcePath); 6694 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6695 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6696 6697 // Note that we invoke the following method only if we are about to unpack an application 6698 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6699 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6700 6701 /* 6702 * If the system app should be overridden by a previously installed 6703 * data, hide the system app now and let the /data/app scan pick it up 6704 * again. 6705 */ 6706 if (shouldHideSystemApp) { 6707 synchronized (mPackages) { 6708 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6709 } 6710 } 6711 6712 return scannedPkg; 6713 } 6714 6715 private static String fixProcessName(String defProcessName, 6716 String processName, int uid) { 6717 if (processName == null) { 6718 return defProcessName; 6719 } 6720 return processName; 6721 } 6722 6723 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6724 throws PackageManagerException { 6725 if (pkgSetting.signatures.mSignatures != null) { 6726 // Already existing package. Make sure signatures match 6727 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6728 == PackageManager.SIGNATURE_MATCH; 6729 if (!match) { 6730 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6731 == PackageManager.SIGNATURE_MATCH; 6732 } 6733 if (!match) { 6734 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6735 == PackageManager.SIGNATURE_MATCH; 6736 } 6737 if (!match) { 6738 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6739 + pkg.packageName + " signatures do not match the " 6740 + "previously installed version; ignoring!"); 6741 } 6742 } 6743 6744 // Check for shared user signatures 6745 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6746 // Already existing package. Make sure signatures match 6747 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6748 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6749 if (!match) { 6750 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6751 == PackageManager.SIGNATURE_MATCH; 6752 } 6753 if (!match) { 6754 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6755 == PackageManager.SIGNATURE_MATCH; 6756 } 6757 if (!match) { 6758 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6759 "Package " + pkg.packageName 6760 + " has no signatures that match those in shared user " 6761 + pkgSetting.sharedUser.name + "; ignoring!"); 6762 } 6763 } 6764 } 6765 6766 /** 6767 * Enforces that only the system UID or root's UID can call a method exposed 6768 * via Binder. 6769 * 6770 * @param message used as message if SecurityException is thrown 6771 * @throws SecurityException if the caller is not system or root 6772 */ 6773 private static final void enforceSystemOrRoot(String message) { 6774 final int uid = Binder.getCallingUid(); 6775 if (uid != Process.SYSTEM_UID && uid != 0) { 6776 throw new SecurityException(message); 6777 } 6778 } 6779 6780 @Override 6781 public void performFstrimIfNeeded() { 6782 enforceSystemOrRoot("Only the system can request fstrim"); 6783 6784 // Before everything else, see whether we need to fstrim. 6785 try { 6786 IMountService ms = PackageHelper.getMountService(); 6787 if (ms != null) { 6788 final boolean isUpgrade = isUpgrade(); 6789 boolean doTrim = isUpgrade; 6790 if (doTrim) { 6791 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6792 } else { 6793 final long interval = android.provider.Settings.Global.getLong( 6794 mContext.getContentResolver(), 6795 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6796 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6797 if (interval > 0) { 6798 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6799 if (timeSinceLast > interval) { 6800 doTrim = true; 6801 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6802 + "; running immediately"); 6803 } 6804 } 6805 } 6806 if (doTrim) { 6807 if (!isFirstBoot()) { 6808 try { 6809 ActivityManagerNative.getDefault().showBootMessage( 6810 mContext.getResources().getString( 6811 R.string.android_upgrading_fstrim), true); 6812 } catch (RemoteException e) { 6813 } 6814 } 6815 ms.runMaintenance(); 6816 } 6817 } else { 6818 Slog.e(TAG, "Mount service unavailable!"); 6819 } 6820 } catch (RemoteException e) { 6821 // Can't happen; MountService is local 6822 } 6823 } 6824 6825 @Override 6826 public void extractPackagesIfNeeded() { 6827 enforceSystemOrRoot("Only the system can request package extraction"); 6828 6829 // Extract pacakges only if profile-guided compilation is enabled because 6830 // otherwise BackgroundDexOptService will not dexopt them later. 6831 if (mUseJitProfiles) { 6832 List<PackageParser.Package> pkgs; 6833 synchronized (mPackages) { 6834 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 6835 } 6836 for (PackageParser.Package pkg : pkgs) { 6837 if (PackageDexOptimizer.canOptimizePackage(pkg)) { 6838 performDexOpt(pkg.packageName, null /* instructionSet */, 6839 false /* useProfiles */, true /* extractOnly */, false /* force */); 6840 } 6841 } 6842 } 6843 } 6844 6845 @Override 6846 public void notifyPackageUse(String packageName) { 6847 synchronized (mPackages) { 6848 PackageParser.Package p = mPackages.get(packageName); 6849 if (p == null) { 6850 return; 6851 } 6852 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6853 } 6854 } 6855 6856 // TODO: this is not used nor needed. Delete it. 6857 @Override 6858 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6859 return performDexOptTraced(packageName, instructionSet, false /* useProfiles */, 6860 false /* extractOnly */, false /* force */); 6861 } 6862 6863 @Override 6864 public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles, 6865 boolean extractOnly, boolean force) { 6866 return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force); 6867 } 6868 6869 private boolean performDexOptTraced(String packageName, String instructionSet, 6870 boolean useProfiles, boolean extractOnly, boolean force) { 6871 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6872 try { 6873 return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly, 6874 force); 6875 } finally { 6876 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6877 } 6878 } 6879 6880 private boolean performDexOptInternal(String packageName, String instructionSet, 6881 boolean useProfiles, boolean extractOnly, boolean force) { 6882 PackageParser.Package p; 6883 final String targetInstructionSet; 6884 synchronized (mPackages) { 6885 p = mPackages.get(packageName); 6886 if (p == null) { 6887 return false; 6888 } 6889 mPackageUsage.write(false); 6890 6891 targetInstructionSet = instructionSet != null ? instructionSet : 6892 getPrimaryInstructionSet(p.applicationInfo); 6893 if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) { 6894 // Skip only if we do not use profiles since they might trigger a recompilation. 6895 return false; 6896 } 6897 } 6898 long callingId = Binder.clearCallingIdentity(); 6899 try { 6900 synchronized (mInstallLock) { 6901 final String[] instructionSets = new String[] { targetInstructionSet }; 6902 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 6903 useProfiles, extractOnly, force); 6904 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6905 } 6906 } finally { 6907 Binder.restoreCallingIdentity(callingId); 6908 } 6909 } 6910 6911 public ArraySet<String> getOptimizablePackages() { 6912 ArraySet<String> pkgs = new ArraySet<String>(); 6913 synchronized (mPackages) { 6914 for (PackageParser.Package p : mPackages.values()) { 6915 if (PackageDexOptimizer.canOptimizePackage(p)) { 6916 pkgs.add(p.packageName); 6917 } 6918 } 6919 } 6920 return pkgs; 6921 } 6922 6923 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 6924 String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) { 6925 // Select the dex optimizer based on the force parameter. 6926 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 6927 // allocate an object here. 6928 PackageDexOptimizer pdo = force 6929 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 6930 : mPackageDexOptimizer; 6931 6932 // Optimize all dependencies first. Note: we ignore the return value and march on 6933 // on errors. 6934 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 6935 if (!deps.isEmpty()) { 6936 for (PackageParser.Package depPackage : deps) { 6937 // TODO: Analyze and investigate if we (should) profile libraries. 6938 // Currently this will do a full compilation of the library. 6939 pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */, 6940 false /* extractOnly */); 6941 } 6942 } 6943 6944 return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly); 6945 } 6946 6947 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 6948 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 6949 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 6950 Set<String> collectedNames = new HashSet<>(); 6951 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 6952 6953 retValue.remove(p); 6954 6955 return retValue; 6956 } else { 6957 return Collections.emptyList(); 6958 } 6959 } 6960 6961 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 6962 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 6963 if (!collectedNames.contains(p.packageName)) { 6964 collectedNames.add(p.packageName); 6965 collected.add(p); 6966 6967 if (p.usesLibraries != null) { 6968 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 6969 } 6970 if (p.usesOptionalLibraries != null) { 6971 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 6972 collectedNames); 6973 } 6974 } 6975 } 6976 6977 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 6978 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 6979 for (String libName : libs) { 6980 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 6981 if (libPkg != null) { 6982 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 6983 } 6984 } 6985 } 6986 6987 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 6988 synchronized (mPackages) { 6989 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 6990 if (lib != null && lib.apk != null) { 6991 return mPackages.get(lib.apk); 6992 } 6993 } 6994 return null; 6995 } 6996 6997 public void shutdown() { 6998 mPackageUsage.write(true); 6999 } 7000 7001 @Override 7002 public void forceDexOpt(String packageName) { 7003 enforceSystemOrRoot("forceDexOpt"); 7004 7005 PackageParser.Package pkg; 7006 synchronized (mPackages) { 7007 pkg = mPackages.get(packageName); 7008 if (pkg == null) { 7009 throw new IllegalArgumentException("Unknown package: " + packageName); 7010 } 7011 } 7012 7013 synchronized (mInstallLock) { 7014 final String[] instructionSets = new String[] { 7015 getPrimaryInstructionSet(pkg.applicationInfo) }; 7016 7017 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7018 7019 // Whoever is calling forceDexOpt wants a fully compiled package. 7020 // Don't use profiles since that may cause compilation to be skipped. 7021 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7022 false /* useProfiles */, false /* extractOnly */, true /* force */); 7023 7024 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7025 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7026 throw new IllegalStateException("Failed to dexopt: " + res); 7027 } 7028 } 7029 } 7030 7031 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7032 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7033 Slog.w(TAG, "Unable to update from " + oldPkg.name 7034 + " to " + newPkg.packageName 7035 + ": old package not in system partition"); 7036 return false; 7037 } else if (mPackages.get(oldPkg.name) != null) { 7038 Slog.w(TAG, "Unable to update from " + oldPkg.name 7039 + " to " + newPkg.packageName 7040 + ": old package still exists"); 7041 return false; 7042 } 7043 return true; 7044 } 7045 7046 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 7047 // TODO: triage flags as part of 26466827 7048 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7049 7050 boolean res = true; 7051 final int[] users = sUserManager.getUserIds(); 7052 for (int user : users) { 7053 try { 7054 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7055 } catch (InstallerException e) { 7056 Slog.w(TAG, "Failed to delete data directory", e); 7057 res = false; 7058 } 7059 } 7060 return res; 7061 } 7062 7063 void removeCodePathLI(File codePath) { 7064 if (codePath.isDirectory()) { 7065 try { 7066 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7067 } catch (InstallerException e) { 7068 Slog.w(TAG, "Failed to remove code path", e); 7069 } 7070 } else { 7071 codePath.delete(); 7072 } 7073 } 7074 7075 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7076 try { 7077 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7078 } catch (InstallerException e) { 7079 Slog.w(TAG, "Failed to destroy app data", e); 7080 } 7081 } 7082 7083 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7084 int appId, String seinfo) { 7085 try { 7086 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7087 } catch (InstallerException e) { 7088 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7089 } 7090 } 7091 7092 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7093 final PackageParser.Package pkg; 7094 synchronized (mPackages) { 7095 pkg = mPackages.get(packageName); 7096 } 7097 if (pkg == null) { 7098 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7099 return; 7100 } 7101 deleteCodeCacheDirsLI(pkg); 7102 } 7103 7104 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7105 // TODO: triage flags as part of 26466827 7106 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7107 7108 int[] users = sUserManager.getUserIds(); 7109 int res = 0; 7110 for (int user : users) { 7111 // Remove the parent code cache 7112 try { 7113 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7114 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7115 } catch (InstallerException e) { 7116 Slog.w(TAG, "Failed to delete code cache directory", e); 7117 } 7118 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7119 for (int i = 0; i < childCount; i++) { 7120 PackageParser.Package childPkg = pkg.childPackages.get(i); 7121 // Remove the child code cache 7122 try { 7123 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7124 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7125 } catch (InstallerException e) { 7126 Slog.w(TAG, "Failed to delete code cache directory", e); 7127 } 7128 } 7129 } 7130 } 7131 7132 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7133 long lastUpdateTime) { 7134 // Set parent install/update time 7135 PackageSetting ps = (PackageSetting) pkg.mExtras; 7136 if (ps != null) { 7137 ps.firstInstallTime = firstInstallTime; 7138 ps.lastUpdateTime = lastUpdateTime; 7139 } 7140 // Set children install/update time 7141 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7142 for (int i = 0; i < childCount; i++) { 7143 PackageParser.Package childPkg = pkg.childPackages.get(i); 7144 ps = (PackageSetting) childPkg.mExtras; 7145 if (ps != null) { 7146 ps.firstInstallTime = firstInstallTime; 7147 ps.lastUpdateTime = lastUpdateTime; 7148 } 7149 } 7150 } 7151 7152 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7153 PackageParser.Package changingLib) { 7154 if (file.path != null) { 7155 usesLibraryFiles.add(file.path); 7156 return; 7157 } 7158 PackageParser.Package p = mPackages.get(file.apk); 7159 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7160 // If we are doing this while in the middle of updating a library apk, 7161 // then we need to make sure to use that new apk for determining the 7162 // dependencies here. (We haven't yet finished committing the new apk 7163 // to the package manager state.) 7164 if (p == null || p.packageName.equals(changingLib.packageName)) { 7165 p = changingLib; 7166 } 7167 } 7168 if (p != null) { 7169 usesLibraryFiles.addAll(p.getAllCodePaths()); 7170 } 7171 } 7172 7173 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7174 PackageParser.Package changingLib) throws PackageManagerException { 7175 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7176 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7177 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7178 for (int i=0; i<N; i++) { 7179 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7180 if (file == null) { 7181 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7182 "Package " + pkg.packageName + " requires unavailable shared library " 7183 + pkg.usesLibraries.get(i) + "; failing!"); 7184 } 7185 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7186 } 7187 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7188 for (int i=0; i<N; i++) { 7189 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7190 if (file == null) { 7191 Slog.w(TAG, "Package " + pkg.packageName 7192 + " desires unavailable shared library " 7193 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7194 } else { 7195 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7196 } 7197 } 7198 N = usesLibraryFiles.size(); 7199 if (N > 0) { 7200 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7201 } else { 7202 pkg.usesLibraryFiles = null; 7203 } 7204 } 7205 } 7206 7207 private static boolean hasString(List<String> list, List<String> which) { 7208 if (list == null) { 7209 return false; 7210 } 7211 for (int i=list.size()-1; i>=0; i--) { 7212 for (int j=which.size()-1; j>=0; j--) { 7213 if (which.get(j).equals(list.get(i))) { 7214 return true; 7215 } 7216 } 7217 } 7218 return false; 7219 } 7220 7221 private void updateAllSharedLibrariesLPw() { 7222 for (PackageParser.Package pkg : mPackages.values()) { 7223 try { 7224 updateSharedLibrariesLPw(pkg, null); 7225 } catch (PackageManagerException e) { 7226 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7227 } 7228 } 7229 } 7230 7231 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7232 PackageParser.Package changingPkg) { 7233 ArrayList<PackageParser.Package> res = null; 7234 for (PackageParser.Package pkg : mPackages.values()) { 7235 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7236 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7237 if (res == null) { 7238 res = new ArrayList<PackageParser.Package>(); 7239 } 7240 res.add(pkg); 7241 try { 7242 updateSharedLibrariesLPw(pkg, changingPkg); 7243 } catch (PackageManagerException e) { 7244 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7245 } 7246 } 7247 } 7248 return res; 7249 } 7250 7251 /** 7252 * Derive the value of the {@code cpuAbiOverride} based on the provided 7253 * value and an optional stored value from the package settings. 7254 */ 7255 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7256 String cpuAbiOverride = null; 7257 7258 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7259 cpuAbiOverride = null; 7260 } else if (abiOverride != null) { 7261 cpuAbiOverride = abiOverride; 7262 } else if (settings != null) { 7263 cpuAbiOverride = settings.cpuAbiOverrideString; 7264 } 7265 7266 return cpuAbiOverride; 7267 } 7268 7269 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7270 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7271 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7272 // If the package has children and this is the first dive in the function 7273 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7274 // whether all packages (parent and children) would be successfully scanned 7275 // before the actual scan since scanning mutates internal state and we want 7276 // to atomically install the package and its children. 7277 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7278 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7279 scanFlags |= SCAN_CHECK_ONLY; 7280 } 7281 } else { 7282 scanFlags &= ~SCAN_CHECK_ONLY; 7283 } 7284 7285 final PackageParser.Package scannedPkg; 7286 try { 7287 // Scan the parent 7288 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7289 // Scan the children 7290 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7291 for (int i = 0; i < childCount; i++) { 7292 PackageParser.Package childPkg = pkg.childPackages.get(i); 7293 scanPackageLI(childPkg, parseFlags, 7294 scanFlags, currentTime, user); 7295 } 7296 } finally { 7297 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7298 } 7299 7300 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7301 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7302 } 7303 7304 return scannedPkg; 7305 } 7306 7307 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7308 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7309 boolean success = false; 7310 try { 7311 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7312 currentTime, user); 7313 success = true; 7314 return res; 7315 } finally { 7316 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7317 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7318 } 7319 } 7320 } 7321 7322 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7323 int scanFlags, long currentTime, UserHandle user) 7324 throws PackageManagerException { 7325 final File scanFile = new File(pkg.codePath); 7326 if (pkg.applicationInfo.getCodePath() == null || 7327 pkg.applicationInfo.getResourcePath() == null) { 7328 // Bail out. The resource and code paths haven't been set. 7329 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7330 "Code and resource paths haven't been set correctly"); 7331 } 7332 7333 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7334 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7335 } else { 7336 // Only allow system apps to be flagged as core apps. 7337 pkg.coreApp = false; 7338 } 7339 7340 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7341 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7342 } 7343 7344 if (mCustomResolverComponentName != null && 7345 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7346 setUpCustomResolverActivity(pkg); 7347 } 7348 7349 if (pkg.packageName.equals("android")) { 7350 synchronized (mPackages) { 7351 if (mAndroidApplication != null) { 7352 Slog.w(TAG, "*************************************************"); 7353 Slog.w(TAG, "Core android package being redefined. Skipping."); 7354 Slog.w(TAG, " file=" + scanFile); 7355 Slog.w(TAG, "*************************************************"); 7356 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7357 "Core android package being redefined. Skipping."); 7358 } 7359 7360 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7361 // Set up information for our fall-back user intent resolution activity. 7362 mPlatformPackage = pkg; 7363 pkg.mVersionCode = mSdkVersion; 7364 mAndroidApplication = pkg.applicationInfo; 7365 7366 if (!mResolverReplaced) { 7367 mResolveActivity.applicationInfo = mAndroidApplication; 7368 mResolveActivity.name = ResolverActivity.class.getName(); 7369 mResolveActivity.packageName = mAndroidApplication.packageName; 7370 mResolveActivity.processName = "system:ui"; 7371 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7372 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7373 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7374 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7375 mResolveActivity.exported = true; 7376 mResolveActivity.enabled = true; 7377 mResolveInfo.activityInfo = mResolveActivity; 7378 mResolveInfo.priority = 0; 7379 mResolveInfo.preferredOrder = 0; 7380 mResolveInfo.match = 0; 7381 mResolveComponentName = new ComponentName( 7382 mAndroidApplication.packageName, mResolveActivity.name); 7383 } 7384 } 7385 } 7386 } 7387 7388 if (DEBUG_PACKAGE_SCANNING) { 7389 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7390 Log.d(TAG, "Scanning package " + pkg.packageName); 7391 } 7392 7393 synchronized (mPackages) { 7394 if (mPackages.containsKey(pkg.packageName) 7395 || mSharedLibraries.containsKey(pkg.packageName)) { 7396 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7397 "Application package " + pkg.packageName 7398 + " already installed. Skipping duplicate."); 7399 } 7400 7401 // If we're only installing presumed-existing packages, require that the 7402 // scanned APK is both already known and at the path previously established 7403 // for it. Previously unknown packages we pick up normally, but if we have an 7404 // a priori expectation about this package's install presence, enforce it. 7405 // With a singular exception for new system packages. When an OTA contains 7406 // a new system package, we allow the codepath to change from a system location 7407 // to the user-installed location. If we don't allow this change, any newer, 7408 // user-installed version of the application will be ignored. 7409 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7410 if (mExpectingBetter.containsKey(pkg.packageName)) { 7411 logCriticalInfo(Log.WARN, 7412 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7413 } else { 7414 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7415 if (known != null) { 7416 if (DEBUG_PACKAGE_SCANNING) { 7417 Log.d(TAG, "Examining " + pkg.codePath 7418 + " and requiring known paths " + known.codePathString 7419 + " & " + known.resourcePathString); 7420 } 7421 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7422 || !pkg.applicationInfo.getResourcePath().equals( 7423 known.resourcePathString)) { 7424 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7425 "Application package " + pkg.packageName 7426 + " found at " + pkg.applicationInfo.getCodePath() 7427 + " but expected at " + known.codePathString 7428 + "; ignoring."); 7429 } 7430 } 7431 } 7432 } 7433 } 7434 7435 // Initialize package source and resource directories 7436 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7437 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7438 7439 SharedUserSetting suid = null; 7440 PackageSetting pkgSetting = null; 7441 7442 if (!isSystemApp(pkg)) { 7443 // Only system apps can use these features. 7444 pkg.mOriginalPackages = null; 7445 pkg.mRealPackage = null; 7446 pkg.mAdoptPermissions = null; 7447 } 7448 7449 // Getting the package setting may have a side-effect, so if we 7450 // are only checking if scan would succeed, stash a copy of the 7451 // old setting to restore at the end. 7452 PackageSetting nonMutatedPs = null; 7453 7454 // writer 7455 synchronized (mPackages) { 7456 if (pkg.mSharedUserId != null) { 7457 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7458 if (suid == null) { 7459 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7460 "Creating application package " + pkg.packageName 7461 + " for shared user failed"); 7462 } 7463 if (DEBUG_PACKAGE_SCANNING) { 7464 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7465 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7466 + "): packages=" + suid.packages); 7467 } 7468 } 7469 7470 // Check if we are renaming from an original package name. 7471 PackageSetting origPackage = null; 7472 String realName = null; 7473 if (pkg.mOriginalPackages != null) { 7474 // This package may need to be renamed to a previously 7475 // installed name. Let's check on that... 7476 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7477 if (pkg.mOriginalPackages.contains(renamed)) { 7478 // This package had originally been installed as the 7479 // original name, and we have already taken care of 7480 // transitioning to the new one. Just update the new 7481 // one to continue using the old name. 7482 realName = pkg.mRealPackage; 7483 if (!pkg.packageName.equals(renamed)) { 7484 // Callers into this function may have already taken 7485 // care of renaming the package; only do it here if 7486 // it is not already done. 7487 pkg.setPackageName(renamed); 7488 } 7489 7490 } else { 7491 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7492 if ((origPackage = mSettings.peekPackageLPr( 7493 pkg.mOriginalPackages.get(i))) != null) { 7494 // We do have the package already installed under its 7495 // original name... should we use it? 7496 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7497 // New package is not compatible with original. 7498 origPackage = null; 7499 continue; 7500 } else if (origPackage.sharedUser != null) { 7501 // Make sure uid is compatible between packages. 7502 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7503 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7504 + " to " + pkg.packageName + ": old uid " 7505 + origPackage.sharedUser.name 7506 + " differs from " + pkg.mSharedUserId); 7507 origPackage = null; 7508 continue; 7509 } 7510 } else { 7511 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7512 + pkg.packageName + " to old name " + origPackage.name); 7513 } 7514 break; 7515 } 7516 } 7517 } 7518 } 7519 7520 if (mTransferedPackages.contains(pkg.packageName)) { 7521 Slog.w(TAG, "Package " + pkg.packageName 7522 + " was transferred to another, but its .apk remains"); 7523 } 7524 7525 // See comments in nonMutatedPs declaration 7526 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7527 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7528 if (foundPs != null) { 7529 nonMutatedPs = new PackageSetting(foundPs); 7530 } 7531 } 7532 7533 // Just create the setting, don't add it yet. For already existing packages 7534 // the PkgSetting exists already and doesn't have to be created. 7535 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7536 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7537 pkg.applicationInfo.primaryCpuAbi, 7538 pkg.applicationInfo.secondaryCpuAbi, 7539 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7540 user, false); 7541 if (pkgSetting == null) { 7542 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7543 "Creating application package " + pkg.packageName + " failed"); 7544 } 7545 7546 if (pkgSetting.origPackage != null) { 7547 // If we are first transitioning from an original package, 7548 // fix up the new package's name now. We need to do this after 7549 // looking up the package under its new name, so getPackageLP 7550 // can take care of fiddling things correctly. 7551 pkg.setPackageName(origPackage.name); 7552 7553 // File a report about this. 7554 String msg = "New package " + pkgSetting.realName 7555 + " renamed to replace old package " + pkgSetting.name; 7556 reportSettingsProblem(Log.WARN, msg); 7557 7558 // Make a note of it. 7559 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7560 mTransferedPackages.add(origPackage.name); 7561 } 7562 7563 // No longer need to retain this. 7564 pkgSetting.origPackage = null; 7565 } 7566 7567 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7568 // Make a note of it. 7569 mTransferedPackages.add(pkg.packageName); 7570 } 7571 7572 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7573 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7574 } 7575 7576 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7577 // Check all shared libraries and map to their actual file path. 7578 // We only do this here for apps not on a system dir, because those 7579 // are the only ones that can fail an install due to this. We 7580 // will take care of the system apps by updating all of their 7581 // library paths after the scan is done. 7582 updateSharedLibrariesLPw(pkg, null); 7583 } 7584 7585 if (mFoundPolicyFile) { 7586 SELinuxMMAC.assignSeinfoValue(pkg); 7587 } 7588 7589 pkg.applicationInfo.uid = pkgSetting.appId; 7590 pkg.mExtras = pkgSetting; 7591 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7592 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7593 // We just determined the app is signed correctly, so bring 7594 // over the latest parsed certs. 7595 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7596 } else { 7597 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7598 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7599 "Package " + pkg.packageName + " upgrade keys do not match the " 7600 + "previously installed version"); 7601 } else { 7602 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7603 String msg = "System package " + pkg.packageName 7604 + " signature changed; retaining data."; 7605 reportSettingsProblem(Log.WARN, msg); 7606 } 7607 } 7608 } else { 7609 try { 7610 verifySignaturesLP(pkgSetting, pkg); 7611 // We just determined the app is signed correctly, so bring 7612 // over the latest parsed certs. 7613 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7614 } catch (PackageManagerException e) { 7615 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7616 throw e; 7617 } 7618 // The signature has changed, but this package is in the system 7619 // image... let's recover! 7620 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7621 // However... if this package is part of a shared user, but it 7622 // doesn't match the signature of the shared user, let's fail. 7623 // What this means is that you can't change the signatures 7624 // associated with an overall shared user, which doesn't seem all 7625 // that unreasonable. 7626 if (pkgSetting.sharedUser != null) { 7627 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7628 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7629 throw new PackageManagerException( 7630 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7631 "Signature mismatch for shared user: " 7632 + pkgSetting.sharedUser); 7633 } 7634 } 7635 // File a report about this. 7636 String msg = "System package " + pkg.packageName 7637 + " signature changed; retaining data."; 7638 reportSettingsProblem(Log.WARN, msg); 7639 } 7640 } 7641 // Verify that this new package doesn't have any content providers 7642 // that conflict with existing packages. Only do this if the 7643 // package isn't already installed, since we don't want to break 7644 // things that are installed. 7645 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7646 final int N = pkg.providers.size(); 7647 int i; 7648 for (i=0; i<N; i++) { 7649 PackageParser.Provider p = pkg.providers.get(i); 7650 if (p.info.authority != null) { 7651 String names[] = p.info.authority.split(";"); 7652 for (int j = 0; j < names.length; j++) { 7653 if (mProvidersByAuthority.containsKey(names[j])) { 7654 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7655 final String otherPackageName = 7656 ((other != null && other.getComponentName() != null) ? 7657 other.getComponentName().getPackageName() : "?"); 7658 throw new PackageManagerException( 7659 INSTALL_FAILED_CONFLICTING_PROVIDER, 7660 "Can't install because provider name " + names[j] 7661 + " (in package " + pkg.applicationInfo.packageName 7662 + ") is already used by " + otherPackageName); 7663 } 7664 } 7665 } 7666 } 7667 } 7668 7669 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7670 // This package wants to adopt ownership of permissions from 7671 // another package. 7672 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7673 final String origName = pkg.mAdoptPermissions.get(i); 7674 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7675 if (orig != null) { 7676 if (verifyPackageUpdateLPr(orig, pkg)) { 7677 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7678 + pkg.packageName); 7679 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7680 } 7681 } 7682 } 7683 } 7684 } 7685 7686 final String pkgName = pkg.packageName; 7687 7688 final long scanFileTime = scanFile.lastModified(); 7689 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7690 pkg.applicationInfo.processName = fixProcessName( 7691 pkg.applicationInfo.packageName, 7692 pkg.applicationInfo.processName, 7693 pkg.applicationInfo.uid); 7694 7695 if (pkg != mPlatformPackage) { 7696 // Get all of our default paths setup 7697 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7698 } 7699 7700 final String path = scanFile.getPath(); 7701 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7702 7703 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7704 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7705 7706 // Some system apps still use directory structure for native libraries 7707 // in which case we might end up not detecting abi solely based on apk 7708 // structure. Try to detect abi based on directory structure. 7709 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7710 pkg.applicationInfo.primaryCpuAbi == null) { 7711 setBundledAppAbisAndRoots(pkg, pkgSetting); 7712 setNativeLibraryPaths(pkg); 7713 } 7714 7715 } else { 7716 if ((scanFlags & SCAN_MOVE) != 0) { 7717 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7718 // but we already have this packages package info in the PackageSetting. We just 7719 // use that and derive the native library path based on the new codepath. 7720 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7721 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7722 } 7723 7724 // Set native library paths again. For moves, the path will be updated based on the 7725 // ABIs we've determined above. For non-moves, the path will be updated based on the 7726 // ABIs we determined during compilation, but the path will depend on the final 7727 // package path (after the rename away from the stage path). 7728 setNativeLibraryPaths(pkg); 7729 } 7730 7731 // This is a special case for the "system" package, where the ABI is 7732 // dictated by the zygote configuration (and init.rc). We should keep track 7733 // of this ABI so that we can deal with "normal" applications that run under 7734 // the same UID correctly. 7735 if (mPlatformPackage == pkg) { 7736 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7737 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7738 } 7739 7740 // If there's a mismatch between the abi-override in the package setting 7741 // and the abiOverride specified for the install. Warn about this because we 7742 // would've already compiled the app without taking the package setting into 7743 // account. 7744 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7745 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7746 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7747 " for package " + pkg.packageName); 7748 } 7749 } 7750 7751 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7752 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7753 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7754 7755 // Copy the derived override back to the parsed package, so that we can 7756 // update the package settings accordingly. 7757 pkg.cpuAbiOverride = cpuAbiOverride; 7758 7759 if (DEBUG_ABI_SELECTION) { 7760 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7761 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7762 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7763 } 7764 7765 // Push the derived path down into PackageSettings so we know what to 7766 // clean up at uninstall time. 7767 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7768 7769 if (DEBUG_ABI_SELECTION) { 7770 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7771 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7772 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7773 } 7774 7775 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7776 // We don't do this here during boot because we can do it all 7777 // at once after scanning all existing packages. 7778 // 7779 // We also do this *before* we perform dexopt on this package, so that 7780 // we can avoid redundant dexopts, and also to make sure we've got the 7781 // code and package path correct. 7782 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7783 pkg, true /* boot complete */); 7784 } 7785 7786 if (mFactoryTest && pkg.requestedPermissions.contains( 7787 android.Manifest.permission.FACTORY_TEST)) { 7788 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7789 } 7790 7791 ArrayList<PackageParser.Package> clientLibPkgs = null; 7792 7793 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7794 if (nonMutatedPs != null) { 7795 synchronized (mPackages) { 7796 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 7797 } 7798 } 7799 return pkg; 7800 } 7801 7802 // Only privileged apps and updated privileged apps can add child packages. 7803 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 7804 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 7805 throw new PackageManagerException("Only privileged apps and updated " 7806 + "privileged apps can add child packages. Ignoring package " 7807 + pkg.packageName); 7808 } 7809 final int childCount = pkg.childPackages.size(); 7810 for (int i = 0; i < childCount; i++) { 7811 PackageParser.Package childPkg = pkg.childPackages.get(i); 7812 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 7813 childPkg.packageName)) { 7814 throw new PackageManagerException("Cannot override a child package of " 7815 + "another disabled system app. Ignoring package " + pkg.packageName); 7816 } 7817 } 7818 } 7819 7820 // writer 7821 synchronized (mPackages) { 7822 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7823 // Only system apps can add new shared libraries. 7824 if (pkg.libraryNames != null) { 7825 for (int i=0; i<pkg.libraryNames.size(); i++) { 7826 String name = pkg.libraryNames.get(i); 7827 boolean allowed = false; 7828 if (pkg.isUpdatedSystemApp()) { 7829 // New library entries can only be added through the 7830 // system image. This is important to get rid of a lot 7831 // of nasty edge cases: for example if we allowed a non- 7832 // system update of the app to add a library, then uninstalling 7833 // the update would make the library go away, and assumptions 7834 // we made such as through app install filtering would now 7835 // have allowed apps on the device which aren't compatible 7836 // with it. Better to just have the restriction here, be 7837 // conservative, and create many fewer cases that can negatively 7838 // impact the user experience. 7839 final PackageSetting sysPs = mSettings 7840 .getDisabledSystemPkgLPr(pkg.packageName); 7841 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7842 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7843 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7844 allowed = true; 7845 break; 7846 } 7847 } 7848 } 7849 } else { 7850 allowed = true; 7851 } 7852 if (allowed) { 7853 if (!mSharedLibraries.containsKey(name)) { 7854 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7855 } else if (!name.equals(pkg.packageName)) { 7856 Slog.w(TAG, "Package " + pkg.packageName + " library " 7857 + name + " already exists; skipping"); 7858 } 7859 } else { 7860 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7861 + name + " that is not declared on system image; skipping"); 7862 } 7863 } 7864 if ((scanFlags & SCAN_BOOTING) == 0) { 7865 // If we are not booting, we need to update any applications 7866 // that are clients of our shared library. If we are booting, 7867 // this will all be done once the scan is complete. 7868 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7869 } 7870 } 7871 } 7872 } 7873 7874 // Request the ActivityManager to kill the process(only for existing packages) 7875 // so that we do not end up in a confused state while the user is still using the older 7876 // version of the application while the new one gets installed. 7877 if ((scanFlags & SCAN_REPLACING) != 0) { 7878 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7879 7880 killApplication(pkg.applicationInfo.packageName, 7881 pkg.applicationInfo.uid, "replace pkg"); 7882 7883 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7884 } 7885 7886 // Also need to kill any apps that are dependent on the library. 7887 if (clientLibPkgs != null) { 7888 for (int i=0; i<clientLibPkgs.size(); i++) { 7889 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7890 killApplication(clientPkg.applicationInfo.packageName, 7891 clientPkg.applicationInfo.uid, "update lib"); 7892 } 7893 } 7894 7895 // Make sure we're not adding any bogus keyset info 7896 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7897 ksms.assertScannedPackageValid(pkg); 7898 7899 // writer 7900 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7901 7902 boolean createIdmapFailed = false; 7903 synchronized (mPackages) { 7904 // We don't expect installation to fail beyond this point 7905 7906 // Add the new setting to mSettings 7907 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7908 // Add the new setting to mPackages 7909 mPackages.put(pkg.applicationInfo.packageName, pkg); 7910 // Make sure we don't accidentally delete its data. 7911 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7912 while (iter.hasNext()) { 7913 PackageCleanItem item = iter.next(); 7914 if (pkgName.equals(item.packageName)) { 7915 iter.remove(); 7916 } 7917 } 7918 7919 // Take care of first install / last update times. 7920 if (currentTime != 0) { 7921 if (pkgSetting.firstInstallTime == 0) { 7922 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7923 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7924 pkgSetting.lastUpdateTime = currentTime; 7925 } 7926 } else if (pkgSetting.firstInstallTime == 0) { 7927 // We need *something*. Take time time stamp of the file. 7928 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7929 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7930 if (scanFileTime != pkgSetting.timeStamp) { 7931 // A package on the system image has changed; consider this 7932 // to be an update. 7933 pkgSetting.lastUpdateTime = scanFileTime; 7934 } 7935 } 7936 7937 // Add the package's KeySets to the global KeySetManagerService 7938 ksms.addScannedPackageLPw(pkg); 7939 7940 int N = pkg.providers.size(); 7941 StringBuilder r = null; 7942 int i; 7943 for (i=0; i<N; i++) { 7944 PackageParser.Provider p = pkg.providers.get(i); 7945 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7946 p.info.processName, pkg.applicationInfo.uid); 7947 mProviders.addProvider(p); 7948 p.syncable = p.info.isSyncable; 7949 if (p.info.authority != null) { 7950 String names[] = p.info.authority.split(";"); 7951 p.info.authority = null; 7952 for (int j = 0; j < names.length; j++) { 7953 if (j == 1 && p.syncable) { 7954 // We only want the first authority for a provider to possibly be 7955 // syncable, so if we already added this provider using a different 7956 // authority clear the syncable flag. We copy the provider before 7957 // changing it because the mProviders object contains a reference 7958 // to a provider that we don't want to change. 7959 // Only do this for the second authority since the resulting provider 7960 // object can be the same for all future authorities for this provider. 7961 p = new PackageParser.Provider(p); 7962 p.syncable = false; 7963 } 7964 if (!mProvidersByAuthority.containsKey(names[j])) { 7965 mProvidersByAuthority.put(names[j], p); 7966 if (p.info.authority == null) { 7967 p.info.authority = names[j]; 7968 } else { 7969 p.info.authority = p.info.authority + ";" + names[j]; 7970 } 7971 if (DEBUG_PACKAGE_SCANNING) { 7972 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7973 Log.d(TAG, "Registered content provider: " + names[j] 7974 + ", className = " + p.info.name + ", isSyncable = " 7975 + p.info.isSyncable); 7976 } 7977 } else { 7978 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7979 Slog.w(TAG, "Skipping provider name " + names[j] + 7980 " (in package " + pkg.applicationInfo.packageName + 7981 "): name already used by " 7982 + ((other != null && other.getComponentName() != null) 7983 ? other.getComponentName().getPackageName() : "?")); 7984 } 7985 } 7986 } 7987 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7988 if (r == null) { 7989 r = new StringBuilder(256); 7990 } else { 7991 r.append(' '); 7992 } 7993 r.append(p.info.name); 7994 } 7995 } 7996 if (r != null) { 7997 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7998 } 7999 8000 N = pkg.services.size(); 8001 r = null; 8002 for (i=0; i<N; i++) { 8003 PackageParser.Service s = pkg.services.get(i); 8004 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8005 s.info.processName, pkg.applicationInfo.uid); 8006 mServices.addService(s); 8007 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8008 if (r == null) { 8009 r = new StringBuilder(256); 8010 } else { 8011 r.append(' '); 8012 } 8013 r.append(s.info.name); 8014 } 8015 } 8016 if (r != null) { 8017 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8018 } 8019 8020 N = pkg.receivers.size(); 8021 r = null; 8022 for (i=0; i<N; i++) { 8023 PackageParser.Activity a = pkg.receivers.get(i); 8024 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8025 a.info.processName, pkg.applicationInfo.uid); 8026 mReceivers.addActivity(a, "receiver"); 8027 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8028 if (r == null) { 8029 r = new StringBuilder(256); 8030 } else { 8031 r.append(' '); 8032 } 8033 r.append(a.info.name); 8034 } 8035 } 8036 if (r != null) { 8037 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8038 } 8039 8040 N = pkg.activities.size(); 8041 r = null; 8042 for (i=0; i<N; i++) { 8043 PackageParser.Activity a = pkg.activities.get(i); 8044 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8045 a.info.processName, pkg.applicationInfo.uid); 8046 mActivities.addActivity(a, "activity"); 8047 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8048 if (r == null) { 8049 r = new StringBuilder(256); 8050 } else { 8051 r.append(' '); 8052 } 8053 r.append(a.info.name); 8054 } 8055 } 8056 if (r != null) { 8057 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8058 } 8059 8060 N = pkg.permissionGroups.size(); 8061 r = null; 8062 for (i=0; i<N; i++) { 8063 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8064 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8065 if (cur == null) { 8066 mPermissionGroups.put(pg.info.name, pg); 8067 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8068 if (r == null) { 8069 r = new StringBuilder(256); 8070 } else { 8071 r.append(' '); 8072 } 8073 r.append(pg.info.name); 8074 } 8075 } else { 8076 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8077 + pg.info.packageName + " ignored: original from " 8078 + cur.info.packageName); 8079 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8080 if (r == null) { 8081 r = new StringBuilder(256); 8082 } else { 8083 r.append(' '); 8084 } 8085 r.append("DUP:"); 8086 r.append(pg.info.name); 8087 } 8088 } 8089 } 8090 if (r != null) { 8091 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8092 } 8093 8094 N = pkg.permissions.size(); 8095 r = null; 8096 for (i=0; i<N; i++) { 8097 PackageParser.Permission p = pkg.permissions.get(i); 8098 8099 // Assume by default that we did not install this permission into the system. 8100 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8101 8102 // Now that permission groups have a special meaning, we ignore permission 8103 // groups for legacy apps to prevent unexpected behavior. In particular, 8104 // permissions for one app being granted to someone just becase they happen 8105 // to be in a group defined by another app (before this had no implications). 8106 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8107 p.group = mPermissionGroups.get(p.info.group); 8108 // Warn for a permission in an unknown group. 8109 if (p.info.group != null && p.group == null) { 8110 Slog.w(TAG, "Permission " + p.info.name + " from package " 8111 + p.info.packageName + " in an unknown group " + p.info.group); 8112 } 8113 } 8114 8115 ArrayMap<String, BasePermission> permissionMap = 8116 p.tree ? mSettings.mPermissionTrees 8117 : mSettings.mPermissions; 8118 BasePermission bp = permissionMap.get(p.info.name); 8119 8120 // Allow system apps to redefine non-system permissions 8121 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8122 final boolean currentOwnerIsSystem = (bp.perm != null 8123 && isSystemApp(bp.perm.owner)); 8124 if (isSystemApp(p.owner)) { 8125 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8126 // It's a built-in permission and no owner, take ownership now 8127 bp.packageSetting = pkgSetting; 8128 bp.perm = p; 8129 bp.uid = pkg.applicationInfo.uid; 8130 bp.sourcePackage = p.info.packageName; 8131 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8132 } else if (!currentOwnerIsSystem) { 8133 String msg = "New decl " + p.owner + " of permission " 8134 + p.info.name + " is system; overriding " + bp.sourcePackage; 8135 reportSettingsProblem(Log.WARN, msg); 8136 bp = null; 8137 } 8138 } 8139 } 8140 8141 if (bp == null) { 8142 bp = new BasePermission(p.info.name, p.info.packageName, 8143 BasePermission.TYPE_NORMAL); 8144 permissionMap.put(p.info.name, bp); 8145 } 8146 8147 if (bp.perm == null) { 8148 if (bp.sourcePackage == null 8149 || bp.sourcePackage.equals(p.info.packageName)) { 8150 BasePermission tree = findPermissionTreeLP(p.info.name); 8151 if (tree == null 8152 || tree.sourcePackage.equals(p.info.packageName)) { 8153 bp.packageSetting = pkgSetting; 8154 bp.perm = p; 8155 bp.uid = pkg.applicationInfo.uid; 8156 bp.sourcePackage = p.info.packageName; 8157 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8158 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8159 if (r == null) { 8160 r = new StringBuilder(256); 8161 } else { 8162 r.append(' '); 8163 } 8164 r.append(p.info.name); 8165 } 8166 } else { 8167 Slog.w(TAG, "Permission " + p.info.name + " from package " 8168 + p.info.packageName + " ignored: base tree " 8169 + tree.name + " is from package " 8170 + tree.sourcePackage); 8171 } 8172 } else { 8173 Slog.w(TAG, "Permission " + p.info.name + " from package " 8174 + p.info.packageName + " ignored: original from " 8175 + bp.sourcePackage); 8176 } 8177 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8178 if (r == null) { 8179 r = new StringBuilder(256); 8180 } else { 8181 r.append(' '); 8182 } 8183 r.append("DUP:"); 8184 r.append(p.info.name); 8185 } 8186 if (bp.perm == p) { 8187 bp.protectionLevel = p.info.protectionLevel; 8188 } 8189 } 8190 8191 if (r != null) { 8192 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8193 } 8194 8195 N = pkg.instrumentation.size(); 8196 r = null; 8197 for (i=0; i<N; i++) { 8198 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8199 a.info.packageName = pkg.applicationInfo.packageName; 8200 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8201 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8202 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8203 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8204 a.info.dataDir = pkg.applicationInfo.dataDir; 8205 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 8206 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 8207 8208 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8209 // need other information about the application, like the ABI and what not ? 8210 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8211 mInstrumentation.put(a.getComponentName(), a); 8212 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8213 if (r == null) { 8214 r = new StringBuilder(256); 8215 } else { 8216 r.append(' '); 8217 } 8218 r.append(a.info.name); 8219 } 8220 } 8221 if (r != null) { 8222 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8223 } 8224 8225 if (pkg.protectedBroadcasts != null) { 8226 N = pkg.protectedBroadcasts.size(); 8227 for (i=0; i<N; i++) { 8228 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8229 } 8230 } 8231 8232 pkgSetting.setTimeStamp(scanFileTime); 8233 8234 // Create idmap files for pairs of (packages, overlay packages). 8235 // Note: "android", ie framework-res.apk, is handled by native layers. 8236 if (pkg.mOverlayTarget != null) { 8237 // This is an overlay package. 8238 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8239 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8240 mOverlays.put(pkg.mOverlayTarget, 8241 new ArrayMap<String, PackageParser.Package>()); 8242 } 8243 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8244 map.put(pkg.packageName, pkg); 8245 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8246 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8247 createIdmapFailed = true; 8248 } 8249 } 8250 } else if (mOverlays.containsKey(pkg.packageName) && 8251 !pkg.packageName.equals("android")) { 8252 // This is a regular package, with one or more known overlay packages. 8253 createIdmapsForPackageLI(pkg); 8254 } 8255 } 8256 8257 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8258 8259 if (createIdmapFailed) { 8260 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8261 "scanPackageLI failed to createIdmap"); 8262 } 8263 return pkg; 8264 } 8265 8266 /** 8267 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8268 * is derived purely on the basis of the contents of {@code scanFile} and 8269 * {@code cpuAbiOverride}. 8270 * 8271 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8272 */ 8273 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8274 String cpuAbiOverride, boolean extractLibs) 8275 throws PackageManagerException { 8276 // TODO: We can probably be smarter about this stuff. For installed apps, 8277 // we can calculate this information at install time once and for all. For 8278 // system apps, we can probably assume that this information doesn't change 8279 // after the first boot scan. As things stand, we do lots of unnecessary work. 8280 8281 // Give ourselves some initial paths; we'll come back for another 8282 // pass once we've determined ABI below. 8283 setNativeLibraryPaths(pkg); 8284 8285 // We would never need to extract libs for forward-locked and external packages, 8286 // since the container service will do it for us. We shouldn't attempt to 8287 // extract libs from system app when it was not updated. 8288 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8289 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8290 extractLibs = false; 8291 } 8292 8293 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8294 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8295 8296 NativeLibraryHelper.Handle handle = null; 8297 try { 8298 handle = NativeLibraryHelper.Handle.create(pkg); 8299 // TODO(multiArch): This can be null for apps that didn't go through the 8300 // usual installation process. We can calculate it again, like we 8301 // do during install time. 8302 // 8303 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8304 // unnecessary. 8305 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8306 8307 // Null out the abis so that they can be recalculated. 8308 pkg.applicationInfo.primaryCpuAbi = null; 8309 pkg.applicationInfo.secondaryCpuAbi = null; 8310 if (isMultiArch(pkg.applicationInfo)) { 8311 // Warn if we've set an abiOverride for multi-lib packages.. 8312 // By definition, we need to copy both 32 and 64 bit libraries for 8313 // such packages. 8314 if (pkg.cpuAbiOverride != null 8315 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8316 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8317 } 8318 8319 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8320 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8321 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8322 if (extractLibs) { 8323 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8324 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8325 useIsaSpecificSubdirs); 8326 } else { 8327 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8328 } 8329 } 8330 8331 maybeThrowExceptionForMultiArchCopy( 8332 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8333 8334 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8335 if (extractLibs) { 8336 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8337 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8338 useIsaSpecificSubdirs); 8339 } else { 8340 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8341 } 8342 } 8343 8344 maybeThrowExceptionForMultiArchCopy( 8345 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8346 8347 if (abi64 >= 0) { 8348 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8349 } 8350 8351 if (abi32 >= 0) { 8352 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8353 if (abi64 >= 0) { 8354 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8355 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8356 pkg.applicationInfo.primaryCpuAbi = abi; 8357 } else { 8358 pkg.applicationInfo.secondaryCpuAbi = abi; 8359 } 8360 } else { 8361 pkg.applicationInfo.primaryCpuAbi = abi; 8362 } 8363 } 8364 8365 } else { 8366 String[] abiList = (cpuAbiOverride != null) ? 8367 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8368 8369 // Enable gross and lame hacks for apps that are built with old 8370 // SDK tools. We must scan their APKs for renderscript bitcode and 8371 // not launch them if it's present. Don't bother checking on devices 8372 // that don't have 64 bit support. 8373 boolean needsRenderScriptOverride = false; 8374 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8375 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8376 abiList = Build.SUPPORTED_32_BIT_ABIS; 8377 needsRenderScriptOverride = true; 8378 } 8379 8380 final int copyRet; 8381 if (extractLibs) { 8382 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8383 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8384 } else { 8385 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8386 } 8387 8388 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8389 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8390 "Error unpackaging native libs for app, errorCode=" + copyRet); 8391 } 8392 8393 if (copyRet >= 0) { 8394 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8395 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8396 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8397 } else if (needsRenderScriptOverride) { 8398 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8399 } 8400 } 8401 } catch (IOException ioe) { 8402 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8403 } finally { 8404 IoUtils.closeQuietly(handle); 8405 } 8406 8407 // Now that we've calculated the ABIs and determined if it's an internal app, 8408 // we will go ahead and populate the nativeLibraryPath. 8409 setNativeLibraryPaths(pkg); 8410 } 8411 8412 /** 8413 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8414 * i.e, so that all packages can be run inside a single process if required. 8415 * 8416 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8417 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8418 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8419 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8420 * updating a package that belongs to a shared user. 8421 * 8422 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8423 * adds unnecessary complexity. 8424 */ 8425 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8426 PackageParser.Package scannedPackage, boolean bootComplete) { 8427 String requiredInstructionSet = null; 8428 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8429 requiredInstructionSet = VMRuntime.getInstructionSet( 8430 scannedPackage.applicationInfo.primaryCpuAbi); 8431 } 8432 8433 PackageSetting requirer = null; 8434 for (PackageSetting ps : packagesForUser) { 8435 // If packagesForUser contains scannedPackage, we skip it. This will happen 8436 // when scannedPackage is an update of an existing package. Without this check, 8437 // we will never be able to change the ABI of any package belonging to a shared 8438 // user, even if it's compatible with other packages. 8439 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8440 if (ps.primaryCpuAbiString == null) { 8441 continue; 8442 } 8443 8444 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8445 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8446 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8447 // this but there's not much we can do. 8448 String errorMessage = "Instruction set mismatch, " 8449 + ((requirer == null) ? "[caller]" : requirer) 8450 + " requires " + requiredInstructionSet + " whereas " + ps 8451 + " requires " + instructionSet; 8452 Slog.w(TAG, errorMessage); 8453 } 8454 8455 if (requiredInstructionSet == null) { 8456 requiredInstructionSet = instructionSet; 8457 requirer = ps; 8458 } 8459 } 8460 } 8461 8462 if (requiredInstructionSet != null) { 8463 String adjustedAbi; 8464 if (requirer != null) { 8465 // requirer != null implies that either scannedPackage was null or that scannedPackage 8466 // did not require an ABI, in which case we have to adjust scannedPackage to match 8467 // the ABI of the set (which is the same as requirer's ABI) 8468 adjustedAbi = requirer.primaryCpuAbiString; 8469 if (scannedPackage != null) { 8470 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8471 } 8472 } else { 8473 // requirer == null implies that we're updating all ABIs in the set to 8474 // match scannedPackage. 8475 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8476 } 8477 8478 for (PackageSetting ps : packagesForUser) { 8479 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8480 if (ps.primaryCpuAbiString != null) { 8481 continue; 8482 } 8483 8484 ps.primaryCpuAbiString = adjustedAbi; 8485 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8486 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8487 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8488 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8489 + " (requirer=" 8490 + (requirer == null ? "null" : requirer.pkg.packageName) 8491 + ", scannedPackage=" 8492 + (scannedPackage != null ? scannedPackage.packageName : "null") 8493 + ")"); 8494 try { 8495 mInstaller.rmdex(ps.codePathString, 8496 getDexCodeInstructionSet(getPreferredInstructionSet())); 8497 } catch (InstallerException ignored) { 8498 } 8499 } 8500 } 8501 } 8502 } 8503 } 8504 8505 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8506 synchronized (mPackages) { 8507 mResolverReplaced = true; 8508 // Set up information for custom user intent resolution activity. 8509 mResolveActivity.applicationInfo = pkg.applicationInfo; 8510 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8511 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8512 mResolveActivity.processName = pkg.applicationInfo.packageName; 8513 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8514 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8515 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8516 mResolveActivity.theme = 0; 8517 mResolveActivity.exported = true; 8518 mResolveActivity.enabled = true; 8519 mResolveInfo.activityInfo = mResolveActivity; 8520 mResolveInfo.priority = 0; 8521 mResolveInfo.preferredOrder = 0; 8522 mResolveInfo.match = 0; 8523 mResolveComponentName = mCustomResolverComponentName; 8524 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8525 mResolveComponentName); 8526 } 8527 } 8528 8529 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8530 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8531 8532 // Set up information for ephemeral installer activity 8533 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8534 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8535 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8536 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8537 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8538 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8539 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8540 mEphemeralInstallerActivity.theme = 0; 8541 mEphemeralInstallerActivity.exported = true; 8542 mEphemeralInstallerActivity.enabled = true; 8543 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8544 mEphemeralInstallerInfo.priority = 0; 8545 mEphemeralInstallerInfo.preferredOrder = 0; 8546 mEphemeralInstallerInfo.match = 0; 8547 8548 if (DEBUG_EPHEMERAL) { 8549 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8550 } 8551 } 8552 8553 private static String calculateBundledApkRoot(final String codePathString) { 8554 final File codePath = new File(codePathString); 8555 final File codeRoot; 8556 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8557 codeRoot = Environment.getRootDirectory(); 8558 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8559 codeRoot = Environment.getOemDirectory(); 8560 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8561 codeRoot = Environment.getVendorDirectory(); 8562 } else { 8563 // Unrecognized code path; take its top real segment as the apk root: 8564 // e.g. /something/app/blah.apk => /something 8565 try { 8566 File f = codePath.getCanonicalFile(); 8567 File parent = f.getParentFile(); // non-null because codePath is a file 8568 File tmp; 8569 while ((tmp = parent.getParentFile()) != null) { 8570 f = parent; 8571 parent = tmp; 8572 } 8573 codeRoot = f; 8574 Slog.w(TAG, "Unrecognized code path " 8575 + codePath + " - using " + codeRoot); 8576 } catch (IOException e) { 8577 // Can't canonicalize the code path -- shenanigans? 8578 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8579 return Environment.getRootDirectory().getPath(); 8580 } 8581 } 8582 return codeRoot.getPath(); 8583 } 8584 8585 /** 8586 * Derive and set the location of native libraries for the given package, 8587 * which varies depending on where and how the package was installed. 8588 */ 8589 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8590 final ApplicationInfo info = pkg.applicationInfo; 8591 final String codePath = pkg.codePath; 8592 final File codeFile = new File(codePath); 8593 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8594 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8595 8596 info.nativeLibraryRootDir = null; 8597 info.nativeLibraryRootRequiresIsa = false; 8598 info.nativeLibraryDir = null; 8599 info.secondaryNativeLibraryDir = null; 8600 8601 if (isApkFile(codeFile)) { 8602 // Monolithic install 8603 if (bundledApp) { 8604 // If "/system/lib64/apkname" exists, assume that is the per-package 8605 // native library directory to use; otherwise use "/system/lib/apkname". 8606 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8607 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8608 getPrimaryInstructionSet(info)); 8609 8610 // This is a bundled system app so choose the path based on the ABI. 8611 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8612 // is just the default path. 8613 final String apkName = deriveCodePathName(codePath); 8614 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8615 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8616 apkName).getAbsolutePath(); 8617 8618 if (info.secondaryCpuAbi != null) { 8619 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8620 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8621 secondaryLibDir, apkName).getAbsolutePath(); 8622 } 8623 } else if (asecApp) { 8624 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8625 .getAbsolutePath(); 8626 } else { 8627 final String apkName = deriveCodePathName(codePath); 8628 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8629 .getAbsolutePath(); 8630 } 8631 8632 info.nativeLibraryRootRequiresIsa = false; 8633 info.nativeLibraryDir = info.nativeLibraryRootDir; 8634 } else { 8635 // Cluster install 8636 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8637 info.nativeLibraryRootRequiresIsa = true; 8638 8639 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8640 getPrimaryInstructionSet(info)).getAbsolutePath(); 8641 8642 if (info.secondaryCpuAbi != null) { 8643 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8644 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8645 } 8646 } 8647 } 8648 8649 /** 8650 * Calculate the abis and roots for a bundled app. These can uniquely 8651 * be determined from the contents of the system partition, i.e whether 8652 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8653 * of this information, and instead assume that the system was built 8654 * sensibly. 8655 */ 8656 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8657 PackageSetting pkgSetting) { 8658 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8659 8660 // If "/system/lib64/apkname" exists, assume that is the per-package 8661 // native library directory to use; otherwise use "/system/lib/apkname". 8662 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8663 setBundledAppAbi(pkg, apkRoot, apkName); 8664 // pkgSetting might be null during rescan following uninstall of updates 8665 // to a bundled app, so accommodate that possibility. The settings in 8666 // that case will be established later from the parsed package. 8667 // 8668 // If the settings aren't null, sync them up with what we've just derived. 8669 // note that apkRoot isn't stored in the package settings. 8670 if (pkgSetting != null) { 8671 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8672 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8673 } 8674 } 8675 8676 /** 8677 * Deduces the ABI of a bundled app and sets the relevant fields on the 8678 * parsed pkg object. 8679 * 8680 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8681 * under which system libraries are installed. 8682 * @param apkName the name of the installed package. 8683 */ 8684 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8685 final File codeFile = new File(pkg.codePath); 8686 8687 final boolean has64BitLibs; 8688 final boolean has32BitLibs; 8689 if (isApkFile(codeFile)) { 8690 // Monolithic install 8691 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8692 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8693 } else { 8694 // Cluster install 8695 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8696 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8697 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8698 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8699 has64BitLibs = (new File(rootDir, isa)).exists(); 8700 } else { 8701 has64BitLibs = false; 8702 } 8703 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8704 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8705 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8706 has32BitLibs = (new File(rootDir, isa)).exists(); 8707 } else { 8708 has32BitLibs = false; 8709 } 8710 } 8711 8712 if (has64BitLibs && !has32BitLibs) { 8713 // The package has 64 bit libs, but not 32 bit libs. Its primary 8714 // ABI should be 64 bit. We can safely assume here that the bundled 8715 // native libraries correspond to the most preferred ABI in the list. 8716 8717 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8718 pkg.applicationInfo.secondaryCpuAbi = null; 8719 } else if (has32BitLibs && !has64BitLibs) { 8720 // The package has 32 bit libs but not 64 bit libs. Its primary 8721 // ABI should be 32 bit. 8722 8723 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8724 pkg.applicationInfo.secondaryCpuAbi = null; 8725 } else if (has32BitLibs && has64BitLibs) { 8726 // The application has both 64 and 32 bit bundled libraries. We check 8727 // here that the app declares multiArch support, and warn if it doesn't. 8728 // 8729 // We will be lenient here and record both ABIs. The primary will be the 8730 // ABI that's higher on the list, i.e, a device that's configured to prefer 8731 // 64 bit apps will see a 64 bit primary ABI, 8732 8733 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8734 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8735 } 8736 8737 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8738 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8739 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8740 } else { 8741 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8742 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8743 } 8744 } else { 8745 pkg.applicationInfo.primaryCpuAbi = null; 8746 pkg.applicationInfo.secondaryCpuAbi = null; 8747 } 8748 } 8749 8750 private void killPackage(PackageParser.Package pkg, String reason) { 8751 // Kill the parent package 8752 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8753 // Kill the child packages 8754 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8755 for (int i = 0; i < childCount; i++) { 8756 PackageParser.Package childPkg = pkg.childPackages.get(i); 8757 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8758 } 8759 } 8760 8761 private void killApplication(String pkgName, int appId, String reason) { 8762 // Request the ActivityManager to kill the process(only for existing packages) 8763 // so that we do not end up in a confused state while the user is still using the older 8764 // version of the application while the new one gets installed. 8765 IActivityManager am = ActivityManagerNative.getDefault(); 8766 if (am != null) { 8767 try { 8768 am.killApplicationWithAppId(pkgName, appId, reason); 8769 } catch (RemoteException e) { 8770 } 8771 } 8772 } 8773 8774 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 8775 // Remove the parent package setting 8776 PackageSetting ps = (PackageSetting) pkg.mExtras; 8777 if (ps != null) { 8778 removePackageLI(ps, chatty); 8779 } 8780 // Remove the child package setting 8781 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8782 for (int i = 0; i < childCount; i++) { 8783 PackageParser.Package childPkg = pkg.childPackages.get(i); 8784 ps = (PackageSetting) childPkg.mExtras; 8785 if (ps != null) { 8786 removePackageLI(ps, chatty); 8787 } 8788 } 8789 } 8790 8791 void removePackageLI(PackageSetting ps, boolean chatty) { 8792 if (DEBUG_INSTALL) { 8793 if (chatty) 8794 Log.d(TAG, "Removing package " + ps.name); 8795 } 8796 8797 // writer 8798 synchronized (mPackages) { 8799 mPackages.remove(ps.name); 8800 final PackageParser.Package pkg = ps.pkg; 8801 if (pkg != null) { 8802 cleanPackageDataStructuresLILPw(pkg, chatty); 8803 } 8804 } 8805 } 8806 8807 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8808 if (DEBUG_INSTALL) { 8809 if (chatty) 8810 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8811 } 8812 8813 // writer 8814 synchronized (mPackages) { 8815 // Remove the parent package 8816 mPackages.remove(pkg.applicationInfo.packageName); 8817 cleanPackageDataStructuresLILPw(pkg, chatty); 8818 8819 // Remove the child packages 8820 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8821 for (int i = 0; i < childCount; i++) { 8822 PackageParser.Package childPkg = pkg.childPackages.get(i); 8823 mPackages.remove(childPkg.applicationInfo.packageName); 8824 cleanPackageDataStructuresLILPw(childPkg, chatty); 8825 } 8826 } 8827 } 8828 8829 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8830 int N = pkg.providers.size(); 8831 StringBuilder r = null; 8832 int i; 8833 for (i=0; i<N; i++) { 8834 PackageParser.Provider p = pkg.providers.get(i); 8835 mProviders.removeProvider(p); 8836 if (p.info.authority == null) { 8837 8838 /* There was another ContentProvider with this authority when 8839 * this app was installed so this authority is null, 8840 * Ignore it as we don't have to unregister the provider. 8841 */ 8842 continue; 8843 } 8844 String names[] = p.info.authority.split(";"); 8845 for (int j = 0; j < names.length; j++) { 8846 if (mProvidersByAuthority.get(names[j]) == p) { 8847 mProvidersByAuthority.remove(names[j]); 8848 if (DEBUG_REMOVE) { 8849 if (chatty) 8850 Log.d(TAG, "Unregistered content provider: " + names[j] 8851 + ", className = " + p.info.name + ", isSyncable = " 8852 + p.info.isSyncable); 8853 } 8854 } 8855 } 8856 if (DEBUG_REMOVE && chatty) { 8857 if (r == null) { 8858 r = new StringBuilder(256); 8859 } else { 8860 r.append(' '); 8861 } 8862 r.append(p.info.name); 8863 } 8864 } 8865 if (r != null) { 8866 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8867 } 8868 8869 N = pkg.services.size(); 8870 r = null; 8871 for (i=0; i<N; i++) { 8872 PackageParser.Service s = pkg.services.get(i); 8873 mServices.removeService(s); 8874 if (chatty) { 8875 if (r == null) { 8876 r = new StringBuilder(256); 8877 } else { 8878 r.append(' '); 8879 } 8880 r.append(s.info.name); 8881 } 8882 } 8883 if (r != null) { 8884 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8885 } 8886 8887 N = pkg.receivers.size(); 8888 r = null; 8889 for (i=0; i<N; i++) { 8890 PackageParser.Activity a = pkg.receivers.get(i); 8891 mReceivers.removeActivity(a, "receiver"); 8892 if (DEBUG_REMOVE && chatty) { 8893 if (r == null) { 8894 r = new StringBuilder(256); 8895 } else { 8896 r.append(' '); 8897 } 8898 r.append(a.info.name); 8899 } 8900 } 8901 if (r != null) { 8902 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8903 } 8904 8905 N = pkg.activities.size(); 8906 r = null; 8907 for (i=0; i<N; i++) { 8908 PackageParser.Activity a = pkg.activities.get(i); 8909 mActivities.removeActivity(a, "activity"); 8910 if (DEBUG_REMOVE && chatty) { 8911 if (r == null) { 8912 r = new StringBuilder(256); 8913 } else { 8914 r.append(' '); 8915 } 8916 r.append(a.info.name); 8917 } 8918 } 8919 if (r != null) { 8920 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8921 } 8922 8923 N = pkg.permissions.size(); 8924 r = null; 8925 for (i=0; i<N; i++) { 8926 PackageParser.Permission p = pkg.permissions.get(i); 8927 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8928 if (bp == null) { 8929 bp = mSettings.mPermissionTrees.get(p.info.name); 8930 } 8931 if (bp != null && bp.perm == p) { 8932 bp.perm = null; 8933 if (DEBUG_REMOVE && chatty) { 8934 if (r == null) { 8935 r = new StringBuilder(256); 8936 } else { 8937 r.append(' '); 8938 } 8939 r.append(p.info.name); 8940 } 8941 } 8942 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8943 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8944 if (appOpPkgs != null) { 8945 appOpPkgs.remove(pkg.packageName); 8946 } 8947 } 8948 } 8949 if (r != null) { 8950 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8951 } 8952 8953 N = pkg.requestedPermissions.size(); 8954 r = null; 8955 for (i=0; i<N; i++) { 8956 String perm = pkg.requestedPermissions.get(i); 8957 BasePermission bp = mSettings.mPermissions.get(perm); 8958 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8959 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8960 if (appOpPkgs != null) { 8961 appOpPkgs.remove(pkg.packageName); 8962 if (appOpPkgs.isEmpty()) { 8963 mAppOpPermissionPackages.remove(perm); 8964 } 8965 } 8966 } 8967 } 8968 if (r != null) { 8969 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8970 } 8971 8972 N = pkg.instrumentation.size(); 8973 r = null; 8974 for (i=0; i<N; i++) { 8975 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8976 mInstrumentation.remove(a.getComponentName()); 8977 if (DEBUG_REMOVE && chatty) { 8978 if (r == null) { 8979 r = new StringBuilder(256); 8980 } else { 8981 r.append(' '); 8982 } 8983 r.append(a.info.name); 8984 } 8985 } 8986 if (r != null) { 8987 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8988 } 8989 8990 r = null; 8991 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8992 // Only system apps can hold shared libraries. 8993 if (pkg.libraryNames != null) { 8994 for (i=0; i<pkg.libraryNames.size(); i++) { 8995 String name = pkg.libraryNames.get(i); 8996 SharedLibraryEntry cur = mSharedLibraries.get(name); 8997 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8998 mSharedLibraries.remove(name); 8999 if (DEBUG_REMOVE && chatty) { 9000 if (r == null) { 9001 r = new StringBuilder(256); 9002 } else { 9003 r.append(' '); 9004 } 9005 r.append(name); 9006 } 9007 } 9008 } 9009 } 9010 } 9011 if (r != null) { 9012 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9013 } 9014 } 9015 9016 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9017 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9018 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9019 return true; 9020 } 9021 } 9022 return false; 9023 } 9024 9025 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9026 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9027 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9028 9029 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9030 // Update the parent permissions 9031 updatePermissionsLPw(pkg.packageName, pkg, flags); 9032 // Update the child permissions 9033 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9034 for (int i = 0; i < childCount; i++) { 9035 PackageParser.Package childPkg = pkg.childPackages.get(i); 9036 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9037 } 9038 } 9039 9040 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9041 int flags) { 9042 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9043 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9044 } 9045 9046 private void updatePermissionsLPw(String changingPkg, 9047 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9048 // Make sure there are no dangling permission trees. 9049 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9050 while (it.hasNext()) { 9051 final BasePermission bp = it.next(); 9052 if (bp.packageSetting == null) { 9053 // We may not yet have parsed the package, so just see if 9054 // we still know about its settings. 9055 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9056 } 9057 if (bp.packageSetting == null) { 9058 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9059 + " from package " + bp.sourcePackage); 9060 it.remove(); 9061 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9062 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9063 Slog.i(TAG, "Removing old permission tree: " + bp.name 9064 + " from package " + bp.sourcePackage); 9065 flags |= UPDATE_PERMISSIONS_ALL; 9066 it.remove(); 9067 } 9068 } 9069 } 9070 9071 // Make sure all dynamic permissions have been assigned to a package, 9072 // and make sure there are no dangling permissions. 9073 it = mSettings.mPermissions.values().iterator(); 9074 while (it.hasNext()) { 9075 final BasePermission bp = it.next(); 9076 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9077 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9078 + bp.name + " pkg=" + bp.sourcePackage 9079 + " info=" + bp.pendingInfo); 9080 if (bp.packageSetting == null && bp.pendingInfo != null) { 9081 final BasePermission tree = findPermissionTreeLP(bp.name); 9082 if (tree != null && tree.perm != null) { 9083 bp.packageSetting = tree.packageSetting; 9084 bp.perm = new PackageParser.Permission(tree.perm.owner, 9085 new PermissionInfo(bp.pendingInfo)); 9086 bp.perm.info.packageName = tree.perm.info.packageName; 9087 bp.perm.info.name = bp.name; 9088 bp.uid = tree.uid; 9089 } 9090 } 9091 } 9092 if (bp.packageSetting == null) { 9093 // We may not yet have parsed the package, so just see if 9094 // we still know about its settings. 9095 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9096 } 9097 if (bp.packageSetting == null) { 9098 Slog.w(TAG, "Removing dangling permission: " + bp.name 9099 + " from package " + bp.sourcePackage); 9100 it.remove(); 9101 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9102 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9103 Slog.i(TAG, "Removing old permission: " + bp.name 9104 + " from package " + bp.sourcePackage); 9105 flags |= UPDATE_PERMISSIONS_ALL; 9106 it.remove(); 9107 } 9108 } 9109 } 9110 9111 // Now update the permissions for all packages, in particular 9112 // replace the granted permissions of the system packages. 9113 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9114 for (PackageParser.Package pkg : mPackages.values()) { 9115 if (pkg != pkgInfo) { 9116 // Only replace for packages on requested volume 9117 final String volumeUuid = getVolumeUuidForPackage(pkg); 9118 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9119 && Objects.equals(replaceVolumeUuid, volumeUuid); 9120 grantPermissionsLPw(pkg, replace, changingPkg); 9121 } 9122 } 9123 } 9124 9125 if (pkgInfo != null) { 9126 // Only replace for packages on requested volume 9127 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9128 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9129 && Objects.equals(replaceVolumeUuid, volumeUuid); 9130 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9131 } 9132 } 9133 9134 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9135 String packageOfInterest) { 9136 // IMPORTANT: There are two types of permissions: install and runtime. 9137 // Install time permissions are granted when the app is installed to 9138 // all device users and users added in the future. Runtime permissions 9139 // are granted at runtime explicitly to specific users. Normal and signature 9140 // protected permissions are install time permissions. Dangerous permissions 9141 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9142 // otherwise they are runtime permissions. This function does not manage 9143 // runtime permissions except for the case an app targeting Lollipop MR1 9144 // being upgraded to target a newer SDK, in which case dangerous permissions 9145 // are transformed from install time to runtime ones. 9146 9147 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9148 if (ps == null) { 9149 return; 9150 } 9151 9152 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9153 9154 PermissionsState permissionsState = ps.getPermissionsState(); 9155 PermissionsState origPermissions = permissionsState; 9156 9157 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9158 9159 boolean runtimePermissionsRevoked = false; 9160 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9161 9162 boolean changedInstallPermission = false; 9163 9164 if (replace) { 9165 ps.installPermissionsFixed = false; 9166 if (!ps.isSharedUser()) { 9167 origPermissions = new PermissionsState(permissionsState); 9168 permissionsState.reset(); 9169 } else { 9170 // We need to know only about runtime permission changes since the 9171 // calling code always writes the install permissions state but 9172 // the runtime ones are written only if changed. The only cases of 9173 // changed runtime permissions here are promotion of an install to 9174 // runtime and revocation of a runtime from a shared user. 9175 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9176 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9177 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9178 runtimePermissionsRevoked = true; 9179 } 9180 } 9181 } 9182 9183 permissionsState.setGlobalGids(mGlobalGids); 9184 9185 final int N = pkg.requestedPermissions.size(); 9186 for (int i=0; i<N; i++) { 9187 final String name = pkg.requestedPermissions.get(i); 9188 final BasePermission bp = mSettings.mPermissions.get(name); 9189 9190 if (DEBUG_INSTALL) { 9191 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9192 } 9193 9194 if (bp == null || bp.packageSetting == null) { 9195 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9196 Slog.w(TAG, "Unknown permission " + name 9197 + " in package " + pkg.packageName); 9198 } 9199 continue; 9200 } 9201 9202 final String perm = bp.name; 9203 boolean allowedSig = false; 9204 int grant = GRANT_DENIED; 9205 9206 // Keep track of app op permissions. 9207 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9208 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9209 if (pkgs == null) { 9210 pkgs = new ArraySet<>(); 9211 mAppOpPermissionPackages.put(bp.name, pkgs); 9212 } 9213 pkgs.add(pkg.packageName); 9214 } 9215 9216 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9217 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9218 >= Build.VERSION_CODES.M; 9219 switch (level) { 9220 case PermissionInfo.PROTECTION_NORMAL: { 9221 // For all apps normal permissions are install time ones. 9222 grant = GRANT_INSTALL; 9223 } break; 9224 9225 case PermissionInfo.PROTECTION_DANGEROUS: { 9226 // If a permission review is required for legacy apps we represent 9227 // their permissions as always granted runtime ones since we need 9228 // to keep the review required permission flag per user while an 9229 // install permission's state is shared across all users. 9230 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9231 // For legacy apps dangerous permissions are install time ones. 9232 grant = GRANT_INSTALL; 9233 } else if (origPermissions.hasInstallPermission(bp.name)) { 9234 // For legacy apps that became modern, install becomes runtime. 9235 grant = GRANT_UPGRADE; 9236 } else if (mPromoteSystemApps 9237 && isSystemApp(ps) 9238 && mExistingSystemPackages.contains(ps.name)) { 9239 // For legacy system apps, install becomes runtime. 9240 // We cannot check hasInstallPermission() for system apps since those 9241 // permissions were granted implicitly and not persisted pre-M. 9242 grant = GRANT_UPGRADE; 9243 } else { 9244 // For modern apps keep runtime permissions unchanged. 9245 grant = GRANT_RUNTIME; 9246 } 9247 } break; 9248 9249 case PermissionInfo.PROTECTION_SIGNATURE: { 9250 // For all apps signature permissions are install time ones. 9251 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9252 if (allowedSig) { 9253 grant = GRANT_INSTALL; 9254 } 9255 } break; 9256 } 9257 9258 if (DEBUG_INSTALL) { 9259 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9260 } 9261 9262 if (grant != GRANT_DENIED) { 9263 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9264 // If this is an existing, non-system package, then 9265 // we can't add any new permissions to it. 9266 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9267 // Except... if this is a permission that was added 9268 // to the platform (note: need to only do this when 9269 // updating the platform). 9270 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9271 grant = GRANT_DENIED; 9272 } 9273 } 9274 } 9275 9276 switch (grant) { 9277 case GRANT_INSTALL: { 9278 // Revoke this as runtime permission to handle the case of 9279 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9280 for (int userId : UserManagerService.getInstance().getUserIds()) { 9281 if (origPermissions.getRuntimePermissionState( 9282 bp.name, userId) != null) { 9283 // Revoke the runtime permission and clear the flags. 9284 origPermissions.revokeRuntimePermission(bp, userId); 9285 origPermissions.updatePermissionFlags(bp, userId, 9286 PackageManager.MASK_PERMISSION_FLAGS, 0); 9287 // If we revoked a permission permission, we have to write. 9288 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9289 changedRuntimePermissionUserIds, userId); 9290 } 9291 } 9292 // Grant an install permission. 9293 if (permissionsState.grantInstallPermission(bp) != 9294 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9295 changedInstallPermission = true; 9296 } 9297 } break; 9298 9299 case GRANT_RUNTIME: { 9300 // Grant previously granted runtime permissions. 9301 for (int userId : UserManagerService.getInstance().getUserIds()) { 9302 PermissionState permissionState = origPermissions 9303 .getRuntimePermissionState(bp.name, userId); 9304 int flags = permissionState != null 9305 ? permissionState.getFlags() : 0; 9306 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9307 if (permissionsState.grantRuntimePermission(bp, userId) == 9308 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9309 // If we cannot put the permission as it was, we have to write. 9310 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9311 changedRuntimePermissionUserIds, userId); 9312 } 9313 // If the app supports runtime permissions no need for a review. 9314 if (Build.PERMISSIONS_REVIEW_REQUIRED 9315 && appSupportsRuntimePermissions 9316 && (flags & PackageManager 9317 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9318 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9319 // Since we changed the flags, we have to write. 9320 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9321 changedRuntimePermissionUserIds, userId); 9322 } 9323 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9324 && !appSupportsRuntimePermissions) { 9325 // For legacy apps that need a permission review, every new 9326 // runtime permission is granted but it is pending a review. 9327 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9328 permissionsState.grantRuntimePermission(bp, userId); 9329 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9330 // We changed the permission and flags, hence have to write. 9331 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9332 changedRuntimePermissionUserIds, userId); 9333 } 9334 } 9335 // Propagate the permission flags. 9336 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9337 } 9338 } break; 9339 9340 case GRANT_UPGRADE: { 9341 // Grant runtime permissions for a previously held install permission. 9342 PermissionState permissionState = origPermissions 9343 .getInstallPermissionState(bp.name); 9344 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9345 9346 if (origPermissions.revokeInstallPermission(bp) 9347 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9348 // We will be transferring the permission flags, so clear them. 9349 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9350 PackageManager.MASK_PERMISSION_FLAGS, 0); 9351 changedInstallPermission = true; 9352 } 9353 9354 // If the permission is not to be promoted to runtime we ignore it and 9355 // also its other flags as they are not applicable to install permissions. 9356 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9357 for (int userId : currentUserIds) { 9358 if (permissionsState.grantRuntimePermission(bp, userId) != 9359 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9360 // Transfer the permission flags. 9361 permissionsState.updatePermissionFlags(bp, userId, 9362 flags, flags); 9363 // If we granted the permission, we have to write. 9364 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9365 changedRuntimePermissionUserIds, userId); 9366 } 9367 } 9368 } 9369 } break; 9370 9371 default: { 9372 if (packageOfInterest == null 9373 || packageOfInterest.equals(pkg.packageName)) { 9374 Slog.w(TAG, "Not granting permission " + perm 9375 + " to package " + pkg.packageName 9376 + " because it was previously installed without"); 9377 } 9378 } break; 9379 } 9380 } else { 9381 if (permissionsState.revokeInstallPermission(bp) != 9382 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9383 // Also drop the permission flags. 9384 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9385 PackageManager.MASK_PERMISSION_FLAGS, 0); 9386 changedInstallPermission = true; 9387 Slog.i(TAG, "Un-granting permission " + perm 9388 + " from package " + pkg.packageName 9389 + " (protectionLevel=" + bp.protectionLevel 9390 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9391 + ")"); 9392 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9393 // Don't print warning for app op permissions, since it is fine for them 9394 // not to be granted, there is a UI for the user to decide. 9395 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9396 Slog.w(TAG, "Not granting permission " + perm 9397 + " to package " + pkg.packageName 9398 + " (protectionLevel=" + bp.protectionLevel 9399 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9400 + ")"); 9401 } 9402 } 9403 } 9404 } 9405 9406 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9407 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9408 // This is the first that we have heard about this package, so the 9409 // permissions we have now selected are fixed until explicitly 9410 // changed. 9411 ps.installPermissionsFixed = true; 9412 } 9413 9414 // Persist the runtime permissions state for users with changes. If permissions 9415 // were revoked because no app in the shared user declares them we have to 9416 // write synchronously to avoid losing runtime permissions state. 9417 for (int userId : changedRuntimePermissionUserIds) { 9418 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9419 } 9420 9421 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9422 } 9423 9424 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9425 boolean allowed = false; 9426 final int NP = PackageParser.NEW_PERMISSIONS.length; 9427 for (int ip=0; ip<NP; ip++) { 9428 final PackageParser.NewPermissionInfo npi 9429 = PackageParser.NEW_PERMISSIONS[ip]; 9430 if (npi.name.equals(perm) 9431 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9432 allowed = true; 9433 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9434 + pkg.packageName); 9435 break; 9436 } 9437 } 9438 return allowed; 9439 } 9440 9441 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9442 BasePermission bp, PermissionsState origPermissions) { 9443 boolean allowed; 9444 allowed = (compareSignatures( 9445 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9446 == PackageManager.SIGNATURE_MATCH) 9447 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9448 == PackageManager.SIGNATURE_MATCH); 9449 if (!allowed && (bp.protectionLevel 9450 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9451 if (isSystemApp(pkg)) { 9452 // For updated system applications, a system permission 9453 // is granted only if it had been defined by the original application. 9454 if (pkg.isUpdatedSystemApp()) { 9455 final PackageSetting sysPs = mSettings 9456 .getDisabledSystemPkgLPr(pkg.packageName); 9457 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9458 // If the original was granted this permission, we take 9459 // that grant decision as read and propagate it to the 9460 // update. 9461 if (sysPs.isPrivileged()) { 9462 allowed = true; 9463 } 9464 } else { 9465 // The system apk may have been updated with an older 9466 // version of the one on the data partition, but which 9467 // granted a new system permission that it didn't have 9468 // before. In this case we do want to allow the app to 9469 // now get the new permission if the ancestral apk is 9470 // privileged to get it. 9471 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9472 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9473 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9474 allowed = true; 9475 break; 9476 } 9477 } 9478 } 9479 // Also if a privileged parent package on the system image or any of 9480 // its children requested a privileged permission, the updated child 9481 // packages can also get the permission. 9482 if (pkg.parentPackage != null) { 9483 final PackageSetting disabledSysParentPs = mSettings 9484 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9485 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9486 && disabledSysParentPs.isPrivileged()) { 9487 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9488 allowed = true; 9489 } else if (disabledSysParentPs.pkg.childPackages != null) { 9490 final int count = disabledSysParentPs.pkg.childPackages.size(); 9491 for (int i = 0; i < count; i++) { 9492 PackageParser.Package disabledSysChildPkg = 9493 disabledSysParentPs.pkg.childPackages.get(i); 9494 if (isPackageRequestingPermission(disabledSysChildPkg, 9495 perm)) { 9496 allowed = true; 9497 break; 9498 } 9499 } 9500 } 9501 } 9502 } 9503 } 9504 } else { 9505 allowed = isPrivilegedApp(pkg); 9506 } 9507 } 9508 } 9509 if (!allowed) { 9510 if (!allowed && (bp.protectionLevel 9511 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9512 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9513 // If this was a previously normal/dangerous permission that got moved 9514 // to a system permission as part of the runtime permission redesign, then 9515 // we still want to blindly grant it to old apps. 9516 allowed = true; 9517 } 9518 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9519 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9520 // If this permission is to be granted to the system installer and 9521 // this app is an installer, then it gets the permission. 9522 allowed = true; 9523 } 9524 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9525 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9526 // If this permission is to be granted to the system verifier and 9527 // this app is a verifier, then it gets the permission. 9528 allowed = true; 9529 } 9530 if (!allowed && (bp.protectionLevel 9531 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9532 && isSystemApp(pkg)) { 9533 // Any pre-installed system app is allowed to get this permission. 9534 allowed = true; 9535 } 9536 if (!allowed && (bp.protectionLevel 9537 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9538 // For development permissions, a development permission 9539 // is granted only if it was already granted. 9540 allowed = origPermissions.hasInstallPermission(perm); 9541 } 9542 } 9543 return allowed; 9544 } 9545 9546 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9547 final int permCount = pkg.requestedPermissions.size(); 9548 for (int j = 0; j < permCount; j++) { 9549 String requestedPermission = pkg.requestedPermissions.get(j); 9550 if (permission.equals(requestedPermission)) { 9551 return true; 9552 } 9553 } 9554 return false; 9555 } 9556 9557 final class ActivityIntentResolver 9558 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9559 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9560 boolean defaultOnly, int userId) { 9561 if (!sUserManager.exists(userId)) return null; 9562 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9563 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9564 } 9565 9566 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9567 int userId) { 9568 if (!sUserManager.exists(userId)) return null; 9569 mFlags = flags; 9570 return super.queryIntent(intent, resolvedType, 9571 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9572 } 9573 9574 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9575 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9576 if (!sUserManager.exists(userId)) return null; 9577 if (packageActivities == null) { 9578 return null; 9579 } 9580 mFlags = flags; 9581 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9582 final int N = packageActivities.size(); 9583 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9584 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9585 9586 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9587 for (int i = 0; i < N; ++i) { 9588 intentFilters = packageActivities.get(i).intents; 9589 if (intentFilters != null && intentFilters.size() > 0) { 9590 PackageParser.ActivityIntentInfo[] array = 9591 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9592 intentFilters.toArray(array); 9593 listCut.add(array); 9594 } 9595 } 9596 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9597 } 9598 9599 public final void addActivity(PackageParser.Activity a, String type) { 9600 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9601 mActivities.put(a.getComponentName(), a); 9602 if (DEBUG_SHOW_INFO) 9603 Log.v( 9604 TAG, " " + type + " " + 9605 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9606 if (DEBUG_SHOW_INFO) 9607 Log.v(TAG, " Class=" + a.info.name); 9608 final int NI = a.intents.size(); 9609 for (int j=0; j<NI; j++) { 9610 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9611 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9612 intent.setPriority(0); 9613 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9614 + a.className + " with priority > 0, forcing to 0"); 9615 } 9616 if (DEBUG_SHOW_INFO) { 9617 Log.v(TAG, " IntentFilter:"); 9618 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9619 } 9620 if (!intent.debugCheck()) { 9621 Log.w(TAG, "==> For Activity " + a.info.name); 9622 } 9623 addFilter(intent); 9624 } 9625 } 9626 9627 public final void removeActivity(PackageParser.Activity a, String type) { 9628 mActivities.remove(a.getComponentName()); 9629 if (DEBUG_SHOW_INFO) { 9630 Log.v(TAG, " " + type + " " 9631 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9632 : a.info.name) + ":"); 9633 Log.v(TAG, " Class=" + a.info.name); 9634 } 9635 final int NI = a.intents.size(); 9636 for (int j=0; j<NI; j++) { 9637 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9638 if (DEBUG_SHOW_INFO) { 9639 Log.v(TAG, " IntentFilter:"); 9640 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9641 } 9642 removeFilter(intent); 9643 } 9644 } 9645 9646 @Override 9647 protected boolean allowFilterResult( 9648 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9649 ActivityInfo filterAi = filter.activity.info; 9650 for (int i=dest.size()-1; i>=0; i--) { 9651 ActivityInfo destAi = dest.get(i).activityInfo; 9652 if (destAi.name == filterAi.name 9653 && destAi.packageName == filterAi.packageName) { 9654 return false; 9655 } 9656 } 9657 return true; 9658 } 9659 9660 @Override 9661 protected ActivityIntentInfo[] newArray(int size) { 9662 return new ActivityIntentInfo[size]; 9663 } 9664 9665 @Override 9666 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9667 if (!sUserManager.exists(userId)) return true; 9668 PackageParser.Package p = filter.activity.owner; 9669 if (p != null) { 9670 PackageSetting ps = (PackageSetting)p.mExtras; 9671 if (ps != null) { 9672 // System apps are never considered stopped for purposes of 9673 // filtering, because there may be no way for the user to 9674 // actually re-launch them. 9675 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9676 && ps.getStopped(userId); 9677 } 9678 } 9679 return false; 9680 } 9681 9682 @Override 9683 protected boolean isPackageForFilter(String packageName, 9684 PackageParser.ActivityIntentInfo info) { 9685 return packageName.equals(info.activity.owner.packageName); 9686 } 9687 9688 @Override 9689 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9690 int match, int userId) { 9691 if (!sUserManager.exists(userId)) return null; 9692 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9693 return null; 9694 } 9695 final PackageParser.Activity activity = info.activity; 9696 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9697 if (ps == null) { 9698 return null; 9699 } 9700 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9701 ps.readUserState(userId), userId); 9702 if (ai == null) { 9703 return null; 9704 } 9705 final ResolveInfo res = new ResolveInfo(); 9706 res.activityInfo = ai; 9707 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9708 res.filter = info; 9709 } 9710 if (info != null) { 9711 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9712 } 9713 res.priority = info.getPriority(); 9714 res.preferredOrder = activity.owner.mPreferredOrder; 9715 //System.out.println("Result: " + res.activityInfo.className + 9716 // " = " + res.priority); 9717 res.match = match; 9718 res.isDefault = info.hasDefault; 9719 res.labelRes = info.labelRes; 9720 res.nonLocalizedLabel = info.nonLocalizedLabel; 9721 if (userNeedsBadging(userId)) { 9722 res.noResourceId = true; 9723 } else { 9724 res.icon = info.icon; 9725 } 9726 res.iconResourceId = info.icon; 9727 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9728 return res; 9729 } 9730 9731 @Override 9732 protected void sortResults(List<ResolveInfo> results) { 9733 Collections.sort(results, mResolvePrioritySorter); 9734 } 9735 9736 @Override 9737 protected void dumpFilter(PrintWriter out, String prefix, 9738 PackageParser.ActivityIntentInfo filter) { 9739 out.print(prefix); out.print( 9740 Integer.toHexString(System.identityHashCode(filter.activity))); 9741 out.print(' '); 9742 filter.activity.printComponentShortName(out); 9743 out.print(" filter "); 9744 out.println(Integer.toHexString(System.identityHashCode(filter))); 9745 } 9746 9747 @Override 9748 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9749 return filter.activity; 9750 } 9751 9752 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9753 PackageParser.Activity activity = (PackageParser.Activity)label; 9754 out.print(prefix); out.print( 9755 Integer.toHexString(System.identityHashCode(activity))); 9756 out.print(' '); 9757 activity.printComponentShortName(out); 9758 if (count > 1) { 9759 out.print(" ("); out.print(count); out.print(" filters)"); 9760 } 9761 out.println(); 9762 } 9763 9764// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9765// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9766// final List<ResolveInfo> retList = Lists.newArrayList(); 9767// while (i.hasNext()) { 9768// final ResolveInfo resolveInfo = i.next(); 9769// if (isEnabledLP(resolveInfo.activityInfo)) { 9770// retList.add(resolveInfo); 9771// } 9772// } 9773// return retList; 9774// } 9775 9776 // Keys are String (activity class name), values are Activity. 9777 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9778 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9779 private int mFlags; 9780 } 9781 9782 private final class ServiceIntentResolver 9783 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9784 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9785 boolean defaultOnly, int userId) { 9786 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9787 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9788 } 9789 9790 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9791 int userId) { 9792 if (!sUserManager.exists(userId)) return null; 9793 mFlags = flags; 9794 return super.queryIntent(intent, resolvedType, 9795 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9796 } 9797 9798 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9799 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9800 if (!sUserManager.exists(userId)) return null; 9801 if (packageServices == null) { 9802 return null; 9803 } 9804 mFlags = flags; 9805 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9806 final int N = packageServices.size(); 9807 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9808 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9809 9810 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9811 for (int i = 0; i < N; ++i) { 9812 intentFilters = packageServices.get(i).intents; 9813 if (intentFilters != null && intentFilters.size() > 0) { 9814 PackageParser.ServiceIntentInfo[] array = 9815 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9816 intentFilters.toArray(array); 9817 listCut.add(array); 9818 } 9819 } 9820 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9821 } 9822 9823 public final void addService(PackageParser.Service s) { 9824 mServices.put(s.getComponentName(), s); 9825 if (DEBUG_SHOW_INFO) { 9826 Log.v(TAG, " " 9827 + (s.info.nonLocalizedLabel != null 9828 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9829 Log.v(TAG, " Class=" + s.info.name); 9830 } 9831 final int NI = s.intents.size(); 9832 int j; 9833 for (j=0; j<NI; j++) { 9834 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9835 if (DEBUG_SHOW_INFO) { 9836 Log.v(TAG, " IntentFilter:"); 9837 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9838 } 9839 if (!intent.debugCheck()) { 9840 Log.w(TAG, "==> For Service " + s.info.name); 9841 } 9842 addFilter(intent); 9843 } 9844 } 9845 9846 public final void removeService(PackageParser.Service s) { 9847 mServices.remove(s.getComponentName()); 9848 if (DEBUG_SHOW_INFO) { 9849 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9850 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9851 Log.v(TAG, " Class=" + s.info.name); 9852 } 9853 final int NI = s.intents.size(); 9854 int j; 9855 for (j=0; j<NI; j++) { 9856 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9857 if (DEBUG_SHOW_INFO) { 9858 Log.v(TAG, " IntentFilter:"); 9859 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9860 } 9861 removeFilter(intent); 9862 } 9863 } 9864 9865 @Override 9866 protected boolean allowFilterResult( 9867 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9868 ServiceInfo filterSi = filter.service.info; 9869 for (int i=dest.size()-1; i>=0; i--) { 9870 ServiceInfo destAi = dest.get(i).serviceInfo; 9871 if (destAi.name == filterSi.name 9872 && destAi.packageName == filterSi.packageName) { 9873 return false; 9874 } 9875 } 9876 return true; 9877 } 9878 9879 @Override 9880 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9881 return new PackageParser.ServiceIntentInfo[size]; 9882 } 9883 9884 @Override 9885 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9886 if (!sUserManager.exists(userId)) return true; 9887 PackageParser.Package p = filter.service.owner; 9888 if (p != null) { 9889 PackageSetting ps = (PackageSetting)p.mExtras; 9890 if (ps != null) { 9891 // System apps are never considered stopped for purposes of 9892 // filtering, because there may be no way for the user to 9893 // actually re-launch them. 9894 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9895 && ps.getStopped(userId); 9896 } 9897 } 9898 return false; 9899 } 9900 9901 @Override 9902 protected boolean isPackageForFilter(String packageName, 9903 PackageParser.ServiceIntentInfo info) { 9904 return packageName.equals(info.service.owner.packageName); 9905 } 9906 9907 @Override 9908 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9909 int match, int userId) { 9910 if (!sUserManager.exists(userId)) return null; 9911 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9912 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9913 return null; 9914 } 9915 final PackageParser.Service service = info.service; 9916 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9917 if (ps == null) { 9918 return null; 9919 } 9920 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9921 ps.readUserState(userId), userId); 9922 if (si == null) { 9923 return null; 9924 } 9925 final ResolveInfo res = new ResolveInfo(); 9926 res.serviceInfo = si; 9927 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9928 res.filter = filter; 9929 } 9930 res.priority = info.getPriority(); 9931 res.preferredOrder = service.owner.mPreferredOrder; 9932 res.match = match; 9933 res.isDefault = info.hasDefault; 9934 res.labelRes = info.labelRes; 9935 res.nonLocalizedLabel = info.nonLocalizedLabel; 9936 res.icon = info.icon; 9937 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9938 return res; 9939 } 9940 9941 @Override 9942 protected void sortResults(List<ResolveInfo> results) { 9943 Collections.sort(results, mResolvePrioritySorter); 9944 } 9945 9946 @Override 9947 protected void dumpFilter(PrintWriter out, String prefix, 9948 PackageParser.ServiceIntentInfo filter) { 9949 out.print(prefix); out.print( 9950 Integer.toHexString(System.identityHashCode(filter.service))); 9951 out.print(' '); 9952 filter.service.printComponentShortName(out); 9953 out.print(" filter "); 9954 out.println(Integer.toHexString(System.identityHashCode(filter))); 9955 } 9956 9957 @Override 9958 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9959 return filter.service; 9960 } 9961 9962 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9963 PackageParser.Service service = (PackageParser.Service)label; 9964 out.print(prefix); out.print( 9965 Integer.toHexString(System.identityHashCode(service))); 9966 out.print(' '); 9967 service.printComponentShortName(out); 9968 if (count > 1) { 9969 out.print(" ("); out.print(count); out.print(" filters)"); 9970 } 9971 out.println(); 9972 } 9973 9974// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9975// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9976// final List<ResolveInfo> retList = Lists.newArrayList(); 9977// while (i.hasNext()) { 9978// final ResolveInfo resolveInfo = (ResolveInfo) i; 9979// if (isEnabledLP(resolveInfo.serviceInfo)) { 9980// retList.add(resolveInfo); 9981// } 9982// } 9983// return retList; 9984// } 9985 9986 // Keys are String (activity class name), values are Activity. 9987 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9988 = new ArrayMap<ComponentName, PackageParser.Service>(); 9989 private int mFlags; 9990 }; 9991 9992 private final class ProviderIntentResolver 9993 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9994 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9995 boolean defaultOnly, int userId) { 9996 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9997 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9998 } 9999 10000 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10001 int userId) { 10002 if (!sUserManager.exists(userId)) 10003 return null; 10004 mFlags = flags; 10005 return super.queryIntent(intent, resolvedType, 10006 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10007 } 10008 10009 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10010 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10011 if (!sUserManager.exists(userId)) 10012 return null; 10013 if (packageProviders == null) { 10014 return null; 10015 } 10016 mFlags = flags; 10017 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10018 final int N = packageProviders.size(); 10019 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10020 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10021 10022 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10023 for (int i = 0; i < N; ++i) { 10024 intentFilters = packageProviders.get(i).intents; 10025 if (intentFilters != null && intentFilters.size() > 0) { 10026 PackageParser.ProviderIntentInfo[] array = 10027 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10028 intentFilters.toArray(array); 10029 listCut.add(array); 10030 } 10031 } 10032 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10033 } 10034 10035 public final void addProvider(PackageParser.Provider p) { 10036 if (mProviders.containsKey(p.getComponentName())) { 10037 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10038 return; 10039 } 10040 10041 mProviders.put(p.getComponentName(), p); 10042 if (DEBUG_SHOW_INFO) { 10043 Log.v(TAG, " " 10044 + (p.info.nonLocalizedLabel != null 10045 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10046 Log.v(TAG, " Class=" + p.info.name); 10047 } 10048 final int NI = p.intents.size(); 10049 int j; 10050 for (j = 0; j < NI; j++) { 10051 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10052 if (DEBUG_SHOW_INFO) { 10053 Log.v(TAG, " IntentFilter:"); 10054 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10055 } 10056 if (!intent.debugCheck()) { 10057 Log.w(TAG, "==> For Provider " + p.info.name); 10058 } 10059 addFilter(intent); 10060 } 10061 } 10062 10063 public final void removeProvider(PackageParser.Provider p) { 10064 mProviders.remove(p.getComponentName()); 10065 if (DEBUG_SHOW_INFO) { 10066 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10067 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10068 Log.v(TAG, " Class=" + p.info.name); 10069 } 10070 final int NI = p.intents.size(); 10071 int j; 10072 for (j = 0; j < NI; j++) { 10073 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10074 if (DEBUG_SHOW_INFO) { 10075 Log.v(TAG, " IntentFilter:"); 10076 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10077 } 10078 removeFilter(intent); 10079 } 10080 } 10081 10082 @Override 10083 protected boolean allowFilterResult( 10084 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10085 ProviderInfo filterPi = filter.provider.info; 10086 for (int i = dest.size() - 1; i >= 0; i--) { 10087 ProviderInfo destPi = dest.get(i).providerInfo; 10088 if (destPi.name == filterPi.name 10089 && destPi.packageName == filterPi.packageName) { 10090 return false; 10091 } 10092 } 10093 return true; 10094 } 10095 10096 @Override 10097 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10098 return new PackageParser.ProviderIntentInfo[size]; 10099 } 10100 10101 @Override 10102 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10103 if (!sUserManager.exists(userId)) 10104 return true; 10105 PackageParser.Package p = filter.provider.owner; 10106 if (p != null) { 10107 PackageSetting ps = (PackageSetting) p.mExtras; 10108 if (ps != null) { 10109 // System apps are never considered stopped for purposes of 10110 // filtering, because there may be no way for the user to 10111 // actually re-launch them. 10112 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10113 && ps.getStopped(userId); 10114 } 10115 } 10116 return false; 10117 } 10118 10119 @Override 10120 protected boolean isPackageForFilter(String packageName, 10121 PackageParser.ProviderIntentInfo info) { 10122 return packageName.equals(info.provider.owner.packageName); 10123 } 10124 10125 @Override 10126 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10127 int match, int userId) { 10128 if (!sUserManager.exists(userId)) 10129 return null; 10130 final PackageParser.ProviderIntentInfo info = filter; 10131 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10132 return null; 10133 } 10134 final PackageParser.Provider provider = info.provider; 10135 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10136 if (ps == null) { 10137 return null; 10138 } 10139 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10140 ps.readUserState(userId), userId); 10141 if (pi == null) { 10142 return null; 10143 } 10144 final ResolveInfo res = new ResolveInfo(); 10145 res.providerInfo = pi; 10146 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10147 res.filter = filter; 10148 } 10149 res.priority = info.getPriority(); 10150 res.preferredOrder = provider.owner.mPreferredOrder; 10151 res.match = match; 10152 res.isDefault = info.hasDefault; 10153 res.labelRes = info.labelRes; 10154 res.nonLocalizedLabel = info.nonLocalizedLabel; 10155 res.icon = info.icon; 10156 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10157 return res; 10158 } 10159 10160 @Override 10161 protected void sortResults(List<ResolveInfo> results) { 10162 Collections.sort(results, mResolvePrioritySorter); 10163 } 10164 10165 @Override 10166 protected void dumpFilter(PrintWriter out, String prefix, 10167 PackageParser.ProviderIntentInfo filter) { 10168 out.print(prefix); 10169 out.print( 10170 Integer.toHexString(System.identityHashCode(filter.provider))); 10171 out.print(' '); 10172 filter.provider.printComponentShortName(out); 10173 out.print(" filter "); 10174 out.println(Integer.toHexString(System.identityHashCode(filter))); 10175 } 10176 10177 @Override 10178 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10179 return filter.provider; 10180 } 10181 10182 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10183 PackageParser.Provider provider = (PackageParser.Provider)label; 10184 out.print(prefix); out.print( 10185 Integer.toHexString(System.identityHashCode(provider))); 10186 out.print(' '); 10187 provider.printComponentShortName(out); 10188 if (count > 1) { 10189 out.print(" ("); out.print(count); out.print(" filters)"); 10190 } 10191 out.println(); 10192 } 10193 10194 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10195 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10196 private int mFlags; 10197 } 10198 10199 private static final class EphemeralIntentResolver 10200 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10201 @Override 10202 protected EphemeralResolveIntentInfo[] newArray(int size) { 10203 return new EphemeralResolveIntentInfo[size]; 10204 } 10205 10206 @Override 10207 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10208 return true; 10209 } 10210 10211 @Override 10212 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10213 int userId) { 10214 if (!sUserManager.exists(userId)) { 10215 return null; 10216 } 10217 return info.getEphemeralResolveInfo(); 10218 } 10219 } 10220 10221 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10222 new Comparator<ResolveInfo>() { 10223 public int compare(ResolveInfo r1, ResolveInfo r2) { 10224 int v1 = r1.priority; 10225 int v2 = r2.priority; 10226 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10227 if (v1 != v2) { 10228 return (v1 > v2) ? -1 : 1; 10229 } 10230 v1 = r1.preferredOrder; 10231 v2 = r2.preferredOrder; 10232 if (v1 != v2) { 10233 return (v1 > v2) ? -1 : 1; 10234 } 10235 if (r1.isDefault != r2.isDefault) { 10236 return r1.isDefault ? -1 : 1; 10237 } 10238 v1 = r1.match; 10239 v2 = r2.match; 10240 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10241 if (v1 != v2) { 10242 return (v1 > v2) ? -1 : 1; 10243 } 10244 if (r1.system != r2.system) { 10245 return r1.system ? -1 : 1; 10246 } 10247 if (r1.activityInfo != null) { 10248 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10249 } 10250 if (r1.serviceInfo != null) { 10251 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10252 } 10253 if (r1.providerInfo != null) { 10254 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10255 } 10256 return 0; 10257 } 10258 }; 10259 10260 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10261 new Comparator<ProviderInfo>() { 10262 public int compare(ProviderInfo p1, ProviderInfo p2) { 10263 final int v1 = p1.initOrder; 10264 final int v2 = p2.initOrder; 10265 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10266 } 10267 }; 10268 10269 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10270 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10271 final int[] userIds) { 10272 mHandler.post(new Runnable() { 10273 @Override 10274 public void run() { 10275 try { 10276 final IActivityManager am = ActivityManagerNative.getDefault(); 10277 if (am == null) return; 10278 final int[] resolvedUserIds; 10279 if (userIds == null) { 10280 resolvedUserIds = am.getRunningUserIds(); 10281 } else { 10282 resolvedUserIds = userIds; 10283 } 10284 for (int id : resolvedUserIds) { 10285 final Intent intent = new Intent(action, 10286 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10287 if (extras != null) { 10288 intent.putExtras(extras); 10289 } 10290 if (targetPkg != null) { 10291 intent.setPackage(targetPkg); 10292 } 10293 // Modify the UID when posting to other users 10294 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10295 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10296 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10297 intent.putExtra(Intent.EXTRA_UID, uid); 10298 } 10299 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10300 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10301 if (DEBUG_BROADCASTS) { 10302 RuntimeException here = new RuntimeException("here"); 10303 here.fillInStackTrace(); 10304 Slog.d(TAG, "Sending to user " + id + ": " 10305 + intent.toShortString(false, true, false, false) 10306 + " " + intent.getExtras(), here); 10307 } 10308 am.broadcastIntent(null, intent, null, finishedReceiver, 10309 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10310 null, finishedReceiver != null, false, id); 10311 } 10312 } catch (RemoteException ex) { 10313 } 10314 } 10315 }); 10316 } 10317 10318 /** 10319 * Check if the external storage media is available. This is true if there 10320 * is a mounted external storage medium or if the external storage is 10321 * emulated. 10322 */ 10323 private boolean isExternalMediaAvailable() { 10324 return mMediaMounted || Environment.isExternalStorageEmulated(); 10325 } 10326 10327 @Override 10328 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10329 // writer 10330 synchronized (mPackages) { 10331 if (!isExternalMediaAvailable()) { 10332 // If the external storage is no longer mounted at this point, 10333 // the caller may not have been able to delete all of this 10334 // packages files and can not delete any more. Bail. 10335 return null; 10336 } 10337 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10338 if (lastPackage != null) { 10339 pkgs.remove(lastPackage); 10340 } 10341 if (pkgs.size() > 0) { 10342 return pkgs.get(0); 10343 } 10344 } 10345 return null; 10346 } 10347 10348 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10349 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10350 userId, andCode ? 1 : 0, packageName); 10351 if (mSystemReady) { 10352 msg.sendToTarget(); 10353 } else { 10354 if (mPostSystemReadyMessages == null) { 10355 mPostSystemReadyMessages = new ArrayList<>(); 10356 } 10357 mPostSystemReadyMessages.add(msg); 10358 } 10359 } 10360 10361 void startCleaningPackages() { 10362 // reader 10363 synchronized (mPackages) { 10364 if (!isExternalMediaAvailable()) { 10365 return; 10366 } 10367 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10368 return; 10369 } 10370 } 10371 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10372 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10373 IActivityManager am = ActivityManagerNative.getDefault(); 10374 if (am != null) { 10375 try { 10376 am.startService(null, intent, null, mContext.getOpPackageName(), 10377 UserHandle.USER_SYSTEM); 10378 } catch (RemoteException e) { 10379 } 10380 } 10381 } 10382 10383 @Override 10384 public void installPackage(String originPath, IPackageInstallObserver2 observer, 10385 int installFlags, String installerPackageName, VerificationParams verificationParams, 10386 String packageAbiOverride) { 10387 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 10388 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 10389 } 10390 10391 @Override 10392 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10393 int installFlags, String installerPackageName, VerificationParams verificationParams, 10394 String packageAbiOverride, int userId) { 10395 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10396 10397 final int callingUid = Binder.getCallingUid(); 10398 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 10399 10400 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10401 try { 10402 if (observer != null) { 10403 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10404 } 10405 } catch (RemoteException re) { 10406 } 10407 return; 10408 } 10409 10410 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10411 installFlags |= PackageManager.INSTALL_FROM_ADB; 10412 10413 } else { 10414 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10415 // about installerPackageName. 10416 10417 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10418 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10419 } 10420 10421 UserHandle user; 10422 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10423 user = UserHandle.ALL; 10424 } else { 10425 user = new UserHandle(userId); 10426 } 10427 10428 // Only system components can circumvent runtime permissions when installing. 10429 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10430 && mContext.checkCallingOrSelfPermission(Manifest.permission 10431 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10432 throw new SecurityException("You need the " 10433 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10434 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10435 } 10436 10437 verificationParams.setInstallerUid(callingUid); 10438 10439 final File originFile = new File(originPath); 10440 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10441 10442 final Message msg = mHandler.obtainMessage(INIT_COPY); 10443 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 10444 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 10445 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10446 msg.obj = params; 10447 10448 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10449 System.identityHashCode(msg.obj)); 10450 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10451 System.identityHashCode(msg.obj)); 10452 10453 mHandler.sendMessage(msg); 10454 } 10455 10456 void installStage(String packageName, File stagedDir, String stagedCid, 10457 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10458 String installerPackageName, int installerUid, UserHandle user) { 10459 if (DEBUG_EPHEMERAL) { 10460 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10461 Slog.d(TAG, "Ephemeral install of " + packageName); 10462 } 10463 } 10464 final VerificationParams verifParams = new VerificationParams( 10465 null, sessionParams.originatingUri, sessionParams.referrerUri, 10466 sessionParams.originatingUid); 10467 verifParams.setInstallerUid(installerUid); 10468 10469 final OriginInfo origin; 10470 if (stagedDir != null) { 10471 origin = OriginInfo.fromStagedFile(stagedDir); 10472 } else { 10473 origin = OriginInfo.fromStagedContainer(stagedCid); 10474 } 10475 10476 final Message msg = mHandler.obtainMessage(INIT_COPY); 10477 final InstallParams params = new InstallParams(origin, null, observer, 10478 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10479 verifParams, user, sessionParams.abiOverride, 10480 sessionParams.grantedRuntimePermissions); 10481 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10482 msg.obj = params; 10483 10484 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10485 System.identityHashCode(msg.obj)); 10486 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10487 System.identityHashCode(msg.obj)); 10488 10489 mHandler.sendMessage(msg); 10490 } 10491 10492 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 10493 int userId) { 10494 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10495 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 10496 } 10497 10498 private void sendPackageAddedForUser(String packageName, boolean isSystem, 10499 int appId, int userId) { 10500 Bundle extras = new Bundle(1); 10501 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 10502 10503 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10504 packageName, extras, 0, null, null, new int[] {userId}); 10505 try { 10506 IActivityManager am = ActivityManagerNative.getDefault(); 10507 if (isSystem && am.isUserRunning(userId, 0)) { 10508 // The just-installed/enabled app is bundled on the system, so presumed 10509 // to be able to run automatically without needing an explicit launch. 10510 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10511 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10512 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10513 .setPackage(packageName); 10514 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10515 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10516 } 10517 } catch (RemoteException e) { 10518 // shouldn't happen 10519 Slog.w(TAG, "Unable to bootstrap installed package", e); 10520 } 10521 } 10522 10523 @Override 10524 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10525 int userId) { 10526 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10527 PackageSetting pkgSetting; 10528 final int uid = Binder.getCallingUid(); 10529 enforceCrossUserPermission(uid, userId, true, true, 10530 "setApplicationHiddenSetting for user " + userId); 10531 10532 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10533 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10534 return false; 10535 } 10536 10537 long callingId = Binder.clearCallingIdentity(); 10538 try { 10539 boolean sendAdded = false; 10540 boolean sendRemoved = false; 10541 // writer 10542 synchronized (mPackages) { 10543 pkgSetting = mSettings.mPackages.get(packageName); 10544 if (pkgSetting == null) { 10545 return false; 10546 } 10547 if (pkgSetting.getHidden(userId) != hidden) { 10548 pkgSetting.setHidden(hidden, userId); 10549 mSettings.writePackageRestrictionsLPr(userId); 10550 if (hidden) { 10551 sendRemoved = true; 10552 } else { 10553 sendAdded = true; 10554 } 10555 } 10556 } 10557 if (sendAdded) { 10558 sendPackageAddedForUser(packageName, pkgSetting, userId); 10559 return true; 10560 } 10561 if (sendRemoved) { 10562 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10563 "hiding pkg"); 10564 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10565 return true; 10566 } 10567 } finally { 10568 Binder.restoreCallingIdentity(callingId); 10569 } 10570 return false; 10571 } 10572 10573 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10574 int userId) { 10575 final PackageRemovedInfo info = new PackageRemovedInfo(); 10576 info.removedPackage = packageName; 10577 info.removedUsers = new int[] {userId}; 10578 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10579 info.sendPackageRemovedBroadcasts(); 10580 } 10581 10582 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10583 if (pkgList.length > 0) { 10584 Bundle extras = new Bundle(1); 10585 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10586 10587 sendPackageBroadcast( 10588 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10589 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10590 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10591 new int[] {userId}); 10592 } 10593 } 10594 10595 /** 10596 * Returns true if application is not found or there was an error. Otherwise it returns 10597 * the hidden state of the package for the given user. 10598 */ 10599 @Override 10600 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10601 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10602 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10603 false, "getApplicationHidden for user " + userId); 10604 PackageSetting pkgSetting; 10605 long callingId = Binder.clearCallingIdentity(); 10606 try { 10607 // writer 10608 synchronized (mPackages) { 10609 pkgSetting = mSettings.mPackages.get(packageName); 10610 if (pkgSetting == null) { 10611 return true; 10612 } 10613 return pkgSetting.getHidden(userId); 10614 } 10615 } finally { 10616 Binder.restoreCallingIdentity(callingId); 10617 } 10618 } 10619 10620 /** 10621 * @hide 10622 */ 10623 @Override 10624 public int installExistingPackageAsUser(String packageName, int userId) { 10625 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10626 null); 10627 PackageSetting pkgSetting; 10628 final int uid = Binder.getCallingUid(); 10629 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10630 + userId); 10631 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10632 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10633 } 10634 10635 long callingId = Binder.clearCallingIdentity(); 10636 try { 10637 boolean installed = false; 10638 10639 // writer 10640 synchronized (mPackages) { 10641 pkgSetting = mSettings.mPackages.get(packageName); 10642 if (pkgSetting == null) { 10643 return PackageManager.INSTALL_FAILED_INVALID_URI; 10644 } 10645 if (!pkgSetting.getInstalled(userId)) { 10646 pkgSetting.setInstalled(true, userId); 10647 pkgSetting.setHidden(false, userId); 10648 mSettings.writePackageRestrictionsLPr(userId); 10649 if (pkgSetting.pkg != null) { 10650 prepareAppDataAfterInstall(pkgSetting.pkg); 10651 } 10652 installed = true; 10653 } 10654 } 10655 10656 if (installed) { 10657 sendPackageAddedForUser(packageName, pkgSetting, userId); 10658 } 10659 } finally { 10660 Binder.restoreCallingIdentity(callingId); 10661 } 10662 10663 return PackageManager.INSTALL_SUCCEEDED; 10664 } 10665 10666 boolean isUserRestricted(int userId, String restrictionKey) { 10667 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10668 if (restrictions.getBoolean(restrictionKey, false)) { 10669 Log.w(TAG, "User is restricted: " + restrictionKey); 10670 return true; 10671 } 10672 return false; 10673 } 10674 10675 @Override 10676 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 10677 int userId) { 10678 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10679 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true, 10680 "setPackagesSuspended for user " + userId); 10681 10682 if (ArrayUtils.isEmpty(packageNames)) { 10683 return packageNames; 10684 } 10685 10686 // List of package names for whom the suspended state has changed. 10687 List<String> changedPackages = new ArrayList<>(packageNames.length); 10688 // List of package names for whom the suspended state is not set as requested in this 10689 // method. 10690 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 10691 for (int i = 0; i < packageNames.length; i++) { 10692 String packageName = packageNames[i]; 10693 long callingId = Binder.clearCallingIdentity(); 10694 try { 10695 boolean changed = false; 10696 final int appId; 10697 synchronized (mPackages) { 10698 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10699 if (pkgSetting == null) { 10700 Slog.w(TAG, "Could not find package setting for package \"" + packageName 10701 + "\". Skipping suspending/un-suspending."); 10702 unactionedPackages.add(packageName); 10703 continue; 10704 } 10705 appId = pkgSetting.appId; 10706 if (pkgSetting.getSuspended(userId) != suspended) { 10707 if (!canSuspendPackageForUser(packageName, userId)) { 10708 unactionedPackages.add(packageName); 10709 continue; 10710 } 10711 pkgSetting.setSuspended(suspended, userId); 10712 mSettings.writePackageRestrictionsLPr(userId); 10713 changed = true; 10714 changedPackages.add(packageName); 10715 } 10716 } 10717 10718 if (changed && suspended) { 10719 killApplication(packageName, UserHandle.getUid(userId, appId), 10720 "suspending package"); 10721 } 10722 } finally { 10723 Binder.restoreCallingIdentity(callingId); 10724 } 10725 } 10726 10727 if (!changedPackages.isEmpty()) { 10728 sendPackagesSuspendedForUser(changedPackages.toArray( 10729 new String[changedPackages.size()]), userId, suspended); 10730 } 10731 10732 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 10733 } 10734 10735 @Override 10736 public boolean isPackageSuspendedForUser(String packageName, int userId) { 10737 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10738 false, "isPackageSuspendedForUser for user " + userId); 10739 synchronized (mPackages) { 10740 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10741 return pkgSetting != null && pkgSetting.getSuspended(userId); 10742 } 10743 } 10744 10745 // TODO: investigate and add more restrictions for suspending crucial packages. 10746 private boolean canSuspendPackageForUser(String packageName, int userId) { 10747 if (isPackageDeviceAdmin(packageName, userId)) { 10748 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10749 + "\": has active device admin"); 10750 return false; 10751 } 10752 10753 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 10754 if (packageName.equals(activeLauncherPackageName)) { 10755 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10756 + "\" because it is set as the active launcher"); 10757 return false; 10758 } 10759 10760 return true; 10761 } 10762 10763 private String getActiveLauncherPackageName(int userId) { 10764 Intent intent = new Intent(Intent.ACTION_MAIN); 10765 intent.addCategory(Intent.CATEGORY_HOME); 10766 ResolveInfo resolveInfo = resolveIntent( 10767 intent, 10768 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 10769 PackageManager.MATCH_DEFAULT_ONLY, 10770 userId); 10771 10772 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 10773 } 10774 10775 @Override 10776 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10777 mContext.enforceCallingOrSelfPermission( 10778 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10779 "Only package verification agents can verify applications"); 10780 10781 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10782 final PackageVerificationResponse response = new PackageVerificationResponse( 10783 verificationCode, Binder.getCallingUid()); 10784 msg.arg1 = id; 10785 msg.obj = response; 10786 mHandler.sendMessage(msg); 10787 } 10788 10789 @Override 10790 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10791 long millisecondsToDelay) { 10792 mContext.enforceCallingOrSelfPermission( 10793 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10794 "Only package verification agents can extend verification timeouts"); 10795 10796 final PackageVerificationState state = mPendingVerification.get(id); 10797 final PackageVerificationResponse response = new PackageVerificationResponse( 10798 verificationCodeAtTimeout, Binder.getCallingUid()); 10799 10800 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10801 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10802 } 10803 if (millisecondsToDelay < 0) { 10804 millisecondsToDelay = 0; 10805 } 10806 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10807 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10808 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10809 } 10810 10811 if ((state != null) && !state.timeoutExtended()) { 10812 state.extendTimeout(); 10813 10814 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10815 msg.arg1 = id; 10816 msg.obj = response; 10817 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10818 } 10819 } 10820 10821 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10822 int verificationCode, UserHandle user) { 10823 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10824 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10825 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10826 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10827 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10828 10829 mContext.sendBroadcastAsUser(intent, user, 10830 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10831 } 10832 10833 private ComponentName matchComponentForVerifier(String packageName, 10834 List<ResolveInfo> receivers) { 10835 ActivityInfo targetReceiver = null; 10836 10837 final int NR = receivers.size(); 10838 for (int i = 0; i < NR; i++) { 10839 final ResolveInfo info = receivers.get(i); 10840 if (info.activityInfo == null) { 10841 continue; 10842 } 10843 10844 if (packageName.equals(info.activityInfo.packageName)) { 10845 targetReceiver = info.activityInfo; 10846 break; 10847 } 10848 } 10849 10850 if (targetReceiver == null) { 10851 return null; 10852 } 10853 10854 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10855 } 10856 10857 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10858 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10859 if (pkgInfo.verifiers.length == 0) { 10860 return null; 10861 } 10862 10863 final int N = pkgInfo.verifiers.length; 10864 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10865 for (int i = 0; i < N; i++) { 10866 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10867 10868 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10869 receivers); 10870 if (comp == null) { 10871 continue; 10872 } 10873 10874 final int verifierUid = getUidForVerifier(verifierInfo); 10875 if (verifierUid == -1) { 10876 continue; 10877 } 10878 10879 if (DEBUG_VERIFY) { 10880 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10881 + " with the correct signature"); 10882 } 10883 sufficientVerifiers.add(comp); 10884 verificationState.addSufficientVerifier(verifierUid); 10885 } 10886 10887 return sufficientVerifiers; 10888 } 10889 10890 private int getUidForVerifier(VerifierInfo verifierInfo) { 10891 synchronized (mPackages) { 10892 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10893 if (pkg == null) { 10894 return -1; 10895 } else if (pkg.mSignatures.length != 1) { 10896 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10897 + " has more than one signature; ignoring"); 10898 return -1; 10899 } 10900 10901 /* 10902 * If the public key of the package's signature does not match 10903 * our expected public key, then this is a different package and 10904 * we should skip. 10905 */ 10906 10907 final byte[] expectedPublicKey; 10908 try { 10909 final Signature verifierSig = pkg.mSignatures[0]; 10910 final PublicKey publicKey = verifierSig.getPublicKey(); 10911 expectedPublicKey = publicKey.getEncoded(); 10912 } catch (CertificateException e) { 10913 return -1; 10914 } 10915 10916 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10917 10918 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10919 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10920 + " does not have the expected public key; ignoring"); 10921 return -1; 10922 } 10923 10924 return pkg.applicationInfo.uid; 10925 } 10926 } 10927 10928 @Override 10929 public void finishPackageInstall(int token) { 10930 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10931 10932 if (DEBUG_INSTALL) { 10933 Slog.v(TAG, "BM finishing package install for " + token); 10934 } 10935 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10936 10937 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10938 mHandler.sendMessage(msg); 10939 } 10940 10941 /** 10942 * Get the verification agent timeout. 10943 * 10944 * @return verification timeout in milliseconds 10945 */ 10946 private long getVerificationTimeout() { 10947 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10948 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10949 DEFAULT_VERIFICATION_TIMEOUT); 10950 } 10951 10952 /** 10953 * Get the default verification agent response code. 10954 * 10955 * @return default verification response code 10956 */ 10957 private int getDefaultVerificationResponse() { 10958 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10959 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10960 DEFAULT_VERIFICATION_RESPONSE); 10961 } 10962 10963 /** 10964 * Check whether or not package verification has been enabled. 10965 * 10966 * @return true if verification should be performed 10967 */ 10968 private boolean isVerificationEnabled(int userId, int installFlags) { 10969 if (!DEFAULT_VERIFY_ENABLE) { 10970 return false; 10971 } 10972 // Ephemeral apps don't get the full verification treatment 10973 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10974 if (DEBUG_EPHEMERAL) { 10975 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10976 } 10977 return false; 10978 } 10979 10980 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10981 10982 // Check if installing from ADB 10983 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10984 // Do not run verification in a test harness environment 10985 if (ActivityManager.isRunningInTestHarness()) { 10986 return false; 10987 } 10988 if (ensureVerifyAppsEnabled) { 10989 return true; 10990 } 10991 // Check if the developer does not want package verification for ADB installs 10992 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10993 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10994 return false; 10995 } 10996 } 10997 10998 if (ensureVerifyAppsEnabled) { 10999 return true; 11000 } 11001 11002 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11003 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11004 } 11005 11006 @Override 11007 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11008 throws RemoteException { 11009 mContext.enforceCallingOrSelfPermission( 11010 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11011 "Only intentfilter verification agents can verify applications"); 11012 11013 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11014 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11015 Binder.getCallingUid(), verificationCode, failedDomains); 11016 msg.arg1 = id; 11017 msg.obj = response; 11018 mHandler.sendMessage(msg); 11019 } 11020 11021 @Override 11022 public int getIntentVerificationStatus(String packageName, int userId) { 11023 synchronized (mPackages) { 11024 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11025 } 11026 } 11027 11028 @Override 11029 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11030 mContext.enforceCallingOrSelfPermission( 11031 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11032 11033 boolean result = false; 11034 synchronized (mPackages) { 11035 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11036 } 11037 if (result) { 11038 scheduleWritePackageRestrictionsLocked(userId); 11039 } 11040 return result; 11041 } 11042 11043 @Override 11044 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 11045 synchronized (mPackages) { 11046 return mSettings.getIntentFilterVerificationsLPr(packageName); 11047 } 11048 } 11049 11050 @Override 11051 public List<IntentFilter> getAllIntentFilters(String packageName) { 11052 if (TextUtils.isEmpty(packageName)) { 11053 return Collections.<IntentFilter>emptyList(); 11054 } 11055 synchronized (mPackages) { 11056 PackageParser.Package pkg = mPackages.get(packageName); 11057 if (pkg == null || pkg.activities == null) { 11058 return Collections.<IntentFilter>emptyList(); 11059 } 11060 final int count = pkg.activities.size(); 11061 ArrayList<IntentFilter> result = new ArrayList<>(); 11062 for (int n=0; n<count; n++) { 11063 PackageParser.Activity activity = pkg.activities.get(n); 11064 if (activity.intents != null && activity.intents.size() > 0) { 11065 result.addAll(activity.intents); 11066 } 11067 } 11068 return result; 11069 } 11070 } 11071 11072 @Override 11073 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11074 mContext.enforceCallingOrSelfPermission( 11075 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11076 11077 synchronized (mPackages) { 11078 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11079 if (packageName != null) { 11080 result |= updateIntentVerificationStatus(packageName, 11081 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11082 userId); 11083 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11084 packageName, userId); 11085 } 11086 return result; 11087 } 11088 } 11089 11090 @Override 11091 public String getDefaultBrowserPackageName(int userId) { 11092 synchronized (mPackages) { 11093 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11094 } 11095 } 11096 11097 /** 11098 * Get the "allow unknown sources" setting. 11099 * 11100 * @return the current "allow unknown sources" setting 11101 */ 11102 private int getUnknownSourcesSettings() { 11103 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11104 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 11105 -1); 11106 } 11107 11108 @Override 11109 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11110 final int uid = Binder.getCallingUid(); 11111 // writer 11112 synchronized (mPackages) { 11113 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11114 if (targetPackageSetting == null) { 11115 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11116 } 11117 11118 PackageSetting installerPackageSetting; 11119 if (installerPackageName != null) { 11120 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11121 if (installerPackageSetting == null) { 11122 throw new IllegalArgumentException("Unknown installer package: " 11123 + installerPackageName); 11124 } 11125 } else { 11126 installerPackageSetting = null; 11127 } 11128 11129 Signature[] callerSignature; 11130 Object obj = mSettings.getUserIdLPr(uid); 11131 if (obj != null) { 11132 if (obj instanceof SharedUserSetting) { 11133 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11134 } else if (obj instanceof PackageSetting) { 11135 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11136 } else { 11137 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11138 } 11139 } else { 11140 throw new SecurityException("Unknown calling UID: " + uid); 11141 } 11142 11143 // Verify: can't set installerPackageName to a package that is 11144 // not signed with the same cert as the caller. 11145 if (installerPackageSetting != null) { 11146 if (compareSignatures(callerSignature, 11147 installerPackageSetting.signatures.mSignatures) 11148 != PackageManager.SIGNATURE_MATCH) { 11149 throw new SecurityException( 11150 "Caller does not have same cert as new installer package " 11151 + installerPackageName); 11152 } 11153 } 11154 11155 // Verify: if target already has an installer package, it must 11156 // be signed with the same cert as the caller. 11157 if (targetPackageSetting.installerPackageName != null) { 11158 PackageSetting setting = mSettings.mPackages.get( 11159 targetPackageSetting.installerPackageName); 11160 // If the currently set package isn't valid, then it's always 11161 // okay to change it. 11162 if (setting != null) { 11163 if (compareSignatures(callerSignature, 11164 setting.signatures.mSignatures) 11165 != PackageManager.SIGNATURE_MATCH) { 11166 throw new SecurityException( 11167 "Caller does not have same cert as old installer package " 11168 + targetPackageSetting.installerPackageName); 11169 } 11170 } 11171 } 11172 11173 // Okay! 11174 targetPackageSetting.installerPackageName = installerPackageName; 11175 scheduleWriteSettingsLocked(); 11176 } 11177 } 11178 11179 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11180 // Queue up an async operation since the package installation may take a little while. 11181 mHandler.post(new Runnable() { 11182 public void run() { 11183 mHandler.removeCallbacks(this); 11184 // Result object to be returned 11185 PackageInstalledInfo res = new PackageInstalledInfo(); 11186 res.setReturnCode(currentStatus); 11187 res.uid = -1; 11188 res.pkg = null; 11189 res.removedInfo = null; 11190 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11191 args.doPreInstall(res.returnCode); 11192 synchronized (mInstallLock) { 11193 installPackageTracedLI(args, res); 11194 } 11195 args.doPostInstall(res.returnCode, res.uid); 11196 } 11197 11198 // A restore should be performed at this point if (a) the install 11199 // succeeded, (b) the operation is not an update, and (c) the new 11200 // package has not opted out of backup participation. 11201 final boolean update = res.removedInfo != null 11202 && res.removedInfo.removedPackage != null; 11203 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11204 boolean doRestore = !update 11205 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11206 11207 // Set up the post-install work request bookkeeping. This will be used 11208 // and cleaned up by the post-install event handling regardless of whether 11209 // there's a restore pass performed. Token values are >= 1. 11210 int token; 11211 if (mNextInstallToken < 0) mNextInstallToken = 1; 11212 token = mNextInstallToken++; 11213 11214 PostInstallData data = new PostInstallData(args, res); 11215 mRunningInstalls.put(token, data); 11216 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11217 11218 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11219 // Pass responsibility to the Backup Manager. It will perform a 11220 // restore if appropriate, then pass responsibility back to the 11221 // Package Manager to run the post-install observer callbacks 11222 // and broadcasts. 11223 IBackupManager bm = IBackupManager.Stub.asInterface( 11224 ServiceManager.getService(Context.BACKUP_SERVICE)); 11225 if (bm != null) { 11226 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11227 + " to BM for possible restore"); 11228 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11229 try { 11230 // TODO: http://b/22388012 11231 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11232 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11233 } else { 11234 doRestore = false; 11235 } 11236 } catch (RemoteException e) { 11237 // can't happen; the backup manager is local 11238 } catch (Exception e) { 11239 Slog.e(TAG, "Exception trying to enqueue restore", e); 11240 doRestore = false; 11241 } 11242 } else { 11243 Slog.e(TAG, "Backup Manager not found!"); 11244 doRestore = false; 11245 } 11246 } 11247 11248 if (!doRestore) { 11249 // No restore possible, or the Backup Manager was mysteriously not 11250 // available -- just fire the post-install work request directly. 11251 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11252 11253 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11254 11255 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11256 mHandler.sendMessage(msg); 11257 } 11258 } 11259 }); 11260 } 11261 11262 private abstract class HandlerParams { 11263 private static final int MAX_RETRIES = 4; 11264 11265 /** 11266 * Number of times startCopy() has been attempted and had a non-fatal 11267 * error. 11268 */ 11269 private int mRetries = 0; 11270 11271 /** User handle for the user requesting the information or installation. */ 11272 private final UserHandle mUser; 11273 String traceMethod; 11274 int traceCookie; 11275 11276 HandlerParams(UserHandle user) { 11277 mUser = user; 11278 } 11279 11280 UserHandle getUser() { 11281 return mUser; 11282 } 11283 11284 HandlerParams setTraceMethod(String traceMethod) { 11285 this.traceMethod = traceMethod; 11286 return this; 11287 } 11288 11289 HandlerParams setTraceCookie(int traceCookie) { 11290 this.traceCookie = traceCookie; 11291 return this; 11292 } 11293 11294 final boolean startCopy() { 11295 boolean res; 11296 try { 11297 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11298 11299 if (++mRetries > MAX_RETRIES) { 11300 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11301 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11302 handleServiceError(); 11303 return false; 11304 } else { 11305 handleStartCopy(); 11306 res = true; 11307 } 11308 } catch (RemoteException e) { 11309 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11310 mHandler.sendEmptyMessage(MCS_RECONNECT); 11311 res = false; 11312 } 11313 handleReturnCode(); 11314 return res; 11315 } 11316 11317 final void serviceError() { 11318 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11319 handleServiceError(); 11320 handleReturnCode(); 11321 } 11322 11323 abstract void handleStartCopy() throws RemoteException; 11324 abstract void handleServiceError(); 11325 abstract void handleReturnCode(); 11326 } 11327 11328 class MeasureParams extends HandlerParams { 11329 private final PackageStats mStats; 11330 private boolean mSuccess; 11331 11332 private final IPackageStatsObserver mObserver; 11333 11334 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11335 super(new UserHandle(stats.userHandle)); 11336 mObserver = observer; 11337 mStats = stats; 11338 } 11339 11340 @Override 11341 public String toString() { 11342 return "MeasureParams{" 11343 + Integer.toHexString(System.identityHashCode(this)) 11344 + " " + mStats.packageName + "}"; 11345 } 11346 11347 @Override 11348 void handleStartCopy() throws RemoteException { 11349 synchronized (mInstallLock) { 11350 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11351 } 11352 11353 if (mSuccess) { 11354 final boolean mounted; 11355 if (Environment.isExternalStorageEmulated()) { 11356 mounted = true; 11357 } else { 11358 final String status = Environment.getExternalStorageState(); 11359 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11360 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11361 } 11362 11363 if (mounted) { 11364 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11365 11366 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11367 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11368 11369 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11370 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11371 11372 // Always subtract cache size, since it's a subdirectory 11373 mStats.externalDataSize -= mStats.externalCacheSize; 11374 11375 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11376 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11377 11378 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11379 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11380 } 11381 } 11382 } 11383 11384 @Override 11385 void handleReturnCode() { 11386 if (mObserver != null) { 11387 try { 11388 mObserver.onGetStatsCompleted(mStats, mSuccess); 11389 } catch (RemoteException e) { 11390 Slog.i(TAG, "Observer no longer exists."); 11391 } 11392 } 11393 } 11394 11395 @Override 11396 void handleServiceError() { 11397 Slog.e(TAG, "Could not measure application " + mStats.packageName 11398 + " external storage"); 11399 } 11400 } 11401 11402 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11403 throws RemoteException { 11404 long result = 0; 11405 for (File path : paths) { 11406 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11407 } 11408 return result; 11409 } 11410 11411 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11412 for (File path : paths) { 11413 try { 11414 mcs.clearDirectory(path.getAbsolutePath()); 11415 } catch (RemoteException e) { 11416 } 11417 } 11418 } 11419 11420 static class OriginInfo { 11421 /** 11422 * Location where install is coming from, before it has been 11423 * copied/renamed into place. This could be a single monolithic APK 11424 * file, or a cluster directory. This location may be untrusted. 11425 */ 11426 final File file; 11427 final String cid; 11428 11429 /** 11430 * Flag indicating that {@link #file} or {@link #cid} has already been 11431 * staged, meaning downstream users don't need to defensively copy the 11432 * contents. 11433 */ 11434 final boolean staged; 11435 11436 /** 11437 * Flag indicating that {@link #file} or {@link #cid} is an already 11438 * installed app that is being moved. 11439 */ 11440 final boolean existing; 11441 11442 final String resolvedPath; 11443 final File resolvedFile; 11444 11445 static OriginInfo fromNothing() { 11446 return new OriginInfo(null, null, false, false); 11447 } 11448 11449 static OriginInfo fromUntrustedFile(File file) { 11450 return new OriginInfo(file, null, false, false); 11451 } 11452 11453 static OriginInfo fromExistingFile(File file) { 11454 return new OriginInfo(file, null, false, true); 11455 } 11456 11457 static OriginInfo fromStagedFile(File file) { 11458 return new OriginInfo(file, null, true, false); 11459 } 11460 11461 static OriginInfo fromStagedContainer(String cid) { 11462 return new OriginInfo(null, cid, true, false); 11463 } 11464 11465 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 11466 this.file = file; 11467 this.cid = cid; 11468 this.staged = staged; 11469 this.existing = existing; 11470 11471 if (cid != null) { 11472 resolvedPath = PackageHelper.getSdDir(cid); 11473 resolvedFile = new File(resolvedPath); 11474 } else if (file != null) { 11475 resolvedPath = file.getAbsolutePath(); 11476 resolvedFile = file; 11477 } else { 11478 resolvedPath = null; 11479 resolvedFile = null; 11480 } 11481 } 11482 } 11483 11484 static class MoveInfo { 11485 final int moveId; 11486 final String fromUuid; 11487 final String toUuid; 11488 final String packageName; 11489 final String dataAppName; 11490 final int appId; 11491 final String seinfo; 11492 final int targetSdkVersion; 11493 11494 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 11495 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 11496 this.moveId = moveId; 11497 this.fromUuid = fromUuid; 11498 this.toUuid = toUuid; 11499 this.packageName = packageName; 11500 this.dataAppName = dataAppName; 11501 this.appId = appId; 11502 this.seinfo = seinfo; 11503 this.targetSdkVersion = targetSdkVersion; 11504 } 11505 } 11506 11507 class InstallParams extends HandlerParams { 11508 final OriginInfo origin; 11509 final MoveInfo move; 11510 final IPackageInstallObserver2 observer; 11511 int installFlags; 11512 final String installerPackageName; 11513 final String volumeUuid; 11514 final VerificationParams verificationParams; 11515 private InstallArgs mArgs; 11516 private int mRet; 11517 final String packageAbiOverride; 11518 final String[] grantedRuntimePermissions; 11519 11520 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11521 int installFlags, String installerPackageName, String volumeUuid, 11522 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 11523 String[] grantedPermissions) { 11524 super(user); 11525 this.origin = origin; 11526 this.move = move; 11527 this.observer = observer; 11528 this.installFlags = installFlags; 11529 this.installerPackageName = installerPackageName; 11530 this.volumeUuid = volumeUuid; 11531 this.verificationParams = verificationParams; 11532 this.packageAbiOverride = packageAbiOverride; 11533 this.grantedRuntimePermissions = grantedPermissions; 11534 } 11535 11536 @Override 11537 public String toString() { 11538 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11539 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11540 } 11541 11542 private int installLocationPolicy(PackageInfoLite pkgLite) { 11543 String packageName = pkgLite.packageName; 11544 int installLocation = pkgLite.installLocation; 11545 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11546 // reader 11547 synchronized (mPackages) { 11548 PackageParser.Package pkg = mPackages.get(packageName); 11549 if (pkg != null) { 11550 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11551 // Check for downgrading. 11552 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 11553 try { 11554 checkDowngrade(pkg, pkgLite); 11555 } catch (PackageManagerException e) { 11556 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11557 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11558 } 11559 } 11560 // Check for updated system application. 11561 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11562 if (onSd) { 11563 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11564 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11565 } 11566 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11567 } else { 11568 if (onSd) { 11569 // Install flag overrides everything. 11570 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11571 } 11572 // If current upgrade specifies particular preference 11573 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11574 // Application explicitly specified internal. 11575 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11576 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11577 // App explictly prefers external. Let policy decide 11578 } else { 11579 // Prefer previous location 11580 if (isExternal(pkg)) { 11581 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11582 } 11583 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11584 } 11585 } 11586 } else { 11587 // Invalid install. Return error code 11588 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11589 } 11590 } 11591 } 11592 // All the special cases have been taken care of. 11593 // Return result based on recommended install location. 11594 if (onSd) { 11595 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11596 } 11597 return pkgLite.recommendedInstallLocation; 11598 } 11599 11600 /* 11601 * Invoke remote method to get package information and install 11602 * location values. Override install location based on default 11603 * policy if needed and then create install arguments based 11604 * on the install location. 11605 */ 11606 public void handleStartCopy() throws RemoteException { 11607 int ret = PackageManager.INSTALL_SUCCEEDED; 11608 11609 // If we're already staged, we've firmly committed to an install location 11610 if (origin.staged) { 11611 if (origin.file != null) { 11612 installFlags |= PackageManager.INSTALL_INTERNAL; 11613 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11614 } else if (origin.cid != null) { 11615 installFlags |= PackageManager.INSTALL_EXTERNAL; 11616 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11617 } else { 11618 throw new IllegalStateException("Invalid stage location"); 11619 } 11620 } 11621 11622 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11623 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11624 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11625 PackageInfoLite pkgLite = null; 11626 11627 if (onInt && onSd) { 11628 // Check if both bits are set. 11629 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11630 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11631 } else if (onSd && ephemeral) { 11632 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11633 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11634 } else { 11635 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11636 packageAbiOverride); 11637 11638 if (DEBUG_EPHEMERAL && ephemeral) { 11639 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11640 } 11641 11642 /* 11643 * If we have too little free space, try to free cache 11644 * before giving up. 11645 */ 11646 if (!origin.staged && pkgLite.recommendedInstallLocation 11647 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11648 // TODO: focus freeing disk space on the target device 11649 final StorageManager storage = StorageManager.from(mContext); 11650 final long lowThreshold = storage.getStorageLowBytes( 11651 Environment.getDataDirectory()); 11652 11653 final long sizeBytes = mContainerService.calculateInstalledSize( 11654 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11655 11656 try { 11657 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11658 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11659 installFlags, packageAbiOverride); 11660 } catch (InstallerException e) { 11661 Slog.w(TAG, "Failed to free cache", e); 11662 } 11663 11664 /* 11665 * The cache free must have deleted the file we 11666 * downloaded to install. 11667 * 11668 * TODO: fix the "freeCache" call to not delete 11669 * the file we care about. 11670 */ 11671 if (pkgLite.recommendedInstallLocation 11672 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11673 pkgLite.recommendedInstallLocation 11674 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11675 } 11676 } 11677 } 11678 11679 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11680 int loc = pkgLite.recommendedInstallLocation; 11681 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11682 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11683 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11684 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11685 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11686 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11687 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11688 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11689 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11690 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11691 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11692 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11693 } else { 11694 // Override with defaults if needed. 11695 loc = installLocationPolicy(pkgLite); 11696 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11697 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11698 } else if (!onSd && !onInt) { 11699 // Override install location with flags 11700 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11701 // Set the flag to install on external media. 11702 installFlags |= PackageManager.INSTALL_EXTERNAL; 11703 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11704 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11705 if (DEBUG_EPHEMERAL) { 11706 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11707 } 11708 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11709 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11710 |PackageManager.INSTALL_INTERNAL); 11711 } else { 11712 // Make sure the flag for installing on external 11713 // media is unset 11714 installFlags |= PackageManager.INSTALL_INTERNAL; 11715 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11716 } 11717 } 11718 } 11719 } 11720 11721 final InstallArgs args = createInstallArgs(this); 11722 mArgs = args; 11723 11724 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11725 // TODO: http://b/22976637 11726 // Apps installed for "all" users use the device owner to verify the app 11727 UserHandle verifierUser = getUser(); 11728 if (verifierUser == UserHandle.ALL) { 11729 verifierUser = UserHandle.SYSTEM; 11730 } 11731 11732 /* 11733 * Determine if we have any installed package verifiers. If we 11734 * do, then we'll defer to them to verify the packages. 11735 */ 11736 final int requiredUid = mRequiredVerifierPackage == null ? -1 11737 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11738 verifierUser.getIdentifier()); 11739 if (!origin.existing && requiredUid != -1 11740 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11741 final Intent verification = new Intent( 11742 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11743 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11744 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11745 PACKAGE_MIME_TYPE); 11746 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11747 11748 // Query all live verifiers based on current user state 11749 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11750 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11751 11752 if (DEBUG_VERIFY) { 11753 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11754 + verification.toString() + " with " + pkgLite.verifiers.length 11755 + " optional verifiers"); 11756 } 11757 11758 final int verificationId = mPendingVerificationToken++; 11759 11760 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11761 11762 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11763 installerPackageName); 11764 11765 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11766 installFlags); 11767 11768 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11769 pkgLite.packageName); 11770 11771 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11772 pkgLite.versionCode); 11773 11774 if (verificationParams != null) { 11775 if (verificationParams.getVerificationURI() != null) { 11776 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11777 verificationParams.getVerificationURI()); 11778 } 11779 if (verificationParams.getOriginatingURI() != null) { 11780 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11781 verificationParams.getOriginatingURI()); 11782 } 11783 if (verificationParams.getReferrer() != null) { 11784 verification.putExtra(Intent.EXTRA_REFERRER, 11785 verificationParams.getReferrer()); 11786 } 11787 if (verificationParams.getOriginatingUid() >= 0) { 11788 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11789 verificationParams.getOriginatingUid()); 11790 } 11791 if (verificationParams.getInstallerUid() >= 0) { 11792 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11793 verificationParams.getInstallerUid()); 11794 } 11795 } 11796 11797 final PackageVerificationState verificationState = new PackageVerificationState( 11798 requiredUid, args); 11799 11800 mPendingVerification.append(verificationId, verificationState); 11801 11802 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11803 receivers, verificationState); 11804 11805 /* 11806 * If any sufficient verifiers were listed in the package 11807 * manifest, attempt to ask them. 11808 */ 11809 if (sufficientVerifiers != null) { 11810 final int N = sufficientVerifiers.size(); 11811 if (N == 0) { 11812 Slog.i(TAG, "Additional verifiers required, but none installed."); 11813 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11814 } else { 11815 for (int i = 0; i < N; i++) { 11816 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11817 11818 final Intent sufficientIntent = new Intent(verification); 11819 sufficientIntent.setComponent(verifierComponent); 11820 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11821 } 11822 } 11823 } 11824 11825 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11826 mRequiredVerifierPackage, receivers); 11827 if (ret == PackageManager.INSTALL_SUCCEEDED 11828 && mRequiredVerifierPackage != null) { 11829 Trace.asyncTraceBegin( 11830 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11831 /* 11832 * Send the intent to the required verification agent, 11833 * but only start the verification timeout after the 11834 * target BroadcastReceivers have run. 11835 */ 11836 verification.setComponent(requiredVerifierComponent); 11837 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11838 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11839 new BroadcastReceiver() { 11840 @Override 11841 public void onReceive(Context context, Intent intent) { 11842 final Message msg = mHandler 11843 .obtainMessage(CHECK_PENDING_VERIFICATION); 11844 msg.arg1 = verificationId; 11845 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11846 } 11847 }, null, 0, null, null); 11848 11849 /* 11850 * We don't want the copy to proceed until verification 11851 * succeeds, so null out this field. 11852 */ 11853 mArgs = null; 11854 } 11855 } else { 11856 /* 11857 * No package verification is enabled, so immediately start 11858 * the remote call to initiate copy using temporary file. 11859 */ 11860 ret = args.copyApk(mContainerService, true); 11861 } 11862 } 11863 11864 mRet = ret; 11865 } 11866 11867 @Override 11868 void handleReturnCode() { 11869 // If mArgs is null, then MCS couldn't be reached. When it 11870 // reconnects, it will try again to install. At that point, this 11871 // will succeed. 11872 if (mArgs != null) { 11873 processPendingInstall(mArgs, mRet); 11874 } 11875 } 11876 11877 @Override 11878 void handleServiceError() { 11879 mArgs = createInstallArgs(this); 11880 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11881 } 11882 11883 public boolean isForwardLocked() { 11884 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11885 } 11886 } 11887 11888 /** 11889 * Used during creation of InstallArgs 11890 * 11891 * @param installFlags package installation flags 11892 * @return true if should be installed on external storage 11893 */ 11894 private static boolean installOnExternalAsec(int installFlags) { 11895 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11896 return false; 11897 } 11898 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11899 return true; 11900 } 11901 return false; 11902 } 11903 11904 /** 11905 * Used during creation of InstallArgs 11906 * 11907 * @param installFlags package installation flags 11908 * @return true if should be installed as forward locked 11909 */ 11910 private static boolean installForwardLocked(int installFlags) { 11911 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11912 } 11913 11914 private InstallArgs createInstallArgs(InstallParams params) { 11915 if (params.move != null) { 11916 return new MoveInstallArgs(params); 11917 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11918 return new AsecInstallArgs(params); 11919 } else { 11920 return new FileInstallArgs(params); 11921 } 11922 } 11923 11924 /** 11925 * Create args that describe an existing installed package. Typically used 11926 * when cleaning up old installs, or used as a move source. 11927 */ 11928 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11929 String resourcePath, String[] instructionSets) { 11930 final boolean isInAsec; 11931 if (installOnExternalAsec(installFlags)) { 11932 /* Apps on SD card are always in ASEC containers. */ 11933 isInAsec = true; 11934 } else if (installForwardLocked(installFlags) 11935 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11936 /* 11937 * Forward-locked apps are only in ASEC containers if they're the 11938 * new style 11939 */ 11940 isInAsec = true; 11941 } else { 11942 isInAsec = false; 11943 } 11944 11945 if (isInAsec) { 11946 return new AsecInstallArgs(codePath, instructionSets, 11947 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11948 } else { 11949 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11950 } 11951 } 11952 11953 static abstract class InstallArgs { 11954 /** @see InstallParams#origin */ 11955 final OriginInfo origin; 11956 /** @see InstallParams#move */ 11957 final MoveInfo move; 11958 11959 final IPackageInstallObserver2 observer; 11960 // Always refers to PackageManager flags only 11961 final int installFlags; 11962 final String installerPackageName; 11963 final String volumeUuid; 11964 final UserHandle user; 11965 final String abiOverride; 11966 final String[] installGrantPermissions; 11967 /** If non-null, drop an async trace when the install completes */ 11968 final String traceMethod; 11969 final int traceCookie; 11970 11971 // The list of instruction sets supported by this app. This is currently 11972 // only used during the rmdex() phase to clean up resources. We can get rid of this 11973 // if we move dex files under the common app path. 11974 /* nullable */ String[] instructionSets; 11975 11976 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11977 int installFlags, String installerPackageName, String volumeUuid, 11978 UserHandle user, String[] instructionSets, 11979 String abiOverride, String[] installGrantPermissions, 11980 String traceMethod, int traceCookie) { 11981 this.origin = origin; 11982 this.move = move; 11983 this.installFlags = installFlags; 11984 this.observer = observer; 11985 this.installerPackageName = installerPackageName; 11986 this.volumeUuid = volumeUuid; 11987 this.user = user; 11988 this.instructionSets = instructionSets; 11989 this.abiOverride = abiOverride; 11990 this.installGrantPermissions = installGrantPermissions; 11991 this.traceMethod = traceMethod; 11992 this.traceCookie = traceCookie; 11993 } 11994 11995 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11996 abstract int doPreInstall(int status); 11997 11998 /** 11999 * Rename package into final resting place. All paths on the given 12000 * scanned package should be updated to reflect the rename. 12001 */ 12002 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12003 abstract int doPostInstall(int status, int uid); 12004 12005 /** @see PackageSettingBase#codePathString */ 12006 abstract String getCodePath(); 12007 /** @see PackageSettingBase#resourcePathString */ 12008 abstract String getResourcePath(); 12009 12010 // Need installer lock especially for dex file removal. 12011 abstract void cleanUpResourcesLI(); 12012 abstract boolean doPostDeleteLI(boolean delete); 12013 12014 /** 12015 * Called before the source arguments are copied. This is used mostly 12016 * for MoveParams when it needs to read the source file to put it in the 12017 * destination. 12018 */ 12019 int doPreCopy() { 12020 return PackageManager.INSTALL_SUCCEEDED; 12021 } 12022 12023 /** 12024 * Called after the source arguments are copied. This is used mostly for 12025 * MoveParams when it needs to read the source file to put it in the 12026 * destination. 12027 * 12028 * @return 12029 */ 12030 int doPostCopy(int uid) { 12031 return PackageManager.INSTALL_SUCCEEDED; 12032 } 12033 12034 protected boolean isFwdLocked() { 12035 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12036 } 12037 12038 protected boolean isExternalAsec() { 12039 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12040 } 12041 12042 protected boolean isEphemeral() { 12043 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12044 } 12045 12046 UserHandle getUser() { 12047 return user; 12048 } 12049 } 12050 12051 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12052 if (!allCodePaths.isEmpty()) { 12053 if (instructionSets == null) { 12054 throw new IllegalStateException("instructionSet == null"); 12055 } 12056 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12057 for (String codePath : allCodePaths) { 12058 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12059 try { 12060 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12061 } catch (InstallerException ignored) { 12062 } 12063 } 12064 } 12065 } 12066 } 12067 12068 /** 12069 * Logic to handle installation of non-ASEC applications, including copying 12070 * and renaming logic. 12071 */ 12072 class FileInstallArgs extends InstallArgs { 12073 private File codeFile; 12074 private File resourceFile; 12075 12076 // Example topology: 12077 // /data/app/com.example/base.apk 12078 // /data/app/com.example/split_foo.apk 12079 // /data/app/com.example/lib/arm/libfoo.so 12080 // /data/app/com.example/lib/arm64/libfoo.so 12081 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12082 12083 /** New install */ 12084 FileInstallArgs(InstallParams params) { 12085 super(params.origin, params.move, params.observer, params.installFlags, 12086 params.installerPackageName, params.volumeUuid, 12087 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12088 params.grantedRuntimePermissions, 12089 params.traceMethod, params.traceCookie); 12090 if (isFwdLocked()) { 12091 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12092 } 12093 } 12094 12095 /** Existing install */ 12096 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12097 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12098 null, null, null, 0); 12099 this.codeFile = (codePath != null) ? new File(codePath) : null; 12100 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12101 } 12102 12103 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12104 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12105 try { 12106 return doCopyApk(imcs, temp); 12107 } finally { 12108 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12109 } 12110 } 12111 12112 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12113 if (origin.staged) { 12114 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12115 codeFile = origin.file; 12116 resourceFile = origin.file; 12117 return PackageManager.INSTALL_SUCCEEDED; 12118 } 12119 12120 try { 12121 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12122 final File tempDir = 12123 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12124 codeFile = tempDir; 12125 resourceFile = tempDir; 12126 } catch (IOException e) { 12127 Slog.w(TAG, "Failed to create copy file: " + e); 12128 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12129 } 12130 12131 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12132 @Override 12133 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12134 if (!FileUtils.isValidExtFilename(name)) { 12135 throw new IllegalArgumentException("Invalid filename: " + name); 12136 } 12137 try { 12138 final File file = new File(codeFile, name); 12139 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12140 O_RDWR | O_CREAT, 0644); 12141 Os.chmod(file.getAbsolutePath(), 0644); 12142 return new ParcelFileDescriptor(fd); 12143 } catch (ErrnoException e) { 12144 throw new RemoteException("Failed to open: " + e.getMessage()); 12145 } 12146 } 12147 }; 12148 12149 int ret = PackageManager.INSTALL_SUCCEEDED; 12150 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12151 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12152 Slog.e(TAG, "Failed to copy package"); 12153 return ret; 12154 } 12155 12156 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12157 NativeLibraryHelper.Handle handle = null; 12158 try { 12159 handle = NativeLibraryHelper.Handle.create(codeFile); 12160 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12161 abiOverride); 12162 } catch (IOException e) { 12163 Slog.e(TAG, "Copying native libraries failed", e); 12164 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12165 } finally { 12166 IoUtils.closeQuietly(handle); 12167 } 12168 12169 return ret; 12170 } 12171 12172 int doPreInstall(int status) { 12173 if (status != PackageManager.INSTALL_SUCCEEDED) { 12174 cleanUp(); 12175 } 12176 return status; 12177 } 12178 12179 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12180 if (status != PackageManager.INSTALL_SUCCEEDED) { 12181 cleanUp(); 12182 return false; 12183 } 12184 12185 final File targetDir = codeFile.getParentFile(); 12186 final File beforeCodeFile = codeFile; 12187 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12188 12189 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12190 try { 12191 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12192 } catch (ErrnoException e) { 12193 Slog.w(TAG, "Failed to rename", e); 12194 return false; 12195 } 12196 12197 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12198 Slog.w(TAG, "Failed to restorecon"); 12199 return false; 12200 } 12201 12202 // Reflect the rename internally 12203 codeFile = afterCodeFile; 12204 resourceFile = afterCodeFile; 12205 12206 // Reflect the rename in scanned details 12207 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12208 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12209 afterCodeFile, pkg.baseCodePath)); 12210 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12211 afterCodeFile, pkg.splitCodePaths)); 12212 12213 // Reflect the rename in app info 12214 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12215 pkg.setApplicationInfoCodePath(pkg.codePath); 12216 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12217 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12218 pkg.setApplicationInfoResourcePath(pkg.codePath); 12219 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12220 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12221 12222 return true; 12223 } 12224 12225 int doPostInstall(int status, int uid) { 12226 if (status != PackageManager.INSTALL_SUCCEEDED) { 12227 cleanUp(); 12228 } 12229 return status; 12230 } 12231 12232 @Override 12233 String getCodePath() { 12234 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12235 } 12236 12237 @Override 12238 String getResourcePath() { 12239 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12240 } 12241 12242 private boolean cleanUp() { 12243 if (codeFile == null || !codeFile.exists()) { 12244 return false; 12245 } 12246 12247 removeCodePathLI(codeFile); 12248 12249 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12250 resourceFile.delete(); 12251 } 12252 12253 return true; 12254 } 12255 12256 void cleanUpResourcesLI() { 12257 // Try enumerating all code paths before deleting 12258 List<String> allCodePaths = Collections.EMPTY_LIST; 12259 if (codeFile != null && codeFile.exists()) { 12260 try { 12261 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12262 allCodePaths = pkg.getAllCodePaths(); 12263 } catch (PackageParserException e) { 12264 // Ignored; we tried our best 12265 } 12266 } 12267 12268 cleanUp(); 12269 removeDexFiles(allCodePaths, instructionSets); 12270 } 12271 12272 boolean doPostDeleteLI(boolean delete) { 12273 // XXX err, shouldn't we respect the delete flag? 12274 cleanUpResourcesLI(); 12275 return true; 12276 } 12277 } 12278 12279 private boolean isAsecExternal(String cid) { 12280 final String asecPath = PackageHelper.getSdFilesystem(cid); 12281 return !asecPath.startsWith(mAsecInternalPath); 12282 } 12283 12284 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12285 PackageManagerException { 12286 if (copyRet < 0) { 12287 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12288 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12289 throw new PackageManagerException(copyRet, message); 12290 } 12291 } 12292 } 12293 12294 /** 12295 * Extract the MountService "container ID" from the full code path of an 12296 * .apk. 12297 */ 12298 static String cidFromCodePath(String fullCodePath) { 12299 int eidx = fullCodePath.lastIndexOf("/"); 12300 String subStr1 = fullCodePath.substring(0, eidx); 12301 int sidx = subStr1.lastIndexOf("/"); 12302 return subStr1.substring(sidx+1, eidx); 12303 } 12304 12305 /** 12306 * Logic to handle installation of ASEC applications, including copying and 12307 * renaming logic. 12308 */ 12309 class AsecInstallArgs extends InstallArgs { 12310 static final String RES_FILE_NAME = "pkg.apk"; 12311 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12312 12313 String cid; 12314 String packagePath; 12315 String resourcePath; 12316 12317 /** New install */ 12318 AsecInstallArgs(InstallParams params) { 12319 super(params.origin, params.move, params.observer, params.installFlags, 12320 params.installerPackageName, params.volumeUuid, 12321 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12322 params.grantedRuntimePermissions, 12323 params.traceMethod, params.traceCookie); 12324 } 12325 12326 /** Existing install */ 12327 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12328 boolean isExternal, boolean isForwardLocked) { 12329 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12330 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12331 instructionSets, null, null, null, 0); 12332 // Hackily pretend we're still looking at a full code path 12333 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12334 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12335 } 12336 12337 // Extract cid from fullCodePath 12338 int eidx = fullCodePath.lastIndexOf("/"); 12339 String subStr1 = fullCodePath.substring(0, eidx); 12340 int sidx = subStr1.lastIndexOf("/"); 12341 cid = subStr1.substring(sidx+1, eidx); 12342 setMountPath(subStr1); 12343 } 12344 12345 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12346 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12347 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12348 instructionSets, null, null, null, 0); 12349 this.cid = cid; 12350 setMountPath(PackageHelper.getSdDir(cid)); 12351 } 12352 12353 void createCopyFile() { 12354 cid = mInstallerService.allocateExternalStageCidLegacy(); 12355 } 12356 12357 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12358 if (origin.staged && origin.cid != null) { 12359 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12360 cid = origin.cid; 12361 setMountPath(PackageHelper.getSdDir(cid)); 12362 return PackageManager.INSTALL_SUCCEEDED; 12363 } 12364 12365 if (temp) { 12366 createCopyFile(); 12367 } else { 12368 /* 12369 * Pre-emptively destroy the container since it's destroyed if 12370 * copying fails due to it existing anyway. 12371 */ 12372 PackageHelper.destroySdDir(cid); 12373 } 12374 12375 final String newMountPath = imcs.copyPackageToContainer( 12376 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12377 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12378 12379 if (newMountPath != null) { 12380 setMountPath(newMountPath); 12381 return PackageManager.INSTALL_SUCCEEDED; 12382 } else { 12383 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12384 } 12385 } 12386 12387 @Override 12388 String getCodePath() { 12389 return packagePath; 12390 } 12391 12392 @Override 12393 String getResourcePath() { 12394 return resourcePath; 12395 } 12396 12397 int doPreInstall(int status) { 12398 if (status != PackageManager.INSTALL_SUCCEEDED) { 12399 // Destroy container 12400 PackageHelper.destroySdDir(cid); 12401 } else { 12402 boolean mounted = PackageHelper.isContainerMounted(cid); 12403 if (!mounted) { 12404 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 12405 Process.SYSTEM_UID); 12406 if (newMountPath != null) { 12407 setMountPath(newMountPath); 12408 } else { 12409 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12410 } 12411 } 12412 } 12413 return status; 12414 } 12415 12416 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12417 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 12418 String newMountPath = null; 12419 if (PackageHelper.isContainerMounted(cid)) { 12420 // Unmount the container 12421 if (!PackageHelper.unMountSdDir(cid)) { 12422 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 12423 return false; 12424 } 12425 } 12426 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12427 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 12428 " which might be stale. Will try to clean up."); 12429 // Clean up the stale container and proceed to recreate. 12430 if (!PackageHelper.destroySdDir(newCacheId)) { 12431 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 12432 return false; 12433 } 12434 // Successfully cleaned up stale container. Try to rename again. 12435 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12436 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 12437 + " inspite of cleaning it up."); 12438 return false; 12439 } 12440 } 12441 if (!PackageHelper.isContainerMounted(newCacheId)) { 12442 Slog.w(TAG, "Mounting container " + newCacheId); 12443 newMountPath = PackageHelper.mountSdDir(newCacheId, 12444 getEncryptKey(), Process.SYSTEM_UID); 12445 } else { 12446 newMountPath = PackageHelper.getSdDir(newCacheId); 12447 } 12448 if (newMountPath == null) { 12449 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 12450 return false; 12451 } 12452 Log.i(TAG, "Succesfully renamed " + cid + 12453 " to " + newCacheId + 12454 " at new path: " + newMountPath); 12455 cid = newCacheId; 12456 12457 final File beforeCodeFile = new File(packagePath); 12458 setMountPath(newMountPath); 12459 final File afterCodeFile = new File(packagePath); 12460 12461 // Reflect the rename in scanned details 12462 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12463 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12464 afterCodeFile, pkg.baseCodePath)); 12465 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12466 afterCodeFile, pkg.splitCodePaths)); 12467 12468 // Reflect the rename in app info 12469 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12470 pkg.setApplicationInfoCodePath(pkg.codePath); 12471 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12472 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12473 pkg.setApplicationInfoResourcePath(pkg.codePath); 12474 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12475 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12476 12477 return true; 12478 } 12479 12480 private void setMountPath(String mountPath) { 12481 final File mountFile = new File(mountPath); 12482 12483 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 12484 if (monolithicFile.exists()) { 12485 packagePath = monolithicFile.getAbsolutePath(); 12486 if (isFwdLocked()) { 12487 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 12488 } else { 12489 resourcePath = packagePath; 12490 } 12491 } else { 12492 packagePath = mountFile.getAbsolutePath(); 12493 resourcePath = packagePath; 12494 } 12495 } 12496 12497 int doPostInstall(int status, int uid) { 12498 if (status != PackageManager.INSTALL_SUCCEEDED) { 12499 cleanUp(); 12500 } else { 12501 final int groupOwner; 12502 final String protectedFile; 12503 if (isFwdLocked()) { 12504 groupOwner = UserHandle.getSharedAppGid(uid); 12505 protectedFile = RES_FILE_NAME; 12506 } else { 12507 groupOwner = -1; 12508 protectedFile = null; 12509 } 12510 12511 if (uid < Process.FIRST_APPLICATION_UID 12512 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 12513 Slog.e(TAG, "Failed to finalize " + cid); 12514 PackageHelper.destroySdDir(cid); 12515 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12516 } 12517 12518 boolean mounted = PackageHelper.isContainerMounted(cid); 12519 if (!mounted) { 12520 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12521 } 12522 } 12523 return status; 12524 } 12525 12526 private void cleanUp() { 12527 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12528 12529 // Destroy secure container 12530 PackageHelper.destroySdDir(cid); 12531 } 12532 12533 private List<String> getAllCodePaths() { 12534 final File codeFile = new File(getCodePath()); 12535 if (codeFile != null && codeFile.exists()) { 12536 try { 12537 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12538 return pkg.getAllCodePaths(); 12539 } catch (PackageParserException e) { 12540 // Ignored; we tried our best 12541 } 12542 } 12543 return Collections.EMPTY_LIST; 12544 } 12545 12546 void cleanUpResourcesLI() { 12547 // Enumerate all code paths before deleting 12548 cleanUpResourcesLI(getAllCodePaths()); 12549 } 12550 12551 private void cleanUpResourcesLI(List<String> allCodePaths) { 12552 cleanUp(); 12553 removeDexFiles(allCodePaths, instructionSets); 12554 } 12555 12556 String getPackageName() { 12557 return getAsecPackageName(cid); 12558 } 12559 12560 boolean doPostDeleteLI(boolean delete) { 12561 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12562 final List<String> allCodePaths = getAllCodePaths(); 12563 boolean mounted = PackageHelper.isContainerMounted(cid); 12564 if (mounted) { 12565 // Unmount first 12566 if (PackageHelper.unMountSdDir(cid)) { 12567 mounted = false; 12568 } 12569 } 12570 if (!mounted && delete) { 12571 cleanUpResourcesLI(allCodePaths); 12572 } 12573 return !mounted; 12574 } 12575 12576 @Override 12577 int doPreCopy() { 12578 if (isFwdLocked()) { 12579 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12580 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12581 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12582 } 12583 } 12584 12585 return PackageManager.INSTALL_SUCCEEDED; 12586 } 12587 12588 @Override 12589 int doPostCopy(int uid) { 12590 if (isFwdLocked()) { 12591 if (uid < Process.FIRST_APPLICATION_UID 12592 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12593 RES_FILE_NAME)) { 12594 Slog.e(TAG, "Failed to finalize " + cid); 12595 PackageHelper.destroySdDir(cid); 12596 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12597 } 12598 } 12599 12600 return PackageManager.INSTALL_SUCCEEDED; 12601 } 12602 } 12603 12604 /** 12605 * Logic to handle movement of existing installed applications. 12606 */ 12607 class MoveInstallArgs extends InstallArgs { 12608 private File codeFile; 12609 private File resourceFile; 12610 12611 /** New install */ 12612 MoveInstallArgs(InstallParams params) { 12613 super(params.origin, params.move, params.observer, params.installFlags, 12614 params.installerPackageName, params.volumeUuid, 12615 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12616 params.grantedRuntimePermissions, 12617 params.traceMethod, params.traceCookie); 12618 } 12619 12620 int copyApk(IMediaContainerService imcs, boolean temp) { 12621 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12622 + move.fromUuid + " to " + move.toUuid); 12623 synchronized (mInstaller) { 12624 try { 12625 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12626 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12627 } catch (InstallerException e) { 12628 Slog.w(TAG, "Failed to move app", e); 12629 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12630 } 12631 } 12632 12633 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12634 resourceFile = codeFile; 12635 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12636 12637 return PackageManager.INSTALL_SUCCEEDED; 12638 } 12639 12640 int doPreInstall(int status) { 12641 if (status != PackageManager.INSTALL_SUCCEEDED) { 12642 cleanUp(move.toUuid); 12643 } 12644 return status; 12645 } 12646 12647 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12648 if (status != PackageManager.INSTALL_SUCCEEDED) { 12649 cleanUp(move.toUuid); 12650 return false; 12651 } 12652 12653 // Reflect the move in app info 12654 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12655 pkg.setApplicationInfoCodePath(pkg.codePath); 12656 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12657 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12658 pkg.setApplicationInfoResourcePath(pkg.codePath); 12659 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12660 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12661 12662 return true; 12663 } 12664 12665 int doPostInstall(int status, int uid) { 12666 if (status == PackageManager.INSTALL_SUCCEEDED) { 12667 cleanUp(move.fromUuid); 12668 } else { 12669 cleanUp(move.toUuid); 12670 } 12671 return status; 12672 } 12673 12674 @Override 12675 String getCodePath() { 12676 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12677 } 12678 12679 @Override 12680 String getResourcePath() { 12681 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12682 } 12683 12684 private boolean cleanUp(String volumeUuid) { 12685 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12686 move.dataAppName); 12687 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12688 synchronized (mInstallLock) { 12689 // Clean up both app data and code 12690 removeDataDirsLI(volumeUuid, move.packageName); 12691 removeCodePathLI(codeFile); 12692 } 12693 return true; 12694 } 12695 12696 void cleanUpResourcesLI() { 12697 throw new UnsupportedOperationException(); 12698 } 12699 12700 boolean doPostDeleteLI(boolean delete) { 12701 throw new UnsupportedOperationException(); 12702 } 12703 } 12704 12705 static String getAsecPackageName(String packageCid) { 12706 int idx = packageCid.lastIndexOf("-"); 12707 if (idx == -1) { 12708 return packageCid; 12709 } 12710 return packageCid.substring(0, idx); 12711 } 12712 12713 // Utility method used to create code paths based on package name and available index. 12714 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12715 String idxStr = ""; 12716 int idx = 1; 12717 // Fall back to default value of idx=1 if prefix is not 12718 // part of oldCodePath 12719 if (oldCodePath != null) { 12720 String subStr = oldCodePath; 12721 // Drop the suffix right away 12722 if (suffix != null && subStr.endsWith(suffix)) { 12723 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12724 } 12725 // If oldCodePath already contains prefix find out the 12726 // ending index to either increment or decrement. 12727 int sidx = subStr.lastIndexOf(prefix); 12728 if (sidx != -1) { 12729 subStr = subStr.substring(sidx + prefix.length()); 12730 if (subStr != null) { 12731 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12732 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12733 } 12734 try { 12735 idx = Integer.parseInt(subStr); 12736 if (idx <= 1) { 12737 idx++; 12738 } else { 12739 idx--; 12740 } 12741 } catch(NumberFormatException e) { 12742 } 12743 } 12744 } 12745 } 12746 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12747 return prefix + idxStr; 12748 } 12749 12750 private File getNextCodePath(File targetDir, String packageName) { 12751 int suffix = 1; 12752 File result; 12753 do { 12754 result = new File(targetDir, packageName + "-" + suffix); 12755 suffix++; 12756 } while (result.exists()); 12757 return result; 12758 } 12759 12760 // Utility method that returns the relative package path with respect 12761 // to the installation directory. Like say for /data/data/com.test-1.apk 12762 // string com.test-1 is returned. 12763 static String deriveCodePathName(String codePath) { 12764 if (codePath == null) { 12765 return null; 12766 } 12767 final File codeFile = new File(codePath); 12768 final String name = codeFile.getName(); 12769 if (codeFile.isDirectory()) { 12770 return name; 12771 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12772 final int lastDot = name.lastIndexOf('.'); 12773 return name.substring(0, lastDot); 12774 } else { 12775 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12776 return null; 12777 } 12778 } 12779 12780 static class PackageInstalledInfo { 12781 String name; 12782 int uid; 12783 // The set of users that originally had this package installed. 12784 int[] origUsers; 12785 // The set of users that now have this package installed. 12786 int[] newUsers; 12787 PackageParser.Package pkg; 12788 int returnCode; 12789 String returnMsg; 12790 PackageRemovedInfo removedInfo; 12791 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 12792 12793 public void setError(int code, String msg) { 12794 setReturnCode(code); 12795 setReturnMessage(msg); 12796 Slog.w(TAG, msg); 12797 } 12798 12799 public void setError(String msg, PackageParserException e) { 12800 setReturnCode(e.error); 12801 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 12802 Slog.w(TAG, msg, e); 12803 } 12804 12805 public void setError(String msg, PackageManagerException e) { 12806 returnCode = e.error; 12807 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 12808 Slog.w(TAG, msg, e); 12809 } 12810 12811 public void setReturnCode(int returnCode) { 12812 this.returnCode = returnCode; 12813 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 12814 for (int i = 0; i < childCount; i++) { 12815 addedChildPackages.valueAt(i).returnCode = returnCode; 12816 } 12817 } 12818 12819 private void setReturnMessage(String returnMsg) { 12820 this.returnMsg = returnMsg; 12821 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 12822 for (int i = 0; i < childCount; i++) { 12823 addedChildPackages.valueAt(i).returnMsg = returnMsg; 12824 } 12825 } 12826 12827 // In some error cases we want to convey more info back to the observer 12828 String origPackage; 12829 String origPermission; 12830 } 12831 12832 /* 12833 * Install a non-existing package. 12834 */ 12835 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12836 UserHandle user, String installerPackageName, String volumeUuid, 12837 PackageInstalledInfo res) { 12838 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12839 12840 // Remember this for later, in case we need to rollback this install 12841 String pkgName = pkg.packageName; 12842 12843 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12844 12845 synchronized(mPackages) { 12846 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12847 // A package with the same name is already installed, though 12848 // it has been renamed to an older name. The package we 12849 // are trying to install should be installed as an update to 12850 // the existing one, but that has not been requested, so bail. 12851 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12852 + " without first uninstalling package running as " 12853 + mSettings.mRenamedPackages.get(pkgName)); 12854 return; 12855 } 12856 if (mPackages.containsKey(pkgName)) { 12857 // Don't allow installation over an existing package with the same name. 12858 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12859 + " without first uninstalling."); 12860 return; 12861 } 12862 } 12863 12864 try { 12865 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12866 System.currentTimeMillis(), user); 12867 12868 updateSettingsLI(newPackage, installerPackageName, null, res, user); 12869 12870 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12871 prepareAppDataAfterInstall(newPackage); 12872 12873 } else { 12874 // Remove package from internal structures, but keep around any 12875 // data that might have already existed 12876 deletePackageLI(pkgName, UserHandle.ALL, false, null, 12877 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 12878 } 12879 } catch (PackageManagerException e) { 12880 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12881 } 12882 12883 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12884 } 12885 12886 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12887 // Can't rotate keys during boot or if sharedUser. 12888 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12889 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12890 return false; 12891 } 12892 // app is using upgradeKeySets; make sure all are valid 12893 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12894 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12895 for (int i = 0; i < upgradeKeySets.length; i++) { 12896 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12897 Slog.wtf(TAG, "Package " 12898 + (oldPs.name != null ? oldPs.name : "<null>") 12899 + " contains upgrade-key-set reference to unknown key-set: " 12900 + upgradeKeySets[i] 12901 + " reverting to signatures check."); 12902 return false; 12903 } 12904 } 12905 return true; 12906 } 12907 12908 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12909 // Upgrade keysets are being used. Determine if new package has a superset of the 12910 // required keys. 12911 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12912 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12913 for (int i = 0; i < upgradeKeySets.length; i++) { 12914 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12915 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12916 return true; 12917 } 12918 } 12919 return false; 12920 } 12921 12922 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12923 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 12924 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12925 12926 final PackageParser.Package oldPackage; 12927 final String pkgName = pkg.packageName; 12928 final int[] allUsers; 12929 12930 // First find the old package info and check signatures 12931 synchronized(mPackages) { 12932 oldPackage = mPackages.get(pkgName); 12933 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12934 if (isEphemeral && !oldIsEphemeral) { 12935 // can't downgrade from full to ephemeral 12936 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12937 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 12938 return; 12939 } 12940 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12941 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12942 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12943 if (!checkUpgradeKeySetLP(ps, pkg)) { 12944 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12945 "New package not signed by keys specified by upgrade-keysets: " 12946 + pkgName); 12947 return; 12948 } 12949 } else { 12950 // default to original signature matching 12951 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12952 != PackageManager.SIGNATURE_MATCH) { 12953 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12954 "New package has a different signature: " + pkgName); 12955 return; 12956 } 12957 } 12958 12959 // In case of rollback, remember per-user/profile install state 12960 allUsers = sUserManager.getUserIds(); 12961 } 12962 12963 // Update what is removed 12964 res.removedInfo = new PackageRemovedInfo(); 12965 res.removedInfo.uid = oldPackage.applicationInfo.uid; 12966 res.removedInfo.removedPackage = oldPackage.packageName; 12967 res.removedInfo.isUpdate = true; 12968 final int childCount = (oldPackage.childPackages != null) 12969 ? oldPackage.childPackages.size() : 0; 12970 for (int i = 0; i < childCount; i++) { 12971 boolean childPackageUpdated = false; 12972 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 12973 if (res.addedChildPackages != null) { 12974 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 12975 if (childRes != null) { 12976 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 12977 childRes.removedInfo.removedPackage = childPkg.packageName; 12978 childRes.removedInfo.isUpdate = true; 12979 childPackageUpdated = true; 12980 } 12981 } 12982 if (!childPackageUpdated) { 12983 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 12984 childRemovedRes.removedPackage = childPkg.packageName; 12985 childRemovedRes.isUpdate = false; 12986 childRemovedRes.dataRemoved = true; 12987 synchronized (mPackages) { 12988 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 12989 if (childPs != null) { 12990 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 12991 } 12992 } 12993 if (res.removedInfo.removedChildPackages == null) { 12994 res.removedInfo.removedChildPackages = new ArrayMap<>(); 12995 } 12996 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 12997 } 12998 } 12999 13000 boolean sysPkg = (isSystemApp(oldPackage)); 13001 if (sysPkg) { 13002 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13003 user, allUsers, installerPackageName, res); 13004 } else { 13005 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13006 user, allUsers, installerPackageName, res); 13007 } 13008 } 13009 13010 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 13011 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13012 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13013 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13014 + deletedPackage); 13015 13016 String pkgName = deletedPackage.packageName; 13017 boolean deletedPkg = true; 13018 boolean addedPkg = false; 13019 13020 final long origUpdateTime = (pkg.mExtras != null) 13021 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13022 13023 // First delete the existing package while retaining the data directory 13024 if (!deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA, 13025 res.removedInfo, true, pkg)) { 13026 // If the existing package wasn't successfully deleted 13027 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13028 deletedPkg = false; 13029 } else { 13030 // Successfully deleted the old package; proceed with replace. 13031 13032 // If deleted package lived in a container, give users a chance to 13033 // relinquish resources before killing. 13034 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13035 if (DEBUG_INSTALL) { 13036 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13037 } 13038 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13039 final ArrayList<String> pkgList = new ArrayList<String>(1); 13040 pkgList.add(deletedPackage.applicationInfo.packageName); 13041 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13042 } 13043 13044 deleteCodeCacheDirsLI(pkg); 13045 13046 try { 13047 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13048 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13049 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13050 prepareAppDataAfterInstall(newPackage); 13051 addedPkg = true; 13052 } catch (PackageManagerException e) { 13053 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13054 } 13055 } 13056 13057 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13058 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13059 13060 // Revert all internal state mutations and added folders for the failed install 13061 if (addedPkg) { 13062 deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA, 13063 res.removedInfo, true, null); 13064 } 13065 13066 // Restore the old package 13067 if (deletedPkg) { 13068 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13069 File restoreFile = new File(deletedPackage.codePath); 13070 // Parse old package 13071 boolean oldExternal = isExternal(deletedPackage); 13072 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13073 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13074 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13075 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13076 try { 13077 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13078 null); 13079 } catch (PackageManagerException e) { 13080 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13081 + e.getMessage()); 13082 return; 13083 } 13084 13085 synchronized (mPackages) { 13086 // Ensure the installer package name up to date 13087 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13088 13089 // Update permissions for restored package 13090 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13091 13092 mSettings.writeLPr(); 13093 } 13094 13095 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13096 } 13097 } else { 13098 synchronized (mPackages) { 13099 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13100 if (ps != null) { 13101 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13102 if (res.removedInfo.removedChildPackages != null) { 13103 final int childCount = res.removedInfo.removedChildPackages.size(); 13104 // Iterate in reverse as we may modify the collection 13105 for (int i = childCount - 1; i >= 0; i--) { 13106 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13107 if (res.addedChildPackages.containsKey(childPackageName)) { 13108 res.removedInfo.removedChildPackages.removeAt(i); 13109 } else { 13110 PackageRemovedInfo childInfo = res.removedInfo 13111 .removedChildPackages.valueAt(i); 13112 childInfo.removedForAllUsers = mPackages.get( 13113 childInfo.removedPackage) == null; 13114 } 13115 } 13116 } 13117 } 13118 } 13119 } 13120 } 13121 13122 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 13123 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13124 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13125 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13126 + ", old=" + deletedPackage); 13127 13128 final boolean disabledSystem; 13129 13130 // Set the system/privileged flags as needed 13131 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13132 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13133 != 0) { 13134 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13135 } 13136 13137 // Kill package processes including services, providers, etc. 13138 killPackage(deletedPackage, "replace sys pkg"); 13139 13140 // Remove existing system package 13141 removePackageLI(deletedPackage, true); 13142 13143 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13144 if (!disabledSystem) { 13145 // We didn't need to disable the .apk as a current system package, 13146 // which means we are replacing another update that is already 13147 // installed. We need to make sure to delete the older one's .apk. 13148 res.removedInfo.args = createInstallArgsForExisting(0, 13149 deletedPackage.applicationInfo.getCodePath(), 13150 deletedPackage.applicationInfo.getResourcePath(), 13151 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13152 } else { 13153 res.removedInfo.args = null; 13154 } 13155 13156 // Successfully disabled the old package. Now proceed with re-installation 13157 deleteCodeCacheDirsLI(pkg); 13158 13159 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13160 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13161 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13162 13163 PackageParser.Package newPackage = null; 13164 try { 13165 // Add the package to the internal data structures 13166 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13167 13168 // Set the update and install times 13169 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13170 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13171 System.currentTimeMillis()); 13172 13173 // Check for shared user id changes 13174 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13175 deletedPackage, newPackage); 13176 if (invalidPackageName != null) { 13177 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13178 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13179 + " to " + invalidPackageName); 13180 } 13181 13182 // Update the package dynamic state if succeeded 13183 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13184 // Now that the install succeeded make sure we remove data 13185 // directories for any child package the update removed. 13186 final int deletedChildCount = (deletedPackage.childPackages != null) 13187 ? deletedPackage.childPackages.size() : 0; 13188 final int newChildCount = (newPackage.childPackages != null) 13189 ? newPackage.childPackages.size() : 0; 13190 for (int i = 0; i < deletedChildCount; i++) { 13191 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13192 boolean childPackageDeleted = true; 13193 for (int j = 0; j < newChildCount; j++) { 13194 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13195 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13196 childPackageDeleted = false; 13197 break; 13198 } 13199 } 13200 if (childPackageDeleted) { 13201 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13202 deletedChildPkg.packageName); 13203 if (ps != null && res.removedInfo.removedChildPackages != null) { 13204 PackageRemovedInfo removedChildRes = res.removedInfo 13205 .removedChildPackages.get(deletedChildPkg.packageName); 13206 removePackageDataLI(ps, allUsers, removedChildRes, 0, false); 13207 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13208 } 13209 } 13210 } 13211 13212 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13213 prepareAppDataAfterInstall(newPackage); 13214 } 13215 } catch (PackageManagerException e) { 13216 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13217 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13218 } 13219 13220 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13221 // Re installation failed. Restore old information 13222 // Remove new pkg information 13223 if (newPackage != null) { 13224 removeInstalledPackageLI(newPackage, true); 13225 } 13226 // Add back the old system package 13227 try { 13228 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13229 } catch (PackageManagerException e) { 13230 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13231 } 13232 13233 synchronized (mPackages) { 13234 if (disabledSystem) { 13235 enableSystemPackageLPw(deletedPackage); 13236 } 13237 13238 // Ensure the installer package name up to date 13239 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13240 13241 // Update permissions for restored package 13242 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13243 13244 mSettings.writeLPr(); 13245 } 13246 13247 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13248 + " after failed upgrade"); 13249 } 13250 } 13251 13252 /** 13253 * Checks whether the parent or any of the child packages have a change shared 13254 * user. For a package to be a valid update the shred users of the parent and 13255 * the children should match. We may later support changing child shared users. 13256 * @param oldPkg The updated package. 13257 * @param newPkg The update package. 13258 * @return The shared user that change between the versions. 13259 */ 13260 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13261 PackageParser.Package newPkg) { 13262 // Check parent shared user 13263 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13264 return newPkg.packageName; 13265 } 13266 // Check child shared users 13267 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13268 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13269 for (int i = 0; i < newChildCount; i++) { 13270 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13271 // If this child was present, did it have the same shared user? 13272 for (int j = 0; j < oldChildCount; j++) { 13273 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13274 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13275 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13276 return newChildPkg.packageName; 13277 } 13278 } 13279 } 13280 return null; 13281 } 13282 13283 private void removeNativeBinariesLI(PackageParser.Package pkg) { 13284 // Remove the lib path for the parent package 13285 PackageSetting ps = (PackageSetting) pkg.mExtras; 13286 if (ps != null) { 13287 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13288 } 13289 // Remove the lib path for the child packages 13290 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13291 for (int i = 0; i < childCount; i++) { 13292 ps = (PackageSetting) pkg.childPackages.get(i).mExtras; 13293 if (ps != null) { 13294 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13295 } 13296 } 13297 } 13298 13299 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13300 // Enable the parent package 13301 mSettings.enableSystemPackageLPw(pkg.packageName); 13302 // Enable the child packages 13303 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13304 for (int i = 0; i < childCount; i++) { 13305 PackageParser.Package childPkg = pkg.childPackages.get(i); 13306 mSettings.enableSystemPackageLPw(childPkg.packageName); 13307 } 13308 } 13309 13310 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13311 PackageParser.Package newPkg) { 13312 // Disable the parent package (parent always replaced) 13313 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13314 // Disable the child packages 13315 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13316 for (int i = 0; i < childCount; i++) { 13317 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13318 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13319 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13320 } 13321 return disabled; 13322 } 13323 13324 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13325 String installerPackageName) { 13326 // Enable the parent package 13327 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 13328 // Enable the child packages 13329 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13330 for (int i = 0; i < childCount; i++) { 13331 PackageParser.Package childPkg = pkg.childPackages.get(i); 13332 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 13333 } 13334 } 13335 13336 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 13337 // Collect all used permissions in the UID 13338 ArraySet<String> usedPermissions = new ArraySet<>(); 13339 final int packageCount = su.packages.size(); 13340 for (int i = 0; i < packageCount; i++) { 13341 PackageSetting ps = su.packages.valueAt(i); 13342 if (ps.pkg == null) { 13343 continue; 13344 } 13345 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 13346 for (int j = 0; j < requestedPermCount; j++) { 13347 String permission = ps.pkg.requestedPermissions.get(j); 13348 BasePermission bp = mSettings.mPermissions.get(permission); 13349 if (bp != null) { 13350 usedPermissions.add(permission); 13351 } 13352 } 13353 } 13354 13355 PermissionsState permissionsState = su.getPermissionsState(); 13356 // Prune install permissions 13357 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 13358 final int installPermCount = installPermStates.size(); 13359 for (int i = installPermCount - 1; i >= 0; i--) { 13360 PermissionState permissionState = installPermStates.get(i); 13361 if (!usedPermissions.contains(permissionState.getName())) { 13362 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13363 if (bp != null) { 13364 permissionsState.revokeInstallPermission(bp); 13365 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 13366 PackageManager.MASK_PERMISSION_FLAGS, 0); 13367 } 13368 } 13369 } 13370 13371 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 13372 13373 // Prune runtime permissions 13374 for (int userId : allUserIds) { 13375 List<PermissionState> runtimePermStates = permissionsState 13376 .getRuntimePermissionStates(userId); 13377 final int runtimePermCount = runtimePermStates.size(); 13378 for (int i = runtimePermCount - 1; i >= 0; i--) { 13379 PermissionState permissionState = runtimePermStates.get(i); 13380 if (!usedPermissions.contains(permissionState.getName())) { 13381 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13382 if (bp != null) { 13383 permissionsState.revokeRuntimePermission(bp, userId); 13384 permissionsState.updatePermissionFlags(bp, userId, 13385 PackageManager.MASK_PERMISSION_FLAGS, 0); 13386 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 13387 runtimePermissionChangedUserIds, userId); 13388 } 13389 } 13390 } 13391 } 13392 13393 return runtimePermissionChangedUserIds; 13394 } 13395 13396 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 13397 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 13398 // Update the parent package setting 13399 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 13400 res, user); 13401 // Update the child packages setting 13402 final int childCount = (newPackage.childPackages != null) 13403 ? newPackage.childPackages.size() : 0; 13404 for (int i = 0; i < childCount; i++) { 13405 PackageParser.Package childPackage = newPackage.childPackages.get(i); 13406 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 13407 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 13408 childRes.origUsers, childRes, user); 13409 } 13410 } 13411 13412 private void updateSettingsInternalLI(PackageParser.Package newPackage, 13413 String installerPackageName, int[] allUsers, int[] installedForUsers, 13414 PackageInstalledInfo res, UserHandle user) { 13415 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 13416 13417 String pkgName = newPackage.packageName; 13418 synchronized (mPackages) { 13419 //write settings. the installStatus will be incomplete at this stage. 13420 //note that the new package setting would have already been 13421 //added to mPackages. It hasn't been persisted yet. 13422 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 13423 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13424 mSettings.writeLPr(); 13425 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13426 } 13427 13428 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 13429 synchronized (mPackages) { 13430 updatePermissionsLPw(newPackage.packageName, newPackage, 13431 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 13432 ? UPDATE_PERMISSIONS_ALL : 0)); 13433 // For system-bundled packages, we assume that installing an upgraded version 13434 // of the package implies that the user actually wants to run that new code, 13435 // so we enable the package. 13436 PackageSetting ps = mSettings.mPackages.get(pkgName); 13437 final int userId = user.getIdentifier(); 13438 if (ps != null) { 13439 if (isSystemApp(newPackage)) { 13440 if (DEBUG_INSTALL) { 13441 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 13442 } 13443 // Enable system package for requested users 13444 if (res.origUsers != null) { 13445 for (int origUserId : res.origUsers) { 13446 if (userId == UserHandle.USER_ALL || userId == origUserId) { 13447 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 13448 origUserId, installerPackageName); 13449 } 13450 } 13451 } 13452 // Also convey the prior install/uninstall state 13453 if (allUsers != null && installedForUsers != null) { 13454 for (int currentUserId : allUsers) { 13455 final boolean installed = ArrayUtils.contains( 13456 installedForUsers, currentUserId); 13457 if (DEBUG_INSTALL) { 13458 Slog.d(TAG, " user " + currentUserId + " => " + installed); 13459 } 13460 ps.setInstalled(installed, currentUserId); 13461 } 13462 // these install state changes will be persisted in the 13463 // upcoming call to mSettings.writeLPr(). 13464 } 13465 } 13466 // It's implied that when a user requests installation, they want the app to be 13467 // installed and enabled. 13468 if (userId != UserHandle.USER_ALL) { 13469 ps.setInstalled(true, userId); 13470 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 13471 } 13472 } 13473 res.name = pkgName; 13474 res.uid = newPackage.applicationInfo.uid; 13475 res.pkg = newPackage; 13476 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 13477 mSettings.setInstallerPackageName(pkgName, installerPackageName); 13478 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13479 //to update install status 13480 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13481 mSettings.writeLPr(); 13482 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13483 } 13484 13485 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13486 } 13487 13488 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 13489 try { 13490 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 13491 installPackageLI(args, res); 13492 } finally { 13493 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13494 } 13495 } 13496 13497 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 13498 final int installFlags = args.installFlags; 13499 final String installerPackageName = args.installerPackageName; 13500 final String volumeUuid = args.volumeUuid; 13501 final File tmpPackageFile = new File(args.getCodePath()); 13502 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 13503 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 13504 || (args.volumeUuid != null)); 13505 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 13506 boolean replace = false; 13507 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 13508 if (args.move != null) { 13509 // moving a complete application; perform an initial scan on the new install location 13510 scanFlags |= SCAN_INITIAL; 13511 } 13512 13513 // Result object to be returned 13514 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13515 13516 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 13517 13518 // Sanity check 13519 if (ephemeral && (forwardLocked || onExternal)) { 13520 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 13521 + " external=" + onExternal); 13522 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13523 return; 13524 } 13525 13526 // Retrieve PackageSettings and parse package 13527 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 13528 | PackageParser.PARSE_ENFORCE_CODE 13529 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 13530 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 13531 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 13532 PackageParser pp = new PackageParser(); 13533 pp.setSeparateProcesses(mSeparateProcesses); 13534 pp.setDisplayMetrics(mMetrics); 13535 13536 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 13537 final PackageParser.Package pkg; 13538 try { 13539 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 13540 } catch (PackageParserException e) { 13541 res.setError("Failed parse during installPackageLI", e); 13542 return; 13543 } finally { 13544 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13545 } 13546 13547 // If we are installing a clustered package add results for the children 13548 if (pkg.childPackages != null) { 13549 synchronized (mPackages) { 13550 final int childCount = pkg.childPackages.size(); 13551 for (int i = 0; i < childCount; i++) { 13552 PackageParser.Package childPkg = pkg.childPackages.get(i); 13553 PackageInstalledInfo childRes = new PackageInstalledInfo(); 13554 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13555 childRes.pkg = childPkg; 13556 childRes.name = childPkg.packageName; 13557 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13558 if (childPs != null) { 13559 childRes.origUsers = childPs.queryInstalledUsers( 13560 sUserManager.getUserIds(), true); 13561 } 13562 if ((mPackages.containsKey(childPkg.packageName))) { 13563 childRes.removedInfo = new PackageRemovedInfo(); 13564 childRes.removedInfo.removedPackage = childPkg.packageName; 13565 } 13566 if (res.addedChildPackages == null) { 13567 res.addedChildPackages = new ArrayMap<>(); 13568 } 13569 res.addedChildPackages.put(childPkg.packageName, childRes); 13570 } 13571 } 13572 } 13573 13574 // If package doesn't declare API override, mark that we have an install 13575 // time CPU ABI override. 13576 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 13577 pkg.cpuAbiOverride = args.abiOverride; 13578 } 13579 13580 String pkgName = res.name = pkg.packageName; 13581 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 13582 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 13583 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 13584 return; 13585 } 13586 } 13587 13588 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 13589 try { 13590 PackageParser.collectCertificates(pkg, parseFlags); 13591 } catch (PackageParserException e) { 13592 res.setError("Failed collect during installPackageLI", e); 13593 return; 13594 } finally { 13595 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13596 } 13597 13598 // Get rid of all references to package scan path via parser. 13599 pp = null; 13600 String oldCodePath = null; 13601 boolean systemApp = false; 13602 synchronized (mPackages) { 13603 // Check if installing already existing package 13604 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13605 String oldName = mSettings.mRenamedPackages.get(pkgName); 13606 if (pkg.mOriginalPackages != null 13607 && pkg.mOriginalPackages.contains(oldName) 13608 && mPackages.containsKey(oldName)) { 13609 // This package is derived from an original package, 13610 // and this device has been updating from that original 13611 // name. We must continue using the original name, so 13612 // rename the new package here. 13613 pkg.setPackageName(oldName); 13614 pkgName = pkg.packageName; 13615 replace = true; 13616 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 13617 + oldName + " pkgName=" + pkgName); 13618 } else if (mPackages.containsKey(pkgName)) { 13619 // This package, under its official name, already exists 13620 // on the device; we should replace it. 13621 replace = true; 13622 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 13623 } 13624 13625 // Child packages are installed through the parent package 13626 if (pkg.parentPackage != null) { 13627 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13628 "Package " + pkg.packageName + " is child of package " 13629 + pkg.parentPackage.parentPackage + ". Child packages " 13630 + "can be updated only through the parent package."); 13631 return; 13632 } 13633 13634 if (replace) { 13635 // Prevent apps opting out from runtime permissions 13636 PackageParser.Package oldPackage = mPackages.get(pkgName); 13637 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 13638 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 13639 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 13640 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 13641 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 13642 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 13643 + " doesn't support runtime permissions but the old" 13644 + " target SDK " + oldTargetSdk + " does."); 13645 return; 13646 } 13647 13648 // Prevent installing of child packages 13649 if (oldPackage.parentPackage != null) { 13650 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13651 "Package " + pkg.packageName + " is child of package " 13652 + oldPackage.parentPackage + ". Child packages " 13653 + "can be updated only through the parent package."); 13654 return; 13655 } 13656 } 13657 } 13658 13659 PackageSetting ps = mSettings.mPackages.get(pkgName); 13660 if (ps != null) { 13661 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 13662 13663 // Quick sanity check that we're signed correctly if updating; 13664 // we'll check this again later when scanning, but we want to 13665 // bail early here before tripping over redefined permissions. 13666 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13667 if (!checkUpgradeKeySetLP(ps, pkg)) { 13668 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 13669 + pkg.packageName + " upgrade keys do not match the " 13670 + "previously installed version"); 13671 return; 13672 } 13673 } else { 13674 try { 13675 verifySignaturesLP(ps, pkg); 13676 } catch (PackageManagerException e) { 13677 res.setError(e.error, e.getMessage()); 13678 return; 13679 } 13680 } 13681 13682 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 13683 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 13684 systemApp = (ps.pkg.applicationInfo.flags & 13685 ApplicationInfo.FLAG_SYSTEM) != 0; 13686 } 13687 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13688 } 13689 13690 // Check whether the newly-scanned package wants to define an already-defined perm 13691 int N = pkg.permissions.size(); 13692 for (int i = N-1; i >= 0; i--) { 13693 PackageParser.Permission perm = pkg.permissions.get(i); 13694 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 13695 if (bp != null) { 13696 // If the defining package is signed with our cert, it's okay. This 13697 // also includes the "updating the same package" case, of course. 13698 // "updating same package" could also involve key-rotation. 13699 final boolean sigsOk; 13700 if (bp.sourcePackage.equals(pkg.packageName) 13701 && (bp.packageSetting instanceof PackageSetting) 13702 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 13703 scanFlags))) { 13704 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 13705 } else { 13706 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 13707 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 13708 } 13709 if (!sigsOk) { 13710 // If the owning package is the system itself, we log but allow 13711 // install to proceed; we fail the install on all other permission 13712 // redefinitions. 13713 if (!bp.sourcePackage.equals("android")) { 13714 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 13715 + pkg.packageName + " attempting to redeclare permission " 13716 + perm.info.name + " already owned by " + bp.sourcePackage); 13717 res.origPermission = perm.info.name; 13718 res.origPackage = bp.sourcePackage; 13719 return; 13720 } else { 13721 Slog.w(TAG, "Package " + pkg.packageName 13722 + " attempting to redeclare system permission " 13723 + perm.info.name + "; ignoring new declaration"); 13724 pkg.permissions.remove(i); 13725 } 13726 } 13727 } 13728 } 13729 } 13730 13731 if (systemApp) { 13732 if (onExternal) { 13733 // Abort update; system app can't be replaced with app on sdcard 13734 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 13735 "Cannot install updates to system apps on sdcard"); 13736 return; 13737 } else if (ephemeral) { 13738 // Abort update; system app can't be replaced with an ephemeral app 13739 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 13740 "Cannot update a system app with an ephemeral app"); 13741 return; 13742 } 13743 } 13744 13745 if (args.move != null) { 13746 // We did an in-place move, so dex is ready to roll 13747 scanFlags |= SCAN_NO_DEX; 13748 scanFlags |= SCAN_MOVE; 13749 13750 synchronized (mPackages) { 13751 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13752 if (ps == null) { 13753 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 13754 "Missing settings for moved package " + pkgName); 13755 } 13756 13757 // We moved the entire application as-is, so bring over the 13758 // previously derived ABI information. 13759 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13760 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13761 } 13762 13763 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13764 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13765 scanFlags |= SCAN_NO_DEX; 13766 13767 try { 13768 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 13769 args.abiOverride : pkg.cpuAbiOverride); 13770 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 13771 true /* extract libs */); 13772 } catch (PackageManagerException pme) { 13773 Slog.e(TAG, "Error deriving application ABI", pme); 13774 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13775 return; 13776 } 13777 13778 // Extract package to save the VM unzipping the APK in memory during 13779 // launch. Only do this if profile-guided compilation is enabled because 13780 // otherwise BackgroundDexOptService will not dexopt the package later. 13781 if (mUseJitProfiles) { 13782 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 13783 // Do not run PackageDexOptimizer through the local performDexOpt 13784 // method because `pkg` is not in `mPackages` yet. 13785 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 13786 false /* useProfiles */, true /* extractOnly */); 13787 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13788 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 13789 String msg = "Extracking package failed for " + pkgName; 13790 res.setError(INSTALL_FAILED_DEXOPT, msg); 13791 return; 13792 } 13793 } 13794 } 13795 13796 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13797 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13798 return; 13799 } 13800 13801 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13802 13803 if (replace) { 13804 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13805 installerPackageName, res); 13806 } else { 13807 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13808 args.user, installerPackageName, volumeUuid, res); 13809 } 13810 synchronized (mPackages) { 13811 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13812 if (ps != null) { 13813 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13814 } 13815 13816 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13817 for (int i = 0; i < childCount; i++) { 13818 PackageParser.Package childPkg = pkg.childPackages.get(i); 13819 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13820 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13821 if (childPs != null) { 13822 childRes.newUsers = childPs.queryInstalledUsers( 13823 sUserManager.getUserIds(), true); 13824 } 13825 } 13826 } 13827 } 13828 13829 private void startIntentFilterVerifications(int userId, boolean replacing, 13830 PackageParser.Package pkg) { 13831 if (mIntentFilterVerifierComponent == null) { 13832 Slog.w(TAG, "No IntentFilter verification will not be done as " 13833 + "there is no IntentFilterVerifier available!"); 13834 return; 13835 } 13836 13837 final int verifierUid = getPackageUid( 13838 mIntentFilterVerifierComponent.getPackageName(), 13839 MATCH_DEBUG_TRIAGED_MISSING, 13840 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13841 13842 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13843 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13844 mHandler.sendMessage(msg); 13845 13846 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13847 for (int i = 0; i < childCount; i++) { 13848 PackageParser.Package childPkg = pkg.childPackages.get(i); 13849 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13850 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 13851 mHandler.sendMessage(msg); 13852 } 13853 } 13854 13855 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13856 PackageParser.Package pkg) { 13857 int size = pkg.activities.size(); 13858 if (size == 0) { 13859 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13860 "No activity, so no need to verify any IntentFilter!"); 13861 return; 13862 } 13863 13864 final boolean hasDomainURLs = hasDomainURLs(pkg); 13865 if (!hasDomainURLs) { 13866 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13867 "No domain URLs, so no need to verify any IntentFilter!"); 13868 return; 13869 } 13870 13871 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13872 + " if any IntentFilter from the " + size 13873 + " Activities needs verification ..."); 13874 13875 int count = 0; 13876 final String packageName = pkg.packageName; 13877 13878 synchronized (mPackages) { 13879 // If this is a new install and we see that we've already run verification for this 13880 // package, we have nothing to do: it means the state was restored from backup. 13881 if (!replacing) { 13882 IntentFilterVerificationInfo ivi = 13883 mSettings.getIntentFilterVerificationLPr(packageName); 13884 if (ivi != null) { 13885 if (DEBUG_DOMAIN_VERIFICATION) { 13886 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13887 + ivi.getStatusString()); 13888 } 13889 return; 13890 } 13891 } 13892 13893 // If any filters need to be verified, then all need to be. 13894 boolean needToVerify = false; 13895 for (PackageParser.Activity a : pkg.activities) { 13896 for (ActivityIntentInfo filter : a.intents) { 13897 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13898 if (DEBUG_DOMAIN_VERIFICATION) { 13899 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13900 } 13901 needToVerify = true; 13902 break; 13903 } 13904 } 13905 } 13906 13907 if (needToVerify) { 13908 final int verificationId = mIntentFilterVerificationToken++; 13909 for (PackageParser.Activity a : pkg.activities) { 13910 for (ActivityIntentInfo filter : a.intents) { 13911 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13912 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13913 "Verification needed for IntentFilter:" + filter.toString()); 13914 mIntentFilterVerifier.addOneIntentFilterVerification( 13915 verifierUid, userId, verificationId, filter, packageName); 13916 count++; 13917 } 13918 } 13919 } 13920 } 13921 } 13922 13923 if (count > 0) { 13924 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13925 + " IntentFilter verification" + (count > 1 ? "s" : "") 13926 + " for userId:" + userId); 13927 mIntentFilterVerifier.startVerifications(userId); 13928 } else { 13929 if (DEBUG_DOMAIN_VERIFICATION) { 13930 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13931 } 13932 } 13933 } 13934 13935 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13936 final ComponentName cn = filter.activity.getComponentName(); 13937 final String packageName = cn.getPackageName(); 13938 13939 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13940 packageName); 13941 if (ivi == null) { 13942 return true; 13943 } 13944 int status = ivi.getStatus(); 13945 switch (status) { 13946 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13947 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13948 return true; 13949 13950 default: 13951 // Nothing to do 13952 return false; 13953 } 13954 } 13955 13956 private static boolean isMultiArch(ApplicationInfo info) { 13957 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13958 } 13959 13960 private static boolean isExternal(PackageParser.Package pkg) { 13961 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13962 } 13963 13964 private static boolean isExternal(PackageSetting ps) { 13965 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13966 } 13967 13968 private static boolean isEphemeral(PackageParser.Package pkg) { 13969 return pkg.applicationInfo.isEphemeralApp(); 13970 } 13971 13972 private static boolean isEphemeral(PackageSetting ps) { 13973 return ps.pkg != null && isEphemeral(ps.pkg); 13974 } 13975 13976 private static boolean isSystemApp(PackageParser.Package pkg) { 13977 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13978 } 13979 13980 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13981 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13982 } 13983 13984 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13985 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13986 } 13987 13988 private static boolean isSystemApp(PackageSetting ps) { 13989 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13990 } 13991 13992 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13993 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13994 } 13995 13996 private int packageFlagsToInstallFlags(PackageSetting ps) { 13997 int installFlags = 0; 13998 if (isEphemeral(ps)) { 13999 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14000 } 14001 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14002 // This existing package was an external ASEC install when we have 14003 // the external flag without a UUID 14004 installFlags |= PackageManager.INSTALL_EXTERNAL; 14005 } 14006 if (ps.isForwardLocked()) { 14007 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14008 } 14009 return installFlags; 14010 } 14011 14012 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14013 if (isExternal(pkg)) { 14014 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14015 return StorageManager.UUID_PRIMARY_PHYSICAL; 14016 } else { 14017 return pkg.volumeUuid; 14018 } 14019 } else { 14020 return StorageManager.UUID_PRIVATE_INTERNAL; 14021 } 14022 } 14023 14024 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14025 if (isExternal(pkg)) { 14026 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14027 return mSettings.getExternalVersion(); 14028 } else { 14029 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14030 } 14031 } else { 14032 return mSettings.getInternalVersion(); 14033 } 14034 } 14035 14036 private void deleteTempPackageFiles() { 14037 final FilenameFilter filter = new FilenameFilter() { 14038 public boolean accept(File dir, String name) { 14039 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14040 } 14041 }; 14042 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14043 file.delete(); 14044 } 14045 } 14046 14047 @Override 14048 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14049 int flags) { 14050 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14051 flags); 14052 } 14053 14054 @Override 14055 public void deletePackage(final String packageName, 14056 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 14057 mContext.enforceCallingOrSelfPermission( 14058 android.Manifest.permission.DELETE_PACKAGES, null); 14059 Preconditions.checkNotNull(packageName); 14060 Preconditions.checkNotNull(observer); 14061 final int uid = Binder.getCallingUid(); 14062 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 14063 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14064 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14065 mContext.enforceCallingOrSelfPermission( 14066 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14067 "deletePackage for user " + userId); 14068 } 14069 14070 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14071 try { 14072 observer.onPackageDeleted(packageName, 14073 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14074 } catch (RemoteException re) { 14075 } 14076 return; 14077 } 14078 14079 for (int currentUserId : users) { 14080 if (getBlockUninstallForUser(packageName, currentUserId)) { 14081 try { 14082 observer.onPackageDeleted(packageName, 14083 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14084 } catch (RemoteException re) { 14085 } 14086 return; 14087 } 14088 } 14089 14090 if (DEBUG_REMOVE) { 14091 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 14092 } 14093 // Queue up an async operation since the package deletion may take a little while. 14094 mHandler.post(new Runnable() { 14095 public void run() { 14096 mHandler.removeCallbacks(this); 14097 final int returnCode = deletePackageX(packageName, userId, flags); 14098 try { 14099 observer.onPackageDeleted(packageName, returnCode, null); 14100 } catch (RemoteException e) { 14101 Log.i(TAG, "Observer no longer exists."); 14102 } //end catch 14103 } //end run 14104 }); 14105 } 14106 14107 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14108 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14109 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14110 try { 14111 if (dpm != null) { 14112 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14113 /* callingUserOnly =*/ false); 14114 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14115 : deviceOwnerComponentName.getPackageName(); 14116 // Does the package contains the device owner? 14117 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14118 // this check is probably not needed, since DO should be registered as a device 14119 // admin on some user too. (Original bug for this: b/17657954) 14120 if (packageName.equals(deviceOwnerPackageName)) { 14121 return true; 14122 } 14123 // Does it contain a device admin for any user? 14124 int[] users; 14125 if (userId == UserHandle.USER_ALL) { 14126 users = sUserManager.getUserIds(); 14127 } else { 14128 users = new int[]{userId}; 14129 } 14130 for (int i = 0; i < users.length; ++i) { 14131 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14132 return true; 14133 } 14134 } 14135 } 14136 } catch (RemoteException e) { 14137 } 14138 return false; 14139 } 14140 14141 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14142 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14143 } 14144 14145 /** 14146 * This method is an internal method that could be get invoked either 14147 * to delete an installed package or to clean up a failed installation. 14148 * After deleting an installed package, a broadcast is sent to notify any 14149 * listeners that the package has been installed. For cleaning up a failed 14150 * installation, the broadcast is not necessary since the package's 14151 * installation wouldn't have sent the initial broadcast either 14152 * The key steps in deleting a package are 14153 * deleting the package information in internal structures like mPackages, 14154 * deleting the packages base directories through installd 14155 * updating mSettings to reflect current status 14156 * persisting settings for later use 14157 * sending a broadcast if necessary 14158 */ 14159 private int deletePackageX(String packageName, int userId, int flags) { 14160 final PackageRemovedInfo info = new PackageRemovedInfo(); 14161 final boolean res; 14162 14163 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 14164 ? UserHandle.ALL : new UserHandle(userId); 14165 14166 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14167 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14168 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14169 } 14170 14171 PackageSetting uninstalledPs = null; 14172 14173 // for the uninstall-updates case and restricted profiles, remember the per- 14174 // user handle installed state 14175 int[] allUsers; 14176 synchronized (mPackages) { 14177 uninstalledPs = mSettings.mPackages.get(packageName); 14178 if (uninstalledPs == null) { 14179 Slog.w(TAG, "Not removing non-existent package " + packageName); 14180 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14181 } 14182 allUsers = sUserManager.getUserIds(); 14183 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14184 } 14185 14186 synchronized (mInstallLock) { 14187 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14188 res = deletePackageLI(packageName, removeForUser, true, allUsers, 14189 flags | REMOVE_CHATTY, info, true, null); 14190 synchronized (mPackages) { 14191 if (res) { 14192 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14193 } 14194 } 14195 } 14196 14197 if (res) { 14198 info.sendPackageRemovedBroadcasts(); 14199 info.sendSystemPackageUpdatedBroadcasts(); 14200 info.sendSystemPackageAppearedBroadcasts(); 14201 } 14202 // Force a gc here. 14203 Runtime.getRuntime().gc(); 14204 // Delete the resources here after sending the broadcast to let 14205 // other processes clean up before deleting resources. 14206 if (info.args != null) { 14207 synchronized (mInstallLock) { 14208 info.args.doPostDeleteLI(true); 14209 } 14210 } 14211 14212 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14213 } 14214 14215 class PackageRemovedInfo { 14216 String removedPackage; 14217 int uid = -1; 14218 int removedAppId = -1; 14219 int[] origUsers; 14220 int[] removedUsers = null; 14221 boolean isRemovedPackageSystemUpdate = false; 14222 boolean isUpdate; 14223 boolean dataRemoved; 14224 boolean removedForAllUsers; 14225 // Clean up resources deleted packages. 14226 InstallArgs args = null; 14227 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14228 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14229 14230 void sendPackageRemovedBroadcasts() { 14231 sendPackageRemovedBroadcastInternal(); 14232 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14233 for (int i = 0; i < childCount; i++) { 14234 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14235 childInfo.sendPackageRemovedBroadcastInternal(); 14236 } 14237 } 14238 14239 void sendSystemPackageUpdatedBroadcasts() { 14240 if (isRemovedPackageSystemUpdate) { 14241 sendSystemPackageUpdatedBroadcastsInternal(); 14242 final int childCount = (removedChildPackages != null) 14243 ? removedChildPackages.size() : 0; 14244 for (int i = 0; i < childCount; i++) { 14245 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14246 if (childInfo.isRemovedPackageSystemUpdate) { 14247 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 14248 } 14249 } 14250 } 14251 } 14252 14253 void sendSystemPackageAppearedBroadcasts() { 14254 final int packageCount = (appearedChildPackages != null) 14255 ? appearedChildPackages.size() : 0; 14256 for (int i = 0; i < packageCount; i++) { 14257 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 14258 for (int userId : installedInfo.newUsers) { 14259 sendPackageAddedForUser(installedInfo.name, true, 14260 UserHandle.getAppId(installedInfo.uid), userId); 14261 } 14262 } 14263 } 14264 14265 private void sendSystemPackageUpdatedBroadcastsInternal() { 14266 Bundle extras = new Bundle(2); 14267 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14268 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14269 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 14270 extras, 0, null, null, null); 14271 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 14272 extras, 0, null, null, null); 14273 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14274 null, 0, removedPackage, null, null); 14275 } 14276 14277 private void sendPackageRemovedBroadcastInternal() { 14278 Bundle extras = new Bundle(2); 14279 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14280 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 14281 if (isUpdate || isRemovedPackageSystemUpdate) { 14282 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14283 } 14284 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14285 if (removedPackage != null) { 14286 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14287 extras, 0, null, null, removedUsers); 14288 if (dataRemoved && !isRemovedPackageSystemUpdate) { 14289 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 14290 removedPackage, extras, 0, null, null, removedUsers); 14291 } 14292 } 14293 if (removedAppId >= 0) { 14294 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 14295 removedUsers); 14296 } 14297 } 14298 } 14299 14300 /* 14301 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 14302 * flag is not set, the data directory is removed as well. 14303 * make sure this flag is set for partially installed apps. If not its meaningless to 14304 * delete a partially installed application. 14305 */ 14306 private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, 14307 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 14308 String packageName = ps.name; 14309 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 14310 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 14311 // Retrieve object to delete permissions for shared user later on 14312 final PackageSetting deletedPs; 14313 // reader 14314 synchronized (mPackages) { 14315 deletedPs = mSettings.mPackages.get(packageName); 14316 if (outInfo != null) { 14317 outInfo.removedPackage = packageName; 14318 outInfo.removedUsers = deletedPs != null 14319 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 14320 : null; 14321 } 14322 } 14323 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14324 removeDataDirsLI(ps.volumeUuid, packageName); 14325 if (outInfo != null) { 14326 outInfo.dataRemoved = true; 14327 } 14328 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 14329 } 14330 // writer 14331 synchronized (mPackages) { 14332 if (deletedPs != null) { 14333 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14334 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 14335 clearDefaultBrowserIfNeeded(packageName); 14336 if (outInfo != null) { 14337 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 14338 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 14339 } 14340 updatePermissionsLPw(deletedPs.name, null, 0); 14341 if (deletedPs.sharedUser != null) { 14342 // Remove permissions associated with package. Since runtime 14343 // permissions are per user we have to kill the removed package 14344 // or packages running under the shared user of the removed 14345 // package if revoking the permissions requested only by the removed 14346 // package is successful and this causes a change in gids. 14347 for (int userId : UserManagerService.getInstance().getUserIds()) { 14348 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 14349 userId); 14350 if (userIdToKill == UserHandle.USER_ALL 14351 || userIdToKill >= UserHandle.USER_SYSTEM) { 14352 // If gids changed for this user, kill all affected packages. 14353 mHandler.post(new Runnable() { 14354 @Override 14355 public void run() { 14356 // This has to happen with no lock held. 14357 killApplication(deletedPs.name, deletedPs.appId, 14358 KILL_APP_REASON_GIDS_CHANGED); 14359 } 14360 }); 14361 break; 14362 } 14363 } 14364 } 14365 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 14366 } 14367 // make sure to preserve per-user disabled state if this removal was just 14368 // a downgrade of a system app to the factory package 14369 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 14370 if (DEBUG_REMOVE) { 14371 Slog.d(TAG, "Propagating install state across downgrade"); 14372 } 14373 for (int userId : allUserHandles) { 14374 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14375 if (DEBUG_REMOVE) { 14376 Slog.d(TAG, " user " + userId + " => " + installed); 14377 } 14378 ps.setInstalled(installed, userId); 14379 } 14380 } 14381 } 14382 // can downgrade to reader 14383 if (writeSettings) { 14384 // Save settings now 14385 mSettings.writeLPr(); 14386 } 14387 } 14388 if (outInfo != null) { 14389 // A user ID was deleted here. Go through all users and remove it 14390 // from KeyStore. 14391 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 14392 } 14393 } 14394 14395 static boolean locationIsPrivileged(File path) { 14396 try { 14397 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 14398 .getCanonicalPath(); 14399 return path.getCanonicalPath().startsWith(privilegedAppDir); 14400 } catch (IOException e) { 14401 Slog.e(TAG, "Unable to access code path " + path); 14402 } 14403 return false; 14404 } 14405 14406 /* 14407 * Tries to delete system package. 14408 */ 14409 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 14410 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 14411 boolean writeSettings) { 14412 if (deletedPkg.parentPackage != null) { 14413 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 14414 return false; 14415 } 14416 14417 final boolean applyUserRestrictions 14418 = (allUserHandles != null) && (outInfo.origUsers != null); 14419 final PackageSetting disabledPs; 14420 // Confirm if the system package has been updated 14421 // An updated system app can be deleted. This will also have to restore 14422 // the system pkg from system partition 14423 // reader 14424 synchronized (mPackages) { 14425 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPkg.packageName); 14426 } 14427 14428 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 14429 + " disabledPs=" + disabledPs); 14430 14431 if (disabledPs == null) { 14432 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 14433 return false; 14434 } else if (DEBUG_REMOVE) { 14435 Slog.d(TAG, "Deleting system pkg from data partition"); 14436 } 14437 14438 if (DEBUG_REMOVE) { 14439 if (applyUserRestrictions) { 14440 Slog.d(TAG, "Remembering install states:"); 14441 for (int userId : allUserHandles) { 14442 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 14443 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 14444 } 14445 } 14446 } 14447 14448 // Delete the updated package 14449 outInfo.isRemovedPackageSystemUpdate = true; 14450 if (outInfo.removedChildPackages != null) { 14451 final int childCount = (deletedPkg.childPackages != null) 14452 ? deletedPkg.childPackages.size() : 0; 14453 for (int i = 0; i < childCount; i++) { 14454 String childPackageName = deletedPkg.childPackages.get(i).packageName; 14455 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 14456 .contains(childPackageName)) { 14457 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14458 childPackageName); 14459 if (childInfo != null) { 14460 childInfo.isRemovedPackageSystemUpdate = true; 14461 } 14462 } 14463 } 14464 } 14465 14466 if (disabledPs.versionCode < deletedPs.versionCode) { 14467 // Delete data for downgrades 14468 flags &= ~PackageManager.DELETE_KEEP_DATA; 14469 } else { 14470 // Preserve data by setting flag 14471 flags |= PackageManager.DELETE_KEEP_DATA; 14472 } 14473 14474 boolean ret = deleteInstalledPackageLI(deletedPkg, true, flags, allUserHandles, 14475 outInfo, writeSettings, disabledPs.pkg); 14476 if (!ret) { 14477 return false; 14478 } 14479 14480 // writer 14481 synchronized (mPackages) { 14482 // Reinstate the old system package 14483 enableSystemPackageLPw(disabledPs.pkg); 14484 // Remove any native libraries from the upgraded package. 14485 removeNativeBinariesLI(deletedPkg); 14486 } 14487 14488 // Install the system package 14489 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 14490 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 14491 if (locationIsPrivileged(disabledPs.codePath)) { 14492 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 14493 } 14494 14495 final PackageParser.Package newPkg; 14496 try { 14497 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 14498 } catch (PackageManagerException e) { 14499 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 14500 + e.getMessage()); 14501 return false; 14502 } 14503 14504 prepareAppDataAfterInstall(newPkg); 14505 14506 // writer 14507 synchronized (mPackages) { 14508 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 14509 14510 // Propagate the permissions state as we do not want to drop on the floor 14511 // runtime permissions. The update permissions method below will take 14512 // care of removing obsolete permissions and grant install permissions. 14513 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 14514 updatePermissionsLPw(newPkg.packageName, newPkg, 14515 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 14516 14517 if (applyUserRestrictions) { 14518 if (DEBUG_REMOVE) { 14519 Slog.d(TAG, "Propagating install state across reinstall"); 14520 } 14521 for (int userId : allUserHandles) { 14522 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14523 if (DEBUG_REMOVE) { 14524 Slog.d(TAG, " user " + userId + " => " + installed); 14525 } 14526 ps.setInstalled(installed, userId); 14527 14528 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 14529 } 14530 // Regardless of writeSettings we need to ensure that this restriction 14531 // state propagation is persisted 14532 mSettings.writeAllUsersPackageRestrictionsLPr(); 14533 } 14534 // can downgrade to reader here 14535 if (writeSettings) { 14536 mSettings.writeLPr(); 14537 } 14538 } 14539 return true; 14540 } 14541 14542 private boolean deleteInstalledPackageLI(PackageParser.Package pkg, 14543 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 14544 PackageRemovedInfo outInfo, boolean writeSettings, 14545 PackageParser.Package replacingPackage) { 14546 PackageSetting ps = null; 14547 14548 synchronized (mPackages) { 14549 pkg = mPackages.get(pkg.packageName); 14550 if (pkg == null) { 14551 return false; 14552 } 14553 14554 ps = mSettings.mPackages.get(pkg.packageName); 14555 if (ps == null) { 14556 return false; 14557 } 14558 14559 if (outInfo != null) { 14560 outInfo.uid = ps.appId; 14561 } 14562 14563 if (outInfo != null && outInfo.removedChildPackages != null) { 14564 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14565 for (int i = 0; i < childCount; i++) { 14566 String childPackageName = ps.childPackageNames.get(i); 14567 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 14568 if (childPs == null) { 14569 return false; 14570 } 14571 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14572 childPackageName); 14573 if (childInfo != null) { 14574 childInfo.uid = childPs.appId; 14575 } 14576 } 14577 } 14578 } 14579 14580 // Delete package data from internal structures and also remove data if flag is set 14581 removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings); 14582 14583 // Delete the child packages data 14584 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14585 for (int i = 0; i < childCount; i++) { 14586 PackageSetting childPs; 14587 synchronized (mPackages) { 14588 childPs = mSettings.peekPackageLPr(pkg.childPackages.get(i).packageName); 14589 } 14590 if (childPs != null) { 14591 PackageRemovedInfo childOutInfo = (outInfo != null 14592 && outInfo.removedChildPackages != null) 14593 ? outInfo.removedChildPackages.get(childPs.name) : null; 14594 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 14595 && (replacingPackage != null 14596 && !replacingPackage.hasChildPackage(childPs.name)) 14597 ? flags & ~DELETE_KEEP_DATA : flags; 14598 removePackageDataLI(childPs, allUserHandles, childOutInfo, 14599 deleteFlags, writeSettings); 14600 } 14601 } 14602 14603 // Delete application code and resources only for parent packages 14604 if (ps.pkg.parentPackage == null) { 14605 if (deleteCodeAndResources && (outInfo != null)) { 14606 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 14607 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 14608 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 14609 } 14610 } 14611 14612 return true; 14613 } 14614 14615 @Override 14616 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 14617 int userId) { 14618 mContext.enforceCallingOrSelfPermission( 14619 android.Manifest.permission.DELETE_PACKAGES, null); 14620 synchronized (mPackages) { 14621 PackageSetting ps = mSettings.mPackages.get(packageName); 14622 if (ps == null) { 14623 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 14624 return false; 14625 } 14626 if (!ps.getInstalled(userId)) { 14627 // Can't block uninstall for an app that is not installed or enabled. 14628 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 14629 return false; 14630 } 14631 ps.setBlockUninstall(blockUninstall, userId); 14632 mSettings.writePackageRestrictionsLPr(userId); 14633 } 14634 return true; 14635 } 14636 14637 @Override 14638 public boolean getBlockUninstallForUser(String packageName, int userId) { 14639 synchronized (mPackages) { 14640 PackageSetting ps = mSettings.mPackages.get(packageName); 14641 if (ps == null) { 14642 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 14643 return false; 14644 } 14645 return ps.getBlockUninstall(userId); 14646 } 14647 } 14648 14649 @Override 14650 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 14651 int callingUid = Binder.getCallingUid(); 14652 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 14653 throw new SecurityException( 14654 "setRequiredForSystemUser can only be run by the system or root"); 14655 } 14656 synchronized (mPackages) { 14657 PackageSetting ps = mSettings.mPackages.get(packageName); 14658 if (ps == null) { 14659 Log.w(TAG, "Package doesn't exist: " + packageName); 14660 return false; 14661 } 14662 if (systemUserApp) { 14663 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14664 } else { 14665 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14666 } 14667 mSettings.writeLPr(); 14668 } 14669 return true; 14670 } 14671 14672 /* 14673 * This method handles package deletion in general 14674 */ 14675 private boolean deletePackageLI(String packageName, UserHandle user, 14676 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 14677 PackageRemovedInfo outInfo, boolean writeSettings, 14678 PackageParser.Package replacingPackage) { 14679 if (packageName == null) { 14680 Slog.w(TAG, "Attempt to delete null packageName."); 14681 return false; 14682 } 14683 14684 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 14685 14686 PackageSetting ps; 14687 14688 synchronized (mPackages) { 14689 ps = mSettings.mPackages.get(packageName); 14690 if (ps == null) { 14691 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14692 return false; 14693 } 14694 14695 if (ps.pkg.parentPackage != null && (!isSystemApp(ps) 14696 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 14697 if (DEBUG_REMOVE) { 14698 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 14699 + ((user == null) ? UserHandle.USER_ALL : user)); 14700 } 14701 final int removedUserId = (user != null) ? user.getIdentifier() 14702 : UserHandle.USER_ALL; 14703 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 14704 return false; 14705 } 14706 markPackageUninstalledForUserLPw(ps, user); 14707 scheduleWritePackageRestrictionsLocked(user); 14708 return true; 14709 } 14710 } 14711 14712 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 14713 && user.getIdentifier() != UserHandle.USER_ALL)) { 14714 // The caller is asking that the package only be deleted for a single 14715 // user. To do this, we just mark its uninstalled state and delete 14716 // its data. If this is a system app, we only allow this to happen if 14717 // they have set the special DELETE_SYSTEM_APP which requests different 14718 // semantics than normal for uninstalling system apps. 14719 markPackageUninstalledForUserLPw(ps, user); 14720 14721 if (!isSystemApp(ps)) { 14722 // Do not uninstall the APK if an app should be cached 14723 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 14724 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 14725 // Other user still have this package installed, so all 14726 // we need to do is clear this user's data and save that 14727 // it is uninstalled. 14728 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 14729 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14730 return false; 14731 } 14732 scheduleWritePackageRestrictionsLocked(user); 14733 return true; 14734 } else { 14735 // We need to set it back to 'installed' so the uninstall 14736 // broadcasts will be sent correctly. 14737 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 14738 ps.setInstalled(true, user.getIdentifier()); 14739 } 14740 } else { 14741 // This is a system app, so we assume that the 14742 // other users still have this package installed, so all 14743 // we need to do is clear this user's data and save that 14744 // it is uninstalled. 14745 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 14746 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14747 return false; 14748 } 14749 scheduleWritePackageRestrictionsLocked(user); 14750 return true; 14751 } 14752 } 14753 14754 // If we are deleting a composite package for all users, keep track 14755 // of result for each child. 14756 if (ps.childPackageNames != null && outInfo != null) { 14757 synchronized (mPackages) { 14758 final int childCount = ps.childPackageNames.size(); 14759 outInfo.removedChildPackages = new ArrayMap<>(childCount); 14760 for (int i = 0; i < childCount; i++) { 14761 String childPackageName = ps.childPackageNames.get(i); 14762 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 14763 childInfo.removedPackage = childPackageName; 14764 outInfo.removedChildPackages.put(childPackageName, childInfo); 14765 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 14766 if (childPs != null) { 14767 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 14768 } 14769 } 14770 } 14771 } 14772 14773 boolean ret = false; 14774 if (isSystemApp(ps)) { 14775 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 14776 // When an updated system application is deleted we delete the existing resources 14777 // as well and fall back to existing code in system partition 14778 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 14779 } else { 14780 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 14781 // Kill application pre-emptively especially for apps on sd. 14782 killApplication(packageName, ps.appId, "uninstall pkg"); 14783 ret = deleteInstalledPackageLI(ps.pkg, deleteCodeAndResources, flags, allUserHandles, 14784 outInfo, writeSettings, replacingPackage); 14785 } 14786 14787 // Take a note whether we deleted the package for all users 14788 if (outInfo != null) { 14789 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14790 if (outInfo.removedChildPackages != null) { 14791 synchronized (mPackages) { 14792 final int childCount = outInfo.removedChildPackages.size(); 14793 for (int i = 0; i < childCount; i++) { 14794 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 14795 if (childInfo != null) { 14796 childInfo.removedForAllUsers = mPackages.get( 14797 childInfo.removedPackage) == null; 14798 } 14799 } 14800 } 14801 } 14802 // If we uninstalled an update to a system app there may be some 14803 // child packages that appeared as they are declared in the system 14804 // app but were not declared in the update. 14805 if (isSystemApp(ps)) { 14806 synchronized (mPackages) { 14807 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 14808 final int childCount = (updatedPs.childPackageNames != null) 14809 ? updatedPs.childPackageNames.size() : 0; 14810 for (int i = 0; i < childCount; i++) { 14811 String childPackageName = updatedPs.childPackageNames.get(i); 14812 if (outInfo.removedChildPackages == null 14813 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 14814 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 14815 if (childPs == null) { 14816 continue; 14817 } 14818 PackageInstalledInfo installRes = new PackageInstalledInfo(); 14819 installRes.name = childPackageName; 14820 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 14821 installRes.pkg = mPackages.get(childPackageName); 14822 installRes.uid = childPs.pkg.applicationInfo.uid; 14823 if (outInfo.appearedChildPackages == null) { 14824 outInfo.appearedChildPackages = new ArrayMap<>(); 14825 } 14826 outInfo.appearedChildPackages.put(childPackageName, installRes); 14827 } 14828 } 14829 } 14830 } 14831 } 14832 14833 return ret; 14834 } 14835 14836 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 14837 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 14838 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 14839 for (int nextUserId : userIds) { 14840 if (DEBUG_REMOVE) { 14841 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 14842 } 14843 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 14844 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 14845 false /*hidden*/, false /*suspended*/, null, null, null, 14846 false /*blockUninstall*/, 14847 ps.readUserState(nextUserId).domainVerificationStatus, 0); 14848 } 14849 } 14850 14851 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 14852 PackageRemovedInfo outInfo) { 14853 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 14854 : new int[] {userId}; 14855 for (int nextUserId : userIds) { 14856 if (DEBUG_REMOVE) { 14857 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 14858 + nextUserId); 14859 } 14860 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 14861 try { 14862 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 14863 } catch (InstallerException e) { 14864 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 14865 return false; 14866 } 14867 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 14868 schedulePackageCleaning(ps.name, nextUserId, false); 14869 synchronized (mPackages) { 14870 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 14871 scheduleWritePackageRestrictionsLocked(nextUserId); 14872 } 14873 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 14874 } 14875 } 14876 14877 if (outInfo != null) { 14878 outInfo.removedPackage = ps.name; 14879 outInfo.removedAppId = ps.appId; 14880 outInfo.removedUsers = userIds; 14881 } 14882 14883 return true; 14884 } 14885 14886 private final class ClearStorageConnection implements ServiceConnection { 14887 IMediaContainerService mContainerService; 14888 14889 @Override 14890 public void onServiceConnected(ComponentName name, IBinder service) { 14891 synchronized (this) { 14892 mContainerService = IMediaContainerService.Stub.asInterface(service); 14893 notifyAll(); 14894 } 14895 } 14896 14897 @Override 14898 public void onServiceDisconnected(ComponentName name) { 14899 } 14900 } 14901 14902 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 14903 final boolean mounted; 14904 if (Environment.isExternalStorageEmulated()) { 14905 mounted = true; 14906 } else { 14907 final String status = Environment.getExternalStorageState(); 14908 14909 mounted = status.equals(Environment.MEDIA_MOUNTED) 14910 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 14911 } 14912 14913 if (!mounted) { 14914 return; 14915 } 14916 14917 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 14918 int[] users; 14919 if (userId == UserHandle.USER_ALL) { 14920 users = sUserManager.getUserIds(); 14921 } else { 14922 users = new int[] { userId }; 14923 } 14924 final ClearStorageConnection conn = new ClearStorageConnection(); 14925 if (mContext.bindServiceAsUser( 14926 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 14927 try { 14928 for (int curUser : users) { 14929 long timeout = SystemClock.uptimeMillis() + 5000; 14930 synchronized (conn) { 14931 long now = SystemClock.uptimeMillis(); 14932 while (conn.mContainerService == null && now < timeout) { 14933 try { 14934 conn.wait(timeout - now); 14935 } catch (InterruptedException e) { 14936 } 14937 } 14938 } 14939 if (conn.mContainerService == null) { 14940 return; 14941 } 14942 14943 final UserEnvironment userEnv = new UserEnvironment(curUser); 14944 clearDirectory(conn.mContainerService, 14945 userEnv.buildExternalStorageAppCacheDirs(packageName)); 14946 if (allData) { 14947 clearDirectory(conn.mContainerService, 14948 userEnv.buildExternalStorageAppDataDirs(packageName)); 14949 clearDirectory(conn.mContainerService, 14950 userEnv.buildExternalStorageAppMediaDirs(packageName)); 14951 } 14952 } 14953 } finally { 14954 mContext.unbindService(conn); 14955 } 14956 } 14957 } 14958 14959 @Override 14960 public void clearApplicationUserData(final String packageName, 14961 final IPackageDataObserver observer, final int userId) { 14962 mContext.enforceCallingOrSelfPermission( 14963 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 14964 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 14965 // Queue up an async operation since the package deletion may take a little while. 14966 mHandler.post(new Runnable() { 14967 public void run() { 14968 mHandler.removeCallbacks(this); 14969 final boolean succeeded; 14970 synchronized (mInstallLock) { 14971 succeeded = clearApplicationUserDataLI(packageName, userId); 14972 } 14973 clearExternalStorageDataSync(packageName, userId, true); 14974 if (succeeded) { 14975 // invoke DeviceStorageMonitor's update method to clear any notifications 14976 DeviceStorageMonitorInternal 14977 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14978 if (dsm != null) { 14979 dsm.checkMemory(); 14980 } 14981 } 14982 if(observer != null) { 14983 try { 14984 observer.onRemoveCompleted(packageName, succeeded); 14985 } catch (RemoteException e) { 14986 Log.i(TAG, "Observer no longer exists."); 14987 } 14988 } //end if observer 14989 } //end run 14990 }); 14991 } 14992 14993 private boolean clearApplicationUserDataLI(String packageName, int userId) { 14994 if (packageName == null) { 14995 Slog.w(TAG, "Attempt to delete null packageName."); 14996 return false; 14997 } 14998 14999 // Try finding details about the requested package 15000 PackageParser.Package pkg; 15001 synchronized (mPackages) { 15002 pkg = mPackages.get(packageName); 15003 if (pkg == null) { 15004 final PackageSetting ps = mSettings.mPackages.get(packageName); 15005 if (ps != null) { 15006 pkg = ps.pkg; 15007 } 15008 } 15009 15010 if (pkg == null) { 15011 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15012 return false; 15013 } 15014 15015 PackageSetting ps = (PackageSetting) pkg.mExtras; 15016 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15017 } 15018 15019 // Always delete data directories for package, even if we found no other 15020 // record of app. This helps users recover from UID mismatches without 15021 // resorting to a full data wipe. 15022 // TODO: triage flags as part of 26466827 15023 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15024 try { 15025 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 15026 } catch (InstallerException e) { 15027 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 15028 return false; 15029 } 15030 15031 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15032 removeKeystoreDataIfNeeded(userId, appId); 15033 15034 // Create a native library symlink only if we have native libraries 15035 // and if the native libraries are 32 bit libraries. We do not provide 15036 // this symlink for 64 bit libraries. 15037 if (pkg.applicationInfo.primaryCpuAbi != null && 15038 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 15039 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 15040 try { 15041 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 15042 nativeLibPath, userId); 15043 } catch (InstallerException e) { 15044 Slog.w(TAG, "Failed linking native library dir", e); 15045 return false; 15046 } 15047 } 15048 15049 return true; 15050 } 15051 15052 /** 15053 * Reverts user permission state changes (permissions and flags) in 15054 * all packages for a given user. 15055 * 15056 * @param userId The device user for which to do a reset. 15057 */ 15058 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15059 final int packageCount = mPackages.size(); 15060 for (int i = 0; i < packageCount; i++) { 15061 PackageParser.Package pkg = mPackages.valueAt(i); 15062 PackageSetting ps = (PackageSetting) pkg.mExtras; 15063 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15064 } 15065 } 15066 15067 /** 15068 * Reverts user permission state changes (permissions and flags). 15069 * 15070 * @param ps The package for which to reset. 15071 * @param userId The device user for which to do a reset. 15072 */ 15073 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15074 final PackageSetting ps, final int userId) { 15075 if (ps.pkg == null) { 15076 return; 15077 } 15078 15079 // These are flags that can change base on user actions. 15080 final int userSettableMask = FLAG_PERMISSION_USER_SET 15081 | FLAG_PERMISSION_USER_FIXED 15082 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15083 | FLAG_PERMISSION_REVIEW_REQUIRED; 15084 15085 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15086 | FLAG_PERMISSION_POLICY_FIXED; 15087 15088 boolean writeInstallPermissions = false; 15089 boolean writeRuntimePermissions = false; 15090 15091 final int permissionCount = ps.pkg.requestedPermissions.size(); 15092 for (int i = 0; i < permissionCount; i++) { 15093 String permission = ps.pkg.requestedPermissions.get(i); 15094 15095 BasePermission bp = mSettings.mPermissions.get(permission); 15096 if (bp == null) { 15097 continue; 15098 } 15099 15100 // If shared user we just reset the state to which only this app contributed. 15101 if (ps.sharedUser != null) { 15102 boolean used = false; 15103 final int packageCount = ps.sharedUser.packages.size(); 15104 for (int j = 0; j < packageCount; j++) { 15105 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15106 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15107 && pkg.pkg.requestedPermissions.contains(permission)) { 15108 used = true; 15109 break; 15110 } 15111 } 15112 if (used) { 15113 continue; 15114 } 15115 } 15116 15117 PermissionsState permissionsState = ps.getPermissionsState(); 15118 15119 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15120 15121 // Always clear the user settable flags. 15122 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15123 bp.name) != null; 15124 // If permission review is enabled and this is a legacy app, mark the 15125 // permission as requiring a review as this is the initial state. 15126 int flags = 0; 15127 if (Build.PERMISSIONS_REVIEW_REQUIRED 15128 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15129 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15130 } 15131 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15132 if (hasInstallState) { 15133 writeInstallPermissions = true; 15134 } else { 15135 writeRuntimePermissions = true; 15136 } 15137 } 15138 15139 // Below is only runtime permission handling. 15140 if (!bp.isRuntime()) { 15141 continue; 15142 } 15143 15144 // Never clobber system or policy. 15145 if ((oldFlags & policyOrSystemFlags) != 0) { 15146 continue; 15147 } 15148 15149 // If this permission was granted by default, make sure it is. 15150 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15151 if (permissionsState.grantRuntimePermission(bp, userId) 15152 != PERMISSION_OPERATION_FAILURE) { 15153 writeRuntimePermissions = true; 15154 } 15155 // If permission review is enabled the permissions for a legacy apps 15156 // are represented as constantly granted runtime ones, so don't revoke. 15157 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15158 // Otherwise, reset the permission. 15159 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15160 switch (revokeResult) { 15161 case PERMISSION_OPERATION_SUCCESS: { 15162 writeRuntimePermissions = true; 15163 } break; 15164 15165 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15166 writeRuntimePermissions = true; 15167 final int appId = ps.appId; 15168 mHandler.post(new Runnable() { 15169 @Override 15170 public void run() { 15171 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 15172 } 15173 }); 15174 } break; 15175 } 15176 } 15177 } 15178 15179 // Synchronously write as we are taking permissions away. 15180 if (writeRuntimePermissions) { 15181 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15182 } 15183 15184 // Synchronously write as we are taking permissions away. 15185 if (writeInstallPermissions) { 15186 mSettings.writeLPr(); 15187 } 15188 } 15189 15190 /** 15191 * Remove entries from the keystore daemon. Will only remove it if the 15192 * {@code appId} is valid. 15193 */ 15194 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15195 if (appId < 0) { 15196 return; 15197 } 15198 15199 final KeyStore keyStore = KeyStore.getInstance(); 15200 if (keyStore != null) { 15201 if (userId == UserHandle.USER_ALL) { 15202 for (final int individual : sUserManager.getUserIds()) { 15203 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15204 } 15205 } else { 15206 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15207 } 15208 } else { 15209 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15210 } 15211 } 15212 15213 @Override 15214 public void deleteApplicationCacheFiles(final String packageName, 15215 final IPackageDataObserver observer) { 15216 mContext.enforceCallingOrSelfPermission( 15217 android.Manifest.permission.DELETE_CACHE_FILES, null); 15218 // Queue up an async operation since the package deletion may take a little while. 15219 final int userId = UserHandle.getCallingUserId(); 15220 mHandler.post(new Runnable() { 15221 public void run() { 15222 mHandler.removeCallbacks(this); 15223 final boolean succeded; 15224 synchronized (mInstallLock) { 15225 succeded = deleteApplicationCacheFilesLI(packageName, userId); 15226 } 15227 clearExternalStorageDataSync(packageName, userId, false); 15228 if (observer != null) { 15229 try { 15230 observer.onRemoveCompleted(packageName, succeded); 15231 } catch (RemoteException e) { 15232 Log.i(TAG, "Observer no longer exists."); 15233 } 15234 } //end if observer 15235 } //end run 15236 }); 15237 } 15238 15239 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 15240 if (packageName == null) { 15241 Slog.w(TAG, "Attempt to delete null packageName."); 15242 return false; 15243 } 15244 PackageParser.Package p; 15245 synchronized (mPackages) { 15246 p = mPackages.get(packageName); 15247 } 15248 if (p == null) { 15249 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15250 return false; 15251 } 15252 final ApplicationInfo applicationInfo = p.applicationInfo; 15253 if (applicationInfo == null) { 15254 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15255 return false; 15256 } 15257 // TODO: triage flags as part of 26466827 15258 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15259 try { 15260 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 15261 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 15262 } catch (InstallerException e) { 15263 Slog.w(TAG, "Couldn't remove cache files for package " 15264 + packageName + " u" + userId, e); 15265 return false; 15266 } 15267 return true; 15268 } 15269 15270 @Override 15271 public void getPackageSizeInfo(final String packageName, int userHandle, 15272 final IPackageStatsObserver observer) { 15273 mContext.enforceCallingOrSelfPermission( 15274 android.Manifest.permission.GET_PACKAGE_SIZE, null); 15275 if (packageName == null) { 15276 throw new IllegalArgumentException("Attempt to get size of null packageName"); 15277 } 15278 15279 PackageStats stats = new PackageStats(packageName, userHandle); 15280 15281 /* 15282 * Queue up an async operation since the package measurement may take a 15283 * little while. 15284 */ 15285 Message msg = mHandler.obtainMessage(INIT_COPY); 15286 msg.obj = new MeasureParams(stats, observer); 15287 mHandler.sendMessage(msg); 15288 } 15289 15290 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 15291 PackageStats pStats) { 15292 if (packageName == null) { 15293 Slog.w(TAG, "Attempt to get size of null packageName."); 15294 return false; 15295 } 15296 PackageParser.Package p; 15297 boolean dataOnly = false; 15298 String libDirRoot = null; 15299 String asecPath = null; 15300 PackageSetting ps = null; 15301 synchronized (mPackages) { 15302 p = mPackages.get(packageName); 15303 ps = mSettings.mPackages.get(packageName); 15304 if(p == null) { 15305 dataOnly = true; 15306 if((ps == null) || (ps.pkg == null)) { 15307 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15308 return false; 15309 } 15310 p = ps.pkg; 15311 } 15312 if (ps != null) { 15313 libDirRoot = ps.legacyNativeLibraryPathString; 15314 } 15315 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 15316 final long token = Binder.clearCallingIdentity(); 15317 try { 15318 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 15319 if (secureContainerId != null) { 15320 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 15321 } 15322 } finally { 15323 Binder.restoreCallingIdentity(token); 15324 } 15325 } 15326 } 15327 String publicSrcDir = null; 15328 if(!dataOnly) { 15329 final ApplicationInfo applicationInfo = p.applicationInfo; 15330 if (applicationInfo == null) { 15331 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15332 return false; 15333 } 15334 if (p.isForwardLocked()) { 15335 publicSrcDir = applicationInfo.getBaseResourcePath(); 15336 } 15337 } 15338 // TODO: extend to measure size of split APKs 15339 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 15340 // not just the first level. 15341 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 15342 // just the primary. 15343 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 15344 15345 String apkPath; 15346 File packageDir = new File(p.codePath); 15347 15348 if (packageDir.isDirectory() && p.canHaveOatDir()) { 15349 apkPath = packageDir.getAbsolutePath(); 15350 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 15351 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 15352 libDirRoot = null; 15353 } 15354 } else { 15355 apkPath = p.baseCodePath; 15356 } 15357 15358 // TODO: triage flags as part of 26466827 15359 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15360 try { 15361 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 15362 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 15363 } catch (InstallerException e) { 15364 return false; 15365 } 15366 15367 // Fix-up for forward-locked applications in ASEC containers. 15368 if (!isExternal(p)) { 15369 pStats.codeSize += pStats.externalCodeSize; 15370 pStats.externalCodeSize = 0L; 15371 } 15372 15373 return true; 15374 } 15375 15376 15377 @Override 15378 public void addPackageToPreferred(String packageName) { 15379 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 15380 } 15381 15382 @Override 15383 public void removePackageFromPreferred(String packageName) { 15384 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 15385 } 15386 15387 @Override 15388 public List<PackageInfo> getPreferredPackages(int flags) { 15389 return new ArrayList<PackageInfo>(); 15390 } 15391 15392 private int getUidTargetSdkVersionLockedLPr(int uid) { 15393 Object obj = mSettings.getUserIdLPr(uid); 15394 if (obj instanceof SharedUserSetting) { 15395 final SharedUserSetting sus = (SharedUserSetting) obj; 15396 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 15397 final Iterator<PackageSetting> it = sus.packages.iterator(); 15398 while (it.hasNext()) { 15399 final PackageSetting ps = it.next(); 15400 if (ps.pkg != null) { 15401 int v = ps.pkg.applicationInfo.targetSdkVersion; 15402 if (v < vers) vers = v; 15403 } 15404 } 15405 return vers; 15406 } else if (obj instanceof PackageSetting) { 15407 final PackageSetting ps = (PackageSetting) obj; 15408 if (ps.pkg != null) { 15409 return ps.pkg.applicationInfo.targetSdkVersion; 15410 } 15411 } 15412 return Build.VERSION_CODES.CUR_DEVELOPMENT; 15413 } 15414 15415 @Override 15416 public void addPreferredActivity(IntentFilter filter, int match, 15417 ComponentName[] set, ComponentName activity, int userId) { 15418 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15419 "Adding preferred"); 15420 } 15421 15422 private void addPreferredActivityInternal(IntentFilter filter, int match, 15423 ComponentName[] set, ComponentName activity, boolean always, int userId, 15424 String opname) { 15425 // writer 15426 int callingUid = Binder.getCallingUid(); 15427 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 15428 if (filter.countActions() == 0) { 15429 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15430 return; 15431 } 15432 synchronized (mPackages) { 15433 if (mContext.checkCallingOrSelfPermission( 15434 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15435 != PackageManager.PERMISSION_GRANTED) { 15436 if (getUidTargetSdkVersionLockedLPr(callingUid) 15437 < Build.VERSION_CODES.FROYO) { 15438 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 15439 + callingUid); 15440 return; 15441 } 15442 mContext.enforceCallingOrSelfPermission( 15443 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15444 } 15445 15446 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 15447 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 15448 + userId + ":"); 15449 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15450 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 15451 scheduleWritePackageRestrictionsLocked(userId); 15452 } 15453 } 15454 15455 @Override 15456 public void replacePreferredActivity(IntentFilter filter, int match, 15457 ComponentName[] set, ComponentName activity, int userId) { 15458 if (filter.countActions() != 1) { 15459 throw new IllegalArgumentException( 15460 "replacePreferredActivity expects filter to have only 1 action."); 15461 } 15462 if (filter.countDataAuthorities() != 0 15463 || filter.countDataPaths() != 0 15464 || filter.countDataSchemes() > 1 15465 || filter.countDataTypes() != 0) { 15466 throw new IllegalArgumentException( 15467 "replacePreferredActivity expects filter to have no data authorities, " + 15468 "paths, or types; and at most one scheme."); 15469 } 15470 15471 final int callingUid = Binder.getCallingUid(); 15472 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 15473 synchronized (mPackages) { 15474 if (mContext.checkCallingOrSelfPermission( 15475 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15476 != PackageManager.PERMISSION_GRANTED) { 15477 if (getUidTargetSdkVersionLockedLPr(callingUid) 15478 < Build.VERSION_CODES.FROYO) { 15479 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 15480 + Binder.getCallingUid()); 15481 return; 15482 } 15483 mContext.enforceCallingOrSelfPermission( 15484 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15485 } 15486 15487 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15488 if (pir != null) { 15489 // Get all of the existing entries that exactly match this filter. 15490 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 15491 if (existing != null && existing.size() == 1) { 15492 PreferredActivity cur = existing.get(0); 15493 if (DEBUG_PREFERRED) { 15494 Slog.i(TAG, "Checking replace of preferred:"); 15495 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15496 if (!cur.mPref.mAlways) { 15497 Slog.i(TAG, " -- CUR; not mAlways!"); 15498 } else { 15499 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 15500 Slog.i(TAG, " -- CUR: mSet=" 15501 + Arrays.toString(cur.mPref.mSetComponents)); 15502 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 15503 Slog.i(TAG, " -- NEW: mMatch=" 15504 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 15505 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 15506 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 15507 } 15508 } 15509 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 15510 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 15511 && cur.mPref.sameSet(set)) { 15512 // Setting the preferred activity to what it happens to be already 15513 if (DEBUG_PREFERRED) { 15514 Slog.i(TAG, "Replacing with same preferred activity " 15515 + cur.mPref.mShortComponent + " for user " 15516 + userId + ":"); 15517 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15518 } 15519 return; 15520 } 15521 } 15522 15523 if (existing != null) { 15524 if (DEBUG_PREFERRED) { 15525 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 15526 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15527 } 15528 for (int i = 0; i < existing.size(); i++) { 15529 PreferredActivity pa = existing.get(i); 15530 if (DEBUG_PREFERRED) { 15531 Slog.i(TAG, "Removing existing preferred activity " 15532 + pa.mPref.mComponent + ":"); 15533 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 15534 } 15535 pir.removeFilter(pa); 15536 } 15537 } 15538 } 15539 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15540 "Replacing preferred"); 15541 } 15542 } 15543 15544 @Override 15545 public void clearPackagePreferredActivities(String packageName) { 15546 final int uid = Binder.getCallingUid(); 15547 // writer 15548 synchronized (mPackages) { 15549 PackageParser.Package pkg = mPackages.get(packageName); 15550 if (pkg == null || pkg.applicationInfo.uid != uid) { 15551 if (mContext.checkCallingOrSelfPermission( 15552 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15553 != PackageManager.PERMISSION_GRANTED) { 15554 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 15555 < Build.VERSION_CODES.FROYO) { 15556 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 15557 + Binder.getCallingUid()); 15558 return; 15559 } 15560 mContext.enforceCallingOrSelfPermission( 15561 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15562 } 15563 } 15564 15565 int user = UserHandle.getCallingUserId(); 15566 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 15567 scheduleWritePackageRestrictionsLocked(user); 15568 } 15569 } 15570 } 15571 15572 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15573 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 15574 ArrayList<PreferredActivity> removed = null; 15575 boolean changed = false; 15576 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15577 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 15578 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15579 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 15580 continue; 15581 } 15582 Iterator<PreferredActivity> it = pir.filterIterator(); 15583 while (it.hasNext()) { 15584 PreferredActivity pa = it.next(); 15585 // Mark entry for removal only if it matches the package name 15586 // and the entry is of type "always". 15587 if (packageName == null || 15588 (pa.mPref.mComponent.getPackageName().equals(packageName) 15589 && pa.mPref.mAlways)) { 15590 if (removed == null) { 15591 removed = new ArrayList<PreferredActivity>(); 15592 } 15593 removed.add(pa); 15594 } 15595 } 15596 if (removed != null) { 15597 for (int j=0; j<removed.size(); j++) { 15598 PreferredActivity pa = removed.get(j); 15599 pir.removeFilter(pa); 15600 } 15601 changed = true; 15602 } 15603 } 15604 return changed; 15605 } 15606 15607 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15608 private void clearIntentFilterVerificationsLPw(int userId) { 15609 final int packageCount = mPackages.size(); 15610 for (int i = 0; i < packageCount; i++) { 15611 PackageParser.Package pkg = mPackages.valueAt(i); 15612 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 15613 } 15614 } 15615 15616 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15617 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 15618 if (userId == UserHandle.USER_ALL) { 15619 if (mSettings.removeIntentFilterVerificationLPw(packageName, 15620 sUserManager.getUserIds())) { 15621 for (int oneUserId : sUserManager.getUserIds()) { 15622 scheduleWritePackageRestrictionsLocked(oneUserId); 15623 } 15624 } 15625 } else { 15626 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 15627 scheduleWritePackageRestrictionsLocked(userId); 15628 } 15629 } 15630 } 15631 15632 void clearDefaultBrowserIfNeeded(String packageName) { 15633 for (int oneUserId : sUserManager.getUserIds()) { 15634 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 15635 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 15636 if (packageName.equals(defaultBrowserPackageName)) { 15637 setDefaultBrowserPackageName(null, oneUserId); 15638 } 15639 } 15640 } 15641 15642 @Override 15643 public void resetApplicationPreferences(int userId) { 15644 mContext.enforceCallingOrSelfPermission( 15645 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15646 // writer 15647 synchronized (mPackages) { 15648 final long identity = Binder.clearCallingIdentity(); 15649 try { 15650 clearPackagePreferredActivitiesLPw(null, userId); 15651 mSettings.applyDefaultPreferredAppsLPw(this, userId); 15652 // TODO: We have to reset the default SMS and Phone. This requires 15653 // significant refactoring to keep all default apps in the package 15654 // manager (cleaner but more work) or have the services provide 15655 // callbacks to the package manager to request a default app reset. 15656 applyFactoryDefaultBrowserLPw(userId); 15657 clearIntentFilterVerificationsLPw(userId); 15658 primeDomainVerificationsLPw(userId); 15659 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 15660 scheduleWritePackageRestrictionsLocked(userId); 15661 } finally { 15662 Binder.restoreCallingIdentity(identity); 15663 } 15664 } 15665 } 15666 15667 @Override 15668 public int getPreferredActivities(List<IntentFilter> outFilters, 15669 List<ComponentName> outActivities, String packageName) { 15670 15671 int num = 0; 15672 final int userId = UserHandle.getCallingUserId(); 15673 // reader 15674 synchronized (mPackages) { 15675 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15676 if (pir != null) { 15677 final Iterator<PreferredActivity> it = pir.filterIterator(); 15678 while (it.hasNext()) { 15679 final PreferredActivity pa = it.next(); 15680 if (packageName == null 15681 || (pa.mPref.mComponent.getPackageName().equals(packageName) 15682 && pa.mPref.mAlways)) { 15683 if (outFilters != null) { 15684 outFilters.add(new IntentFilter(pa)); 15685 } 15686 if (outActivities != null) { 15687 outActivities.add(pa.mPref.mComponent); 15688 } 15689 } 15690 } 15691 } 15692 } 15693 15694 return num; 15695 } 15696 15697 @Override 15698 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 15699 int userId) { 15700 int callingUid = Binder.getCallingUid(); 15701 if (callingUid != Process.SYSTEM_UID) { 15702 throw new SecurityException( 15703 "addPersistentPreferredActivity can only be run by the system"); 15704 } 15705 if (filter.countActions() == 0) { 15706 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15707 return; 15708 } 15709 synchronized (mPackages) { 15710 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 15711 ":"); 15712 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15713 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 15714 new PersistentPreferredActivity(filter, activity)); 15715 scheduleWritePackageRestrictionsLocked(userId); 15716 } 15717 } 15718 15719 @Override 15720 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 15721 int callingUid = Binder.getCallingUid(); 15722 if (callingUid != Process.SYSTEM_UID) { 15723 throw new SecurityException( 15724 "clearPackagePersistentPreferredActivities can only be run by the system"); 15725 } 15726 ArrayList<PersistentPreferredActivity> removed = null; 15727 boolean changed = false; 15728 synchronized (mPackages) { 15729 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 15730 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 15731 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 15732 .valueAt(i); 15733 if (userId != thisUserId) { 15734 continue; 15735 } 15736 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 15737 while (it.hasNext()) { 15738 PersistentPreferredActivity ppa = it.next(); 15739 // Mark entry for removal only if it matches the package name. 15740 if (ppa.mComponent.getPackageName().equals(packageName)) { 15741 if (removed == null) { 15742 removed = new ArrayList<PersistentPreferredActivity>(); 15743 } 15744 removed.add(ppa); 15745 } 15746 } 15747 if (removed != null) { 15748 for (int j=0; j<removed.size(); j++) { 15749 PersistentPreferredActivity ppa = removed.get(j); 15750 ppir.removeFilter(ppa); 15751 } 15752 changed = true; 15753 } 15754 } 15755 15756 if (changed) { 15757 scheduleWritePackageRestrictionsLocked(userId); 15758 } 15759 } 15760 } 15761 15762 /** 15763 * Common machinery for picking apart a restored XML blob and passing 15764 * it to a caller-supplied functor to be applied to the running system. 15765 */ 15766 private void restoreFromXml(XmlPullParser parser, int userId, 15767 String expectedStartTag, BlobXmlRestorer functor) 15768 throws IOException, XmlPullParserException { 15769 int type; 15770 while ((type = parser.next()) != XmlPullParser.START_TAG 15771 && type != XmlPullParser.END_DOCUMENT) { 15772 } 15773 if (type != XmlPullParser.START_TAG) { 15774 // oops didn't find a start tag?! 15775 if (DEBUG_BACKUP) { 15776 Slog.e(TAG, "Didn't find start tag during restore"); 15777 } 15778 return; 15779 } 15780Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 15781 // this is supposed to be TAG_PREFERRED_BACKUP 15782 if (!expectedStartTag.equals(parser.getName())) { 15783 if (DEBUG_BACKUP) { 15784 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 15785 } 15786 return; 15787 } 15788 15789 // skip interfering stuff, then we're aligned with the backing implementation 15790 while ((type = parser.next()) == XmlPullParser.TEXT) { } 15791Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 15792 functor.apply(parser, userId); 15793 } 15794 15795 private interface BlobXmlRestorer { 15796 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 15797 } 15798 15799 /** 15800 * Non-Binder method, support for the backup/restore mechanism: write the 15801 * full set of preferred activities in its canonical XML format. Returns the 15802 * XML output as a byte array, or null if there is none. 15803 */ 15804 @Override 15805 public byte[] getPreferredActivityBackup(int userId) { 15806 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15807 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 15808 } 15809 15810 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15811 try { 15812 final XmlSerializer serializer = new FastXmlSerializer(); 15813 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15814 serializer.startDocument(null, true); 15815 serializer.startTag(null, TAG_PREFERRED_BACKUP); 15816 15817 synchronized (mPackages) { 15818 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 15819 } 15820 15821 serializer.endTag(null, TAG_PREFERRED_BACKUP); 15822 serializer.endDocument(); 15823 serializer.flush(); 15824 } catch (Exception e) { 15825 if (DEBUG_BACKUP) { 15826 Slog.e(TAG, "Unable to write preferred activities for backup", e); 15827 } 15828 return null; 15829 } 15830 15831 return dataStream.toByteArray(); 15832 } 15833 15834 @Override 15835 public void restorePreferredActivities(byte[] backup, int userId) { 15836 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15837 throw new SecurityException("Only the system may call restorePreferredActivities()"); 15838 } 15839 15840 try { 15841 final XmlPullParser parser = Xml.newPullParser(); 15842 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15843 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 15844 new BlobXmlRestorer() { 15845 @Override 15846 public void apply(XmlPullParser parser, int userId) 15847 throws XmlPullParserException, IOException { 15848 synchronized (mPackages) { 15849 mSettings.readPreferredActivitiesLPw(parser, userId); 15850 } 15851 } 15852 } ); 15853 } catch (Exception e) { 15854 if (DEBUG_BACKUP) { 15855 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15856 } 15857 } 15858 } 15859 15860 /** 15861 * Non-Binder method, support for the backup/restore mechanism: write the 15862 * default browser (etc) settings in its canonical XML format. Returns the default 15863 * browser XML representation as a byte array, or null if there is none. 15864 */ 15865 @Override 15866 public byte[] getDefaultAppsBackup(int userId) { 15867 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15868 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 15869 } 15870 15871 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15872 try { 15873 final XmlSerializer serializer = new FastXmlSerializer(); 15874 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15875 serializer.startDocument(null, true); 15876 serializer.startTag(null, TAG_DEFAULT_APPS); 15877 15878 synchronized (mPackages) { 15879 mSettings.writeDefaultAppsLPr(serializer, userId); 15880 } 15881 15882 serializer.endTag(null, TAG_DEFAULT_APPS); 15883 serializer.endDocument(); 15884 serializer.flush(); 15885 } catch (Exception e) { 15886 if (DEBUG_BACKUP) { 15887 Slog.e(TAG, "Unable to write default apps for backup", e); 15888 } 15889 return null; 15890 } 15891 15892 return dataStream.toByteArray(); 15893 } 15894 15895 @Override 15896 public void restoreDefaultApps(byte[] backup, int userId) { 15897 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15898 throw new SecurityException("Only the system may call restoreDefaultApps()"); 15899 } 15900 15901 try { 15902 final XmlPullParser parser = Xml.newPullParser(); 15903 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15904 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 15905 new BlobXmlRestorer() { 15906 @Override 15907 public void apply(XmlPullParser parser, int userId) 15908 throws XmlPullParserException, IOException { 15909 synchronized (mPackages) { 15910 mSettings.readDefaultAppsLPw(parser, userId); 15911 } 15912 } 15913 } ); 15914 } catch (Exception e) { 15915 if (DEBUG_BACKUP) { 15916 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 15917 } 15918 } 15919 } 15920 15921 @Override 15922 public byte[] getIntentFilterVerificationBackup(int userId) { 15923 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15924 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 15925 } 15926 15927 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15928 try { 15929 final XmlSerializer serializer = new FastXmlSerializer(); 15930 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15931 serializer.startDocument(null, true); 15932 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 15933 15934 synchronized (mPackages) { 15935 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 15936 } 15937 15938 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 15939 serializer.endDocument(); 15940 serializer.flush(); 15941 } catch (Exception e) { 15942 if (DEBUG_BACKUP) { 15943 Slog.e(TAG, "Unable to write default apps for backup", e); 15944 } 15945 return null; 15946 } 15947 15948 return dataStream.toByteArray(); 15949 } 15950 15951 @Override 15952 public void restoreIntentFilterVerification(byte[] backup, int userId) { 15953 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15954 throw new SecurityException("Only the system may call restorePreferredActivities()"); 15955 } 15956 15957 try { 15958 final XmlPullParser parser = Xml.newPullParser(); 15959 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15960 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 15961 new BlobXmlRestorer() { 15962 @Override 15963 public void apply(XmlPullParser parser, int userId) 15964 throws XmlPullParserException, IOException { 15965 synchronized (mPackages) { 15966 mSettings.readAllDomainVerificationsLPr(parser, userId); 15967 mSettings.writeLPr(); 15968 } 15969 } 15970 } ); 15971 } catch (Exception e) { 15972 if (DEBUG_BACKUP) { 15973 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15974 } 15975 } 15976 } 15977 15978 @Override 15979 public byte[] getPermissionGrantBackup(int userId) { 15980 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15981 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 15982 } 15983 15984 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15985 try { 15986 final XmlSerializer serializer = new FastXmlSerializer(); 15987 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15988 serializer.startDocument(null, true); 15989 serializer.startTag(null, TAG_PERMISSION_BACKUP); 15990 15991 synchronized (mPackages) { 15992 serializeRuntimePermissionGrantsLPr(serializer, userId); 15993 } 15994 15995 serializer.endTag(null, TAG_PERMISSION_BACKUP); 15996 serializer.endDocument(); 15997 serializer.flush(); 15998 } catch (Exception e) { 15999 if (DEBUG_BACKUP) { 16000 Slog.e(TAG, "Unable to write default apps for backup", e); 16001 } 16002 return null; 16003 } 16004 16005 return dataStream.toByteArray(); 16006 } 16007 16008 @Override 16009 public void restorePermissionGrants(byte[] backup, int userId) { 16010 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16011 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16012 } 16013 16014 try { 16015 final XmlPullParser parser = Xml.newPullParser(); 16016 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16017 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16018 new BlobXmlRestorer() { 16019 @Override 16020 public void apply(XmlPullParser parser, int userId) 16021 throws XmlPullParserException, IOException { 16022 synchronized (mPackages) { 16023 processRestoredPermissionGrantsLPr(parser, userId); 16024 } 16025 } 16026 } ); 16027 } catch (Exception e) { 16028 if (DEBUG_BACKUP) { 16029 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16030 } 16031 } 16032 } 16033 16034 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16035 throws IOException { 16036 serializer.startTag(null, TAG_ALL_GRANTS); 16037 16038 final int N = mSettings.mPackages.size(); 16039 for (int i = 0; i < N; i++) { 16040 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16041 boolean pkgGrantsKnown = false; 16042 16043 PermissionsState packagePerms = ps.getPermissionsState(); 16044 16045 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16046 final int grantFlags = state.getFlags(); 16047 // only look at grants that are not system/policy fixed 16048 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16049 final boolean isGranted = state.isGranted(); 16050 // And only back up the user-twiddled state bits 16051 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16052 final String packageName = mSettings.mPackages.keyAt(i); 16053 if (!pkgGrantsKnown) { 16054 serializer.startTag(null, TAG_GRANT); 16055 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16056 pkgGrantsKnown = true; 16057 } 16058 16059 final boolean userSet = 16060 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16061 final boolean userFixed = 16062 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16063 final boolean revoke = 16064 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16065 16066 serializer.startTag(null, TAG_PERMISSION); 16067 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16068 if (isGranted) { 16069 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16070 } 16071 if (userSet) { 16072 serializer.attribute(null, ATTR_USER_SET, "true"); 16073 } 16074 if (userFixed) { 16075 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16076 } 16077 if (revoke) { 16078 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16079 } 16080 serializer.endTag(null, TAG_PERMISSION); 16081 } 16082 } 16083 } 16084 16085 if (pkgGrantsKnown) { 16086 serializer.endTag(null, TAG_GRANT); 16087 } 16088 } 16089 16090 serializer.endTag(null, TAG_ALL_GRANTS); 16091 } 16092 16093 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16094 throws XmlPullParserException, IOException { 16095 String pkgName = null; 16096 int outerDepth = parser.getDepth(); 16097 int type; 16098 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16099 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16100 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16101 continue; 16102 } 16103 16104 final String tagName = parser.getName(); 16105 if (tagName.equals(TAG_GRANT)) { 16106 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16107 if (DEBUG_BACKUP) { 16108 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16109 } 16110 } else if (tagName.equals(TAG_PERMISSION)) { 16111 16112 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16113 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16114 16115 int newFlagSet = 0; 16116 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16117 newFlagSet |= FLAG_PERMISSION_USER_SET; 16118 } 16119 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16120 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16121 } 16122 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16123 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16124 } 16125 if (DEBUG_BACKUP) { 16126 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16127 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16128 } 16129 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16130 if (ps != null) { 16131 // Already installed so we apply the grant immediately 16132 if (DEBUG_BACKUP) { 16133 Slog.v(TAG, " + already installed; applying"); 16134 } 16135 PermissionsState perms = ps.getPermissionsState(); 16136 BasePermission bp = mSettings.mPermissions.get(permName); 16137 if (bp != null) { 16138 if (isGranted) { 16139 perms.grantRuntimePermission(bp, userId); 16140 } 16141 if (newFlagSet != 0) { 16142 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16143 } 16144 } 16145 } else { 16146 // Need to wait for post-restore install to apply the grant 16147 if (DEBUG_BACKUP) { 16148 Slog.v(TAG, " - not yet installed; saving for later"); 16149 } 16150 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16151 isGranted, newFlagSet, userId); 16152 } 16153 } else { 16154 PackageManagerService.reportSettingsProblem(Log.WARN, 16155 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16156 XmlUtils.skipCurrentTag(parser); 16157 } 16158 } 16159 16160 scheduleWriteSettingsLocked(); 16161 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16162 } 16163 16164 @Override 16165 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16166 int sourceUserId, int targetUserId, int flags) { 16167 mContext.enforceCallingOrSelfPermission( 16168 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16169 int callingUid = Binder.getCallingUid(); 16170 enforceOwnerRights(ownerPackage, callingUid); 16171 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16172 if (intentFilter.countActions() == 0) { 16173 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16174 return; 16175 } 16176 synchronized (mPackages) { 16177 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16178 ownerPackage, targetUserId, flags); 16179 CrossProfileIntentResolver resolver = 16180 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16181 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16182 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16183 if (existing != null) { 16184 int size = existing.size(); 16185 for (int i = 0; i < size; i++) { 16186 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16187 return; 16188 } 16189 } 16190 } 16191 resolver.addFilter(newFilter); 16192 scheduleWritePackageRestrictionsLocked(sourceUserId); 16193 } 16194 } 16195 16196 @Override 16197 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16198 mContext.enforceCallingOrSelfPermission( 16199 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16200 int callingUid = Binder.getCallingUid(); 16201 enforceOwnerRights(ownerPackage, callingUid); 16202 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16203 synchronized (mPackages) { 16204 CrossProfileIntentResolver resolver = 16205 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16206 ArraySet<CrossProfileIntentFilter> set = 16207 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16208 for (CrossProfileIntentFilter filter : set) { 16209 if (filter.getOwnerPackage().equals(ownerPackage)) { 16210 resolver.removeFilter(filter); 16211 } 16212 } 16213 scheduleWritePackageRestrictionsLocked(sourceUserId); 16214 } 16215 } 16216 16217 // Enforcing that callingUid is owning pkg on userId 16218 private void enforceOwnerRights(String pkg, int callingUid) { 16219 // The system owns everything. 16220 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16221 return; 16222 } 16223 int callingUserId = UserHandle.getUserId(callingUid); 16224 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16225 if (pi == null) { 16226 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16227 + callingUserId); 16228 } 16229 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16230 throw new SecurityException("Calling uid " + callingUid 16231 + " does not own package " + pkg); 16232 } 16233 } 16234 16235 @Override 16236 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16237 Intent intent = new Intent(Intent.ACTION_MAIN); 16238 intent.addCategory(Intent.CATEGORY_HOME); 16239 16240 final int callingUserId = UserHandle.getCallingUserId(); 16241 List<ResolveInfo> list = queryIntentActivities(intent, null, 16242 PackageManager.GET_META_DATA, callingUserId); 16243 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16244 true, false, false, callingUserId); 16245 16246 allHomeCandidates.clear(); 16247 if (list != null) { 16248 for (ResolveInfo ri : list) { 16249 allHomeCandidates.add(ri); 16250 } 16251 } 16252 return (preferred == null || preferred.activityInfo == null) 16253 ? null 16254 : new ComponentName(preferred.activityInfo.packageName, 16255 preferred.activityInfo.name); 16256 } 16257 16258 @Override 16259 public void setApplicationEnabledSetting(String appPackageName, 16260 int newState, int flags, int userId, String callingPackage) { 16261 if (!sUserManager.exists(userId)) return; 16262 if (callingPackage == null) { 16263 callingPackage = Integer.toString(Binder.getCallingUid()); 16264 } 16265 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 16266 } 16267 16268 @Override 16269 public void setComponentEnabledSetting(ComponentName componentName, 16270 int newState, int flags, int userId) { 16271 if (!sUserManager.exists(userId)) return; 16272 setEnabledSetting(componentName.getPackageName(), 16273 componentName.getClassName(), newState, flags, userId, null); 16274 } 16275 16276 private void setEnabledSetting(final String packageName, String className, int newState, 16277 final int flags, int userId, String callingPackage) { 16278 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 16279 || newState == COMPONENT_ENABLED_STATE_ENABLED 16280 || newState == COMPONENT_ENABLED_STATE_DISABLED 16281 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 16282 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 16283 throw new IllegalArgumentException("Invalid new component state: " 16284 + newState); 16285 } 16286 PackageSetting pkgSetting; 16287 final int uid = Binder.getCallingUid(); 16288 final int permission = mContext.checkCallingOrSelfPermission( 16289 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16290 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 16291 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16292 boolean sendNow = false; 16293 boolean isApp = (className == null); 16294 String componentName = isApp ? packageName : className; 16295 int packageUid = -1; 16296 ArrayList<String> components; 16297 16298 // writer 16299 synchronized (mPackages) { 16300 pkgSetting = mSettings.mPackages.get(packageName); 16301 if (pkgSetting == null) { 16302 if (className == null) { 16303 throw new IllegalArgumentException("Unknown package: " + packageName); 16304 } 16305 throw new IllegalArgumentException( 16306 "Unknown component: " + packageName + "/" + className); 16307 } 16308 // Allow root and verify that userId is not being specified by a different user 16309 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 16310 throw new SecurityException( 16311 "Permission Denial: attempt to change component state from pid=" 16312 + Binder.getCallingPid() 16313 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 16314 } 16315 if (className == null) { 16316 // We're dealing with an application/package level state change 16317 if (pkgSetting.getEnabled(userId) == newState) { 16318 // Nothing to do 16319 return; 16320 } 16321 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 16322 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 16323 // Don't care about who enables an app. 16324 callingPackage = null; 16325 } 16326 pkgSetting.setEnabled(newState, userId, callingPackage); 16327 // pkgSetting.pkg.mSetEnabled = newState; 16328 } else { 16329 // We're dealing with a component level state change 16330 // First, verify that this is a valid class name. 16331 PackageParser.Package pkg = pkgSetting.pkg; 16332 if (pkg == null || !pkg.hasComponentClassName(className)) { 16333 if (pkg != null && 16334 pkg.applicationInfo.targetSdkVersion >= 16335 Build.VERSION_CODES.JELLY_BEAN) { 16336 throw new IllegalArgumentException("Component class " + className 16337 + " does not exist in " + packageName); 16338 } else { 16339 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 16340 + className + " does not exist in " + packageName); 16341 } 16342 } 16343 switch (newState) { 16344 case COMPONENT_ENABLED_STATE_ENABLED: 16345 if (!pkgSetting.enableComponentLPw(className, userId)) { 16346 return; 16347 } 16348 break; 16349 case COMPONENT_ENABLED_STATE_DISABLED: 16350 if (!pkgSetting.disableComponentLPw(className, userId)) { 16351 return; 16352 } 16353 break; 16354 case COMPONENT_ENABLED_STATE_DEFAULT: 16355 if (!pkgSetting.restoreComponentLPw(className, userId)) { 16356 return; 16357 } 16358 break; 16359 default: 16360 Slog.e(TAG, "Invalid new component state: " + newState); 16361 return; 16362 } 16363 } 16364 scheduleWritePackageRestrictionsLocked(userId); 16365 components = mPendingBroadcasts.get(userId, packageName); 16366 final boolean newPackage = components == null; 16367 if (newPackage) { 16368 components = new ArrayList<String>(); 16369 } 16370 if (!components.contains(componentName)) { 16371 components.add(componentName); 16372 } 16373 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 16374 sendNow = true; 16375 // Purge entry from pending broadcast list if another one exists already 16376 // since we are sending one right away. 16377 mPendingBroadcasts.remove(userId, packageName); 16378 } else { 16379 if (newPackage) { 16380 mPendingBroadcasts.put(userId, packageName, components); 16381 } 16382 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 16383 // Schedule a message 16384 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 16385 } 16386 } 16387 } 16388 16389 long callingId = Binder.clearCallingIdentity(); 16390 try { 16391 if (sendNow) { 16392 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 16393 sendPackageChangedBroadcast(packageName, 16394 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 16395 } 16396 } finally { 16397 Binder.restoreCallingIdentity(callingId); 16398 } 16399 } 16400 16401 private void sendPackageChangedBroadcast(String packageName, 16402 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 16403 if (DEBUG_INSTALL) 16404 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 16405 + componentNames); 16406 Bundle extras = new Bundle(4); 16407 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 16408 String nameList[] = new String[componentNames.size()]; 16409 componentNames.toArray(nameList); 16410 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 16411 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 16412 extras.putInt(Intent.EXTRA_UID, packageUid); 16413 // If this is not reporting a change of the overall package, then only send it 16414 // to registered receivers. We don't want to launch a swath of apps for every 16415 // little component state change. 16416 final int flags = !componentNames.contains(packageName) 16417 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 16418 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 16419 new int[] {UserHandle.getUserId(packageUid)}); 16420 } 16421 16422 @Override 16423 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 16424 if (!sUserManager.exists(userId)) return; 16425 final int uid = Binder.getCallingUid(); 16426 final int permission = mContext.checkCallingOrSelfPermission( 16427 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16428 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16429 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 16430 // writer 16431 synchronized (mPackages) { 16432 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 16433 allowedByPermission, uid, userId)) { 16434 scheduleWritePackageRestrictionsLocked(userId); 16435 } 16436 } 16437 } 16438 16439 @Override 16440 public String getInstallerPackageName(String packageName) { 16441 // reader 16442 synchronized (mPackages) { 16443 return mSettings.getInstallerPackageNameLPr(packageName); 16444 } 16445 } 16446 16447 @Override 16448 public int getApplicationEnabledSetting(String packageName, int userId) { 16449 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16450 int uid = Binder.getCallingUid(); 16451 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 16452 // reader 16453 synchronized (mPackages) { 16454 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 16455 } 16456 } 16457 16458 @Override 16459 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 16460 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16461 int uid = Binder.getCallingUid(); 16462 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 16463 // reader 16464 synchronized (mPackages) { 16465 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 16466 } 16467 } 16468 16469 @Override 16470 public void enterSafeMode() { 16471 enforceSystemOrRoot("Only the system can request entering safe mode"); 16472 16473 if (!mSystemReady) { 16474 mSafeMode = true; 16475 } 16476 } 16477 16478 @Override 16479 public void systemReady() { 16480 mSystemReady = true; 16481 16482 // Read the compatibilty setting when the system is ready. 16483 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 16484 mContext.getContentResolver(), 16485 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 16486 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 16487 if (DEBUG_SETTINGS) { 16488 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 16489 } 16490 16491 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 16492 16493 synchronized (mPackages) { 16494 // Verify that all of the preferred activity components actually 16495 // exist. It is possible for applications to be updated and at 16496 // that point remove a previously declared activity component that 16497 // had been set as a preferred activity. We try to clean this up 16498 // the next time we encounter that preferred activity, but it is 16499 // possible for the user flow to never be able to return to that 16500 // situation so here we do a sanity check to make sure we haven't 16501 // left any junk around. 16502 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 16503 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16504 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16505 removed.clear(); 16506 for (PreferredActivity pa : pir.filterSet()) { 16507 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 16508 removed.add(pa); 16509 } 16510 } 16511 if (removed.size() > 0) { 16512 for (int r=0; r<removed.size(); r++) { 16513 PreferredActivity pa = removed.get(r); 16514 Slog.w(TAG, "Removing dangling preferred activity: " 16515 + pa.mPref.mComponent); 16516 pir.removeFilter(pa); 16517 } 16518 mSettings.writePackageRestrictionsLPr( 16519 mSettings.mPreferredActivities.keyAt(i)); 16520 } 16521 } 16522 16523 for (int userId : UserManagerService.getInstance().getUserIds()) { 16524 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 16525 grantPermissionsUserIds = ArrayUtils.appendInt( 16526 grantPermissionsUserIds, userId); 16527 } 16528 } 16529 } 16530 sUserManager.systemReady(); 16531 16532 // If we upgraded grant all default permissions before kicking off. 16533 for (int userId : grantPermissionsUserIds) { 16534 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 16535 } 16536 16537 // Kick off any messages waiting for system ready 16538 if (mPostSystemReadyMessages != null) { 16539 for (Message msg : mPostSystemReadyMessages) { 16540 msg.sendToTarget(); 16541 } 16542 mPostSystemReadyMessages = null; 16543 } 16544 16545 // Watch for external volumes that come and go over time 16546 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16547 storage.registerListener(mStorageListener); 16548 16549 mInstallerService.systemReady(); 16550 mPackageDexOptimizer.systemReady(); 16551 16552 MountServiceInternal mountServiceInternal = LocalServices.getService( 16553 MountServiceInternal.class); 16554 mountServiceInternal.addExternalStoragePolicy( 16555 new MountServiceInternal.ExternalStorageMountPolicy() { 16556 @Override 16557 public int getMountMode(int uid, String packageName) { 16558 if (Process.isIsolated(uid)) { 16559 return Zygote.MOUNT_EXTERNAL_NONE; 16560 } 16561 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 16562 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16563 } 16564 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16565 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16566 } 16567 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16568 return Zygote.MOUNT_EXTERNAL_READ; 16569 } 16570 return Zygote.MOUNT_EXTERNAL_WRITE; 16571 } 16572 16573 @Override 16574 public boolean hasExternalStorage(int uid, String packageName) { 16575 return true; 16576 } 16577 }); 16578 } 16579 16580 @Override 16581 public boolean isSafeMode() { 16582 return mSafeMode; 16583 } 16584 16585 @Override 16586 public boolean hasSystemUidErrors() { 16587 return mHasSystemUidErrors; 16588 } 16589 16590 static String arrayToString(int[] array) { 16591 StringBuffer buf = new StringBuffer(128); 16592 buf.append('['); 16593 if (array != null) { 16594 for (int i=0; i<array.length; i++) { 16595 if (i > 0) buf.append(", "); 16596 buf.append(array[i]); 16597 } 16598 } 16599 buf.append(']'); 16600 return buf.toString(); 16601 } 16602 16603 static class DumpState { 16604 public static final int DUMP_LIBS = 1 << 0; 16605 public static final int DUMP_FEATURES = 1 << 1; 16606 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 16607 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 16608 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 16609 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 16610 public static final int DUMP_PERMISSIONS = 1 << 6; 16611 public static final int DUMP_PACKAGES = 1 << 7; 16612 public static final int DUMP_SHARED_USERS = 1 << 8; 16613 public static final int DUMP_MESSAGES = 1 << 9; 16614 public static final int DUMP_PROVIDERS = 1 << 10; 16615 public static final int DUMP_VERIFIERS = 1 << 11; 16616 public static final int DUMP_PREFERRED = 1 << 12; 16617 public static final int DUMP_PREFERRED_XML = 1 << 13; 16618 public static final int DUMP_KEYSETS = 1 << 14; 16619 public static final int DUMP_VERSION = 1 << 15; 16620 public static final int DUMP_INSTALLS = 1 << 16; 16621 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 16622 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 16623 16624 public static final int OPTION_SHOW_FILTERS = 1 << 0; 16625 16626 private int mTypes; 16627 16628 private int mOptions; 16629 16630 private boolean mTitlePrinted; 16631 16632 private SharedUserSetting mSharedUser; 16633 16634 public boolean isDumping(int type) { 16635 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 16636 return true; 16637 } 16638 16639 return (mTypes & type) != 0; 16640 } 16641 16642 public void setDump(int type) { 16643 mTypes |= type; 16644 } 16645 16646 public boolean isOptionEnabled(int option) { 16647 return (mOptions & option) != 0; 16648 } 16649 16650 public void setOptionEnabled(int option) { 16651 mOptions |= option; 16652 } 16653 16654 public boolean onTitlePrinted() { 16655 final boolean printed = mTitlePrinted; 16656 mTitlePrinted = true; 16657 return printed; 16658 } 16659 16660 public boolean getTitlePrinted() { 16661 return mTitlePrinted; 16662 } 16663 16664 public void setTitlePrinted(boolean enabled) { 16665 mTitlePrinted = enabled; 16666 } 16667 16668 public SharedUserSetting getSharedUser() { 16669 return mSharedUser; 16670 } 16671 16672 public void setSharedUser(SharedUserSetting user) { 16673 mSharedUser = user; 16674 } 16675 } 16676 16677 @Override 16678 public void onShellCommand(FileDescriptor in, FileDescriptor out, 16679 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 16680 (new PackageManagerShellCommand(this)).exec( 16681 this, in, out, err, args, resultReceiver); 16682 } 16683 16684 @Override 16685 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 16686 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 16687 != PackageManager.PERMISSION_GRANTED) { 16688 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 16689 + Binder.getCallingPid() 16690 + ", uid=" + Binder.getCallingUid() 16691 + " without permission " 16692 + android.Manifest.permission.DUMP); 16693 return; 16694 } 16695 16696 DumpState dumpState = new DumpState(); 16697 boolean fullPreferred = false; 16698 boolean checkin = false; 16699 16700 String packageName = null; 16701 ArraySet<String> permissionNames = null; 16702 16703 int opti = 0; 16704 while (opti < args.length) { 16705 String opt = args[opti]; 16706 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 16707 break; 16708 } 16709 opti++; 16710 16711 if ("-a".equals(opt)) { 16712 // Right now we only know how to print all. 16713 } else if ("-h".equals(opt)) { 16714 pw.println("Package manager dump options:"); 16715 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 16716 pw.println(" --checkin: dump for a checkin"); 16717 pw.println(" -f: print details of intent filters"); 16718 pw.println(" -h: print this help"); 16719 pw.println(" cmd may be one of:"); 16720 pw.println(" l[ibraries]: list known shared libraries"); 16721 pw.println(" f[eatures]: list device features"); 16722 pw.println(" k[eysets]: print known keysets"); 16723 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 16724 pw.println(" perm[issions]: dump permissions"); 16725 pw.println(" permission [name ...]: dump declaration and use of given permission"); 16726 pw.println(" pref[erred]: print preferred package settings"); 16727 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 16728 pw.println(" prov[iders]: dump content providers"); 16729 pw.println(" p[ackages]: dump installed packages"); 16730 pw.println(" s[hared-users]: dump shared user IDs"); 16731 pw.println(" m[essages]: print collected runtime messages"); 16732 pw.println(" v[erifiers]: print package verifier info"); 16733 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 16734 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 16735 pw.println(" version: print database version info"); 16736 pw.println(" write: write current settings now"); 16737 pw.println(" installs: details about install sessions"); 16738 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 16739 pw.println(" <package.name>: info about given package"); 16740 return; 16741 } else if ("--checkin".equals(opt)) { 16742 checkin = true; 16743 } else if ("-f".equals(opt)) { 16744 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16745 } else { 16746 pw.println("Unknown argument: " + opt + "; use -h for help"); 16747 } 16748 } 16749 16750 // Is the caller requesting to dump a particular piece of data? 16751 if (opti < args.length) { 16752 String cmd = args[opti]; 16753 opti++; 16754 // Is this a package name? 16755 if ("android".equals(cmd) || cmd.contains(".")) { 16756 packageName = cmd; 16757 // When dumping a single package, we always dump all of its 16758 // filter information since the amount of data will be reasonable. 16759 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16760 } else if ("check-permission".equals(cmd)) { 16761 if (opti >= args.length) { 16762 pw.println("Error: check-permission missing permission argument"); 16763 return; 16764 } 16765 String perm = args[opti]; 16766 opti++; 16767 if (opti >= args.length) { 16768 pw.println("Error: check-permission missing package argument"); 16769 return; 16770 } 16771 String pkg = args[opti]; 16772 opti++; 16773 int user = UserHandle.getUserId(Binder.getCallingUid()); 16774 if (opti < args.length) { 16775 try { 16776 user = Integer.parseInt(args[opti]); 16777 } catch (NumberFormatException e) { 16778 pw.println("Error: check-permission user argument is not a number: " 16779 + args[opti]); 16780 return; 16781 } 16782 } 16783 pw.println(checkPermission(perm, pkg, user)); 16784 return; 16785 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 16786 dumpState.setDump(DumpState.DUMP_LIBS); 16787 } else if ("f".equals(cmd) || "features".equals(cmd)) { 16788 dumpState.setDump(DumpState.DUMP_FEATURES); 16789 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 16790 if (opti >= args.length) { 16791 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 16792 | DumpState.DUMP_SERVICE_RESOLVERS 16793 | DumpState.DUMP_RECEIVER_RESOLVERS 16794 | DumpState.DUMP_CONTENT_RESOLVERS); 16795 } else { 16796 while (opti < args.length) { 16797 String name = args[opti]; 16798 if ("a".equals(name) || "activity".equals(name)) { 16799 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 16800 } else if ("s".equals(name) || "service".equals(name)) { 16801 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 16802 } else if ("r".equals(name) || "receiver".equals(name)) { 16803 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 16804 } else if ("c".equals(name) || "content".equals(name)) { 16805 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 16806 } else { 16807 pw.println("Error: unknown resolver table type: " + name); 16808 return; 16809 } 16810 opti++; 16811 } 16812 } 16813 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 16814 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 16815 } else if ("permission".equals(cmd)) { 16816 if (opti >= args.length) { 16817 pw.println("Error: permission requires permission name"); 16818 return; 16819 } 16820 permissionNames = new ArraySet<>(); 16821 while (opti < args.length) { 16822 permissionNames.add(args[opti]); 16823 opti++; 16824 } 16825 dumpState.setDump(DumpState.DUMP_PERMISSIONS 16826 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 16827 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 16828 dumpState.setDump(DumpState.DUMP_PREFERRED); 16829 } else if ("preferred-xml".equals(cmd)) { 16830 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 16831 if (opti < args.length && "--full".equals(args[opti])) { 16832 fullPreferred = true; 16833 opti++; 16834 } 16835 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 16836 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 16837 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 16838 dumpState.setDump(DumpState.DUMP_PACKAGES); 16839 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 16840 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 16841 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 16842 dumpState.setDump(DumpState.DUMP_PROVIDERS); 16843 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 16844 dumpState.setDump(DumpState.DUMP_MESSAGES); 16845 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 16846 dumpState.setDump(DumpState.DUMP_VERIFIERS); 16847 } else if ("i".equals(cmd) || "ifv".equals(cmd) 16848 || "intent-filter-verifiers".equals(cmd)) { 16849 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 16850 } else if ("version".equals(cmd)) { 16851 dumpState.setDump(DumpState.DUMP_VERSION); 16852 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 16853 dumpState.setDump(DumpState.DUMP_KEYSETS); 16854 } else if ("installs".equals(cmd)) { 16855 dumpState.setDump(DumpState.DUMP_INSTALLS); 16856 } else if ("write".equals(cmd)) { 16857 synchronized (mPackages) { 16858 mSettings.writeLPr(); 16859 pw.println("Settings written."); 16860 return; 16861 } 16862 } 16863 } 16864 16865 if (checkin) { 16866 pw.println("vers,1"); 16867 } 16868 16869 // reader 16870 synchronized (mPackages) { 16871 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 16872 if (!checkin) { 16873 if (dumpState.onTitlePrinted()) 16874 pw.println(); 16875 pw.println("Database versions:"); 16876 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 16877 } 16878 } 16879 16880 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 16881 if (!checkin) { 16882 if (dumpState.onTitlePrinted()) 16883 pw.println(); 16884 pw.println("Verifiers:"); 16885 pw.print(" Required: "); 16886 pw.print(mRequiredVerifierPackage); 16887 pw.print(" (uid="); 16888 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 16889 UserHandle.USER_SYSTEM)); 16890 pw.println(")"); 16891 } else if (mRequiredVerifierPackage != null) { 16892 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 16893 pw.print(","); 16894 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 16895 UserHandle.USER_SYSTEM)); 16896 } 16897 } 16898 16899 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 16900 packageName == null) { 16901 if (mIntentFilterVerifierComponent != null) { 16902 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 16903 if (!checkin) { 16904 if (dumpState.onTitlePrinted()) 16905 pw.println(); 16906 pw.println("Intent Filter Verifier:"); 16907 pw.print(" Using: "); 16908 pw.print(verifierPackageName); 16909 pw.print(" (uid="); 16910 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 16911 UserHandle.USER_SYSTEM)); 16912 pw.println(")"); 16913 } else if (verifierPackageName != null) { 16914 pw.print("ifv,"); pw.print(verifierPackageName); 16915 pw.print(","); 16916 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 16917 UserHandle.USER_SYSTEM)); 16918 } 16919 } else { 16920 pw.println(); 16921 pw.println("No Intent Filter Verifier available!"); 16922 } 16923 } 16924 16925 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 16926 boolean printedHeader = false; 16927 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 16928 while (it.hasNext()) { 16929 String name = it.next(); 16930 SharedLibraryEntry ent = mSharedLibraries.get(name); 16931 if (!checkin) { 16932 if (!printedHeader) { 16933 if (dumpState.onTitlePrinted()) 16934 pw.println(); 16935 pw.println("Libraries:"); 16936 printedHeader = true; 16937 } 16938 pw.print(" "); 16939 } else { 16940 pw.print("lib,"); 16941 } 16942 pw.print(name); 16943 if (!checkin) { 16944 pw.print(" -> "); 16945 } 16946 if (ent.path != null) { 16947 if (!checkin) { 16948 pw.print("(jar) "); 16949 pw.print(ent.path); 16950 } else { 16951 pw.print(",jar,"); 16952 pw.print(ent.path); 16953 } 16954 } else { 16955 if (!checkin) { 16956 pw.print("(apk) "); 16957 pw.print(ent.apk); 16958 } else { 16959 pw.print(",apk,"); 16960 pw.print(ent.apk); 16961 } 16962 } 16963 pw.println(); 16964 } 16965 } 16966 16967 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 16968 if (dumpState.onTitlePrinted()) 16969 pw.println(); 16970 if (!checkin) { 16971 pw.println("Features:"); 16972 } 16973 16974 for (FeatureInfo feat : mAvailableFeatures.values()) { 16975 if (checkin) { 16976 pw.print("feat,"); 16977 pw.print(feat.name); 16978 pw.print(","); 16979 pw.println(feat.version); 16980 } else { 16981 pw.print(" "); 16982 pw.print(feat.name); 16983 if (feat.version > 0) { 16984 pw.print(" version="); 16985 pw.print(feat.version); 16986 } 16987 pw.println(); 16988 } 16989 } 16990 } 16991 16992 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 16993 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 16994 : "Activity Resolver Table:", " ", packageName, 16995 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16996 dumpState.setTitlePrinted(true); 16997 } 16998 } 16999 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17000 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17001 : "Receiver Resolver Table:", " ", packageName, 17002 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17003 dumpState.setTitlePrinted(true); 17004 } 17005 } 17006 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17007 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17008 : "Service Resolver Table:", " ", packageName, 17009 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17010 dumpState.setTitlePrinted(true); 17011 } 17012 } 17013 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17014 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17015 : "Provider Resolver Table:", " ", packageName, 17016 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17017 dumpState.setTitlePrinted(true); 17018 } 17019 } 17020 17021 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17022 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17023 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17024 int user = mSettings.mPreferredActivities.keyAt(i); 17025 if (pir.dump(pw, 17026 dumpState.getTitlePrinted() 17027 ? "\nPreferred Activities User " + user + ":" 17028 : "Preferred Activities User " + user + ":", " ", 17029 packageName, true, false)) { 17030 dumpState.setTitlePrinted(true); 17031 } 17032 } 17033 } 17034 17035 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17036 pw.flush(); 17037 FileOutputStream fout = new FileOutputStream(fd); 17038 BufferedOutputStream str = new BufferedOutputStream(fout); 17039 XmlSerializer serializer = new FastXmlSerializer(); 17040 try { 17041 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17042 serializer.startDocument(null, true); 17043 serializer.setFeature( 17044 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17045 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17046 serializer.endDocument(); 17047 serializer.flush(); 17048 } catch (IllegalArgumentException e) { 17049 pw.println("Failed writing: " + e); 17050 } catch (IllegalStateException e) { 17051 pw.println("Failed writing: " + e); 17052 } catch (IOException e) { 17053 pw.println("Failed writing: " + e); 17054 } 17055 } 17056 17057 if (!checkin 17058 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17059 && packageName == null) { 17060 pw.println(); 17061 int count = mSettings.mPackages.size(); 17062 if (count == 0) { 17063 pw.println("No applications!"); 17064 pw.println(); 17065 } else { 17066 final String prefix = " "; 17067 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17068 if (allPackageSettings.size() == 0) { 17069 pw.println("No domain preferred apps!"); 17070 pw.println(); 17071 } else { 17072 pw.println("App verification status:"); 17073 pw.println(); 17074 count = 0; 17075 for (PackageSetting ps : allPackageSettings) { 17076 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17077 if (ivi == null || ivi.getPackageName() == null) continue; 17078 pw.println(prefix + "Package: " + ivi.getPackageName()); 17079 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17080 pw.println(prefix + "Status: " + ivi.getStatusString()); 17081 pw.println(); 17082 count++; 17083 } 17084 if (count == 0) { 17085 pw.println(prefix + "No app verification established."); 17086 pw.println(); 17087 } 17088 for (int userId : sUserManager.getUserIds()) { 17089 pw.println("App linkages for user " + userId + ":"); 17090 pw.println(); 17091 count = 0; 17092 for (PackageSetting ps : allPackageSettings) { 17093 final long status = ps.getDomainVerificationStatusForUser(userId); 17094 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17095 continue; 17096 } 17097 pw.println(prefix + "Package: " + ps.name); 17098 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17099 String statusStr = IntentFilterVerificationInfo. 17100 getStatusStringFromValue(status); 17101 pw.println(prefix + "Status: " + statusStr); 17102 pw.println(); 17103 count++; 17104 } 17105 if (count == 0) { 17106 pw.println(prefix + "No configured app linkages."); 17107 pw.println(); 17108 } 17109 } 17110 } 17111 } 17112 } 17113 17114 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17115 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17116 if (packageName == null && permissionNames == null) { 17117 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17118 if (iperm == 0) { 17119 if (dumpState.onTitlePrinted()) 17120 pw.println(); 17121 pw.println("AppOp Permissions:"); 17122 } 17123 pw.print(" AppOp Permission "); 17124 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17125 pw.println(":"); 17126 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17127 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17128 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17129 } 17130 } 17131 } 17132 } 17133 17134 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17135 boolean printedSomething = false; 17136 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17137 if (packageName != null && !packageName.equals(p.info.packageName)) { 17138 continue; 17139 } 17140 if (!printedSomething) { 17141 if (dumpState.onTitlePrinted()) 17142 pw.println(); 17143 pw.println("Registered ContentProviders:"); 17144 printedSomething = true; 17145 } 17146 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17147 pw.print(" "); pw.println(p.toString()); 17148 } 17149 printedSomething = false; 17150 for (Map.Entry<String, PackageParser.Provider> entry : 17151 mProvidersByAuthority.entrySet()) { 17152 PackageParser.Provider p = entry.getValue(); 17153 if (packageName != null && !packageName.equals(p.info.packageName)) { 17154 continue; 17155 } 17156 if (!printedSomething) { 17157 if (dumpState.onTitlePrinted()) 17158 pw.println(); 17159 pw.println("ContentProvider Authorities:"); 17160 printedSomething = true; 17161 } 17162 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17163 pw.print(" "); pw.println(p.toString()); 17164 if (p.info != null && p.info.applicationInfo != null) { 17165 final String appInfo = p.info.applicationInfo.toString(); 17166 pw.print(" applicationInfo="); pw.println(appInfo); 17167 } 17168 } 17169 } 17170 17171 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17172 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17173 } 17174 17175 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17176 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17177 } 17178 17179 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17180 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17181 } 17182 17183 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17184 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17185 } 17186 17187 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17188 // XXX should handle packageName != null by dumping only install data that 17189 // the given package is involved with. 17190 if (dumpState.onTitlePrinted()) pw.println(); 17191 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17192 } 17193 17194 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 17195 if (dumpState.onTitlePrinted()) pw.println(); 17196 mSettings.dumpReadMessagesLPr(pw, dumpState); 17197 17198 pw.println(); 17199 pw.println("Package warning messages:"); 17200 BufferedReader in = null; 17201 String line = null; 17202 try { 17203 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17204 while ((line = in.readLine()) != null) { 17205 if (line.contains("ignored: updated version")) continue; 17206 pw.println(line); 17207 } 17208 } catch (IOException ignored) { 17209 } finally { 17210 IoUtils.closeQuietly(in); 17211 } 17212 } 17213 17214 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 17215 BufferedReader in = null; 17216 String line = null; 17217 try { 17218 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17219 while ((line = in.readLine()) != null) { 17220 if (line.contains("ignored: updated version")) continue; 17221 pw.print("msg,"); 17222 pw.println(line); 17223 } 17224 } catch (IOException ignored) { 17225 } finally { 17226 IoUtils.closeQuietly(in); 17227 } 17228 } 17229 } 17230 } 17231 17232 private String dumpDomainString(String packageName) { 17233 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 17234 List<IntentFilter> filters = getAllIntentFilters(packageName); 17235 17236 ArraySet<String> result = new ArraySet<>(); 17237 if (iviList.size() > 0) { 17238 for (IntentFilterVerificationInfo ivi : iviList) { 17239 for (String host : ivi.getDomains()) { 17240 result.add(host); 17241 } 17242 } 17243 } 17244 if (filters != null && filters.size() > 0) { 17245 for (IntentFilter filter : filters) { 17246 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 17247 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 17248 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 17249 result.addAll(filter.getHostsList()); 17250 } 17251 } 17252 } 17253 17254 StringBuilder sb = new StringBuilder(result.size() * 16); 17255 for (String domain : result) { 17256 if (sb.length() > 0) sb.append(" "); 17257 sb.append(domain); 17258 } 17259 return sb.toString(); 17260 } 17261 17262 // ------- apps on sdcard specific code ------- 17263 static final boolean DEBUG_SD_INSTALL = false; 17264 17265 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 17266 17267 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 17268 17269 private boolean mMediaMounted = false; 17270 17271 static String getEncryptKey() { 17272 try { 17273 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 17274 SD_ENCRYPTION_KEYSTORE_NAME); 17275 if (sdEncKey == null) { 17276 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 17277 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 17278 if (sdEncKey == null) { 17279 Slog.e(TAG, "Failed to create encryption keys"); 17280 return null; 17281 } 17282 } 17283 return sdEncKey; 17284 } catch (NoSuchAlgorithmException nsae) { 17285 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 17286 return null; 17287 } catch (IOException ioe) { 17288 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 17289 return null; 17290 } 17291 } 17292 17293 /* 17294 * Update media status on PackageManager. 17295 */ 17296 @Override 17297 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 17298 int callingUid = Binder.getCallingUid(); 17299 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 17300 throw new SecurityException("Media status can only be updated by the system"); 17301 } 17302 // reader; this apparently protects mMediaMounted, but should probably 17303 // be a different lock in that case. 17304 synchronized (mPackages) { 17305 Log.i(TAG, "Updating external media status from " 17306 + (mMediaMounted ? "mounted" : "unmounted") + " to " 17307 + (mediaStatus ? "mounted" : "unmounted")); 17308 if (DEBUG_SD_INSTALL) 17309 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 17310 + ", mMediaMounted=" + mMediaMounted); 17311 if (mediaStatus == mMediaMounted) { 17312 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 17313 : 0, -1); 17314 mHandler.sendMessage(msg); 17315 return; 17316 } 17317 mMediaMounted = mediaStatus; 17318 } 17319 // Queue up an async operation since the package installation may take a 17320 // little while. 17321 mHandler.post(new Runnable() { 17322 public void run() { 17323 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 17324 } 17325 }); 17326 } 17327 17328 /** 17329 * Called by MountService when the initial ASECs to scan are available. 17330 * Should block until all the ASEC containers are finished being scanned. 17331 */ 17332 public void scanAvailableAsecs() { 17333 updateExternalMediaStatusInner(true, false, false); 17334 } 17335 17336 /* 17337 * Collect information of applications on external media, map them against 17338 * existing containers and update information based on current mount status. 17339 * Please note that we always have to report status if reportStatus has been 17340 * set to true especially when unloading packages. 17341 */ 17342 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 17343 boolean externalStorage) { 17344 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 17345 int[] uidArr = EmptyArray.INT; 17346 17347 final String[] list = PackageHelper.getSecureContainerList(); 17348 if (ArrayUtils.isEmpty(list)) { 17349 Log.i(TAG, "No secure containers found"); 17350 } else { 17351 // Process list of secure containers and categorize them 17352 // as active or stale based on their package internal state. 17353 17354 // reader 17355 synchronized (mPackages) { 17356 for (String cid : list) { 17357 // Leave stages untouched for now; installer service owns them 17358 if (PackageInstallerService.isStageName(cid)) continue; 17359 17360 if (DEBUG_SD_INSTALL) 17361 Log.i(TAG, "Processing container " + cid); 17362 String pkgName = getAsecPackageName(cid); 17363 if (pkgName == null) { 17364 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 17365 continue; 17366 } 17367 if (DEBUG_SD_INSTALL) 17368 Log.i(TAG, "Looking for pkg : " + pkgName); 17369 17370 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17371 if (ps == null) { 17372 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 17373 continue; 17374 } 17375 17376 /* 17377 * Skip packages that are not external if we're unmounting 17378 * external storage. 17379 */ 17380 if (externalStorage && !isMounted && !isExternal(ps)) { 17381 continue; 17382 } 17383 17384 final AsecInstallArgs args = new AsecInstallArgs(cid, 17385 getAppDexInstructionSets(ps), ps.isForwardLocked()); 17386 // The package status is changed only if the code path 17387 // matches between settings and the container id. 17388 if (ps.codePathString != null 17389 && ps.codePathString.startsWith(args.getCodePath())) { 17390 if (DEBUG_SD_INSTALL) { 17391 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 17392 + " at code path: " + ps.codePathString); 17393 } 17394 17395 // We do have a valid package installed on sdcard 17396 processCids.put(args, ps.codePathString); 17397 final int uid = ps.appId; 17398 if (uid != -1) { 17399 uidArr = ArrayUtils.appendInt(uidArr, uid); 17400 } 17401 } else { 17402 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 17403 + ps.codePathString); 17404 } 17405 } 17406 } 17407 17408 Arrays.sort(uidArr); 17409 } 17410 17411 // Process packages with valid entries. 17412 if (isMounted) { 17413 if (DEBUG_SD_INSTALL) 17414 Log.i(TAG, "Loading packages"); 17415 loadMediaPackages(processCids, uidArr, externalStorage); 17416 startCleaningPackages(); 17417 mInstallerService.onSecureContainersAvailable(); 17418 } else { 17419 if (DEBUG_SD_INSTALL) 17420 Log.i(TAG, "Unloading packages"); 17421 unloadMediaPackages(processCids, uidArr, reportStatus); 17422 } 17423 } 17424 17425 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17426 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 17427 final int size = infos.size(); 17428 final String[] packageNames = new String[size]; 17429 final int[] packageUids = new int[size]; 17430 for (int i = 0; i < size; i++) { 17431 final ApplicationInfo info = infos.get(i); 17432 packageNames[i] = info.packageName; 17433 packageUids[i] = info.uid; 17434 } 17435 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 17436 finishedReceiver); 17437 } 17438 17439 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17440 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17441 sendResourcesChangedBroadcast(mediaStatus, replacing, 17442 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 17443 } 17444 17445 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17446 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17447 int size = pkgList.length; 17448 if (size > 0) { 17449 // Send broadcasts here 17450 Bundle extras = new Bundle(); 17451 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 17452 if (uidArr != null) { 17453 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 17454 } 17455 if (replacing) { 17456 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 17457 } 17458 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 17459 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 17460 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 17461 } 17462 } 17463 17464 /* 17465 * Look at potentially valid container ids from processCids If package 17466 * information doesn't match the one on record or package scanning fails, 17467 * the cid is added to list of removeCids. We currently don't delete stale 17468 * containers. 17469 */ 17470 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 17471 boolean externalStorage) { 17472 ArrayList<String> pkgList = new ArrayList<String>(); 17473 Set<AsecInstallArgs> keys = processCids.keySet(); 17474 17475 for (AsecInstallArgs args : keys) { 17476 String codePath = processCids.get(args); 17477 if (DEBUG_SD_INSTALL) 17478 Log.i(TAG, "Loading container : " + args.cid); 17479 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17480 try { 17481 // Make sure there are no container errors first. 17482 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 17483 Slog.e(TAG, "Failed to mount cid : " + args.cid 17484 + " when installing from sdcard"); 17485 continue; 17486 } 17487 // Check code path here. 17488 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 17489 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 17490 + " does not match one in settings " + codePath); 17491 continue; 17492 } 17493 // Parse package 17494 int parseFlags = mDefParseFlags; 17495 if (args.isExternalAsec()) { 17496 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 17497 } 17498 if (args.isFwdLocked()) { 17499 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 17500 } 17501 17502 synchronized (mInstallLock) { 17503 PackageParser.Package pkg = null; 17504 try { 17505 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 17506 } catch (PackageManagerException e) { 17507 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 17508 } 17509 // Scan the package 17510 if (pkg != null) { 17511 /* 17512 * TODO why is the lock being held? doPostInstall is 17513 * called in other places without the lock. This needs 17514 * to be straightened out. 17515 */ 17516 // writer 17517 synchronized (mPackages) { 17518 retCode = PackageManager.INSTALL_SUCCEEDED; 17519 pkgList.add(pkg.packageName); 17520 // Post process args 17521 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 17522 pkg.applicationInfo.uid); 17523 } 17524 } else { 17525 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 17526 } 17527 } 17528 17529 } finally { 17530 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 17531 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 17532 } 17533 } 17534 } 17535 // writer 17536 synchronized (mPackages) { 17537 // If the platform SDK has changed since the last time we booted, 17538 // we need to re-grant app permission to catch any new ones that 17539 // appear. This is really a hack, and means that apps can in some 17540 // cases get permissions that the user didn't initially explicitly 17541 // allow... it would be nice to have some better way to handle 17542 // this situation. 17543 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 17544 : mSettings.getInternalVersion(); 17545 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 17546 : StorageManager.UUID_PRIVATE_INTERNAL; 17547 17548 int updateFlags = UPDATE_PERMISSIONS_ALL; 17549 if (ver.sdkVersion != mSdkVersion) { 17550 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17551 + mSdkVersion + "; regranting permissions for external"); 17552 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17553 } 17554 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17555 17556 // Yay, everything is now upgraded 17557 ver.forceCurrent(); 17558 17559 // can downgrade to reader 17560 // Persist settings 17561 mSettings.writeLPr(); 17562 } 17563 // Send a broadcast to let everyone know we are done processing 17564 if (pkgList.size() > 0) { 17565 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 17566 } 17567 } 17568 17569 /* 17570 * Utility method to unload a list of specified containers 17571 */ 17572 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 17573 // Just unmount all valid containers. 17574 for (AsecInstallArgs arg : cidArgs) { 17575 synchronized (mInstallLock) { 17576 arg.doPostDeleteLI(false); 17577 } 17578 } 17579 } 17580 17581 /* 17582 * Unload packages mounted on external media. This involves deleting package 17583 * data from internal structures, sending broadcasts about disabled packages, 17584 * gc'ing to free up references, unmounting all secure containers 17585 * corresponding to packages on external media, and posting a 17586 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 17587 * that we always have to post this message if status has been requested no 17588 * matter what. 17589 */ 17590 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 17591 final boolean reportStatus) { 17592 if (DEBUG_SD_INSTALL) 17593 Log.i(TAG, "unloading media packages"); 17594 ArrayList<String> pkgList = new ArrayList<String>(); 17595 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 17596 final Set<AsecInstallArgs> keys = processCids.keySet(); 17597 for (AsecInstallArgs args : keys) { 17598 String pkgName = args.getPackageName(); 17599 if (DEBUG_SD_INSTALL) 17600 Log.i(TAG, "Trying to unload pkg : " + pkgName); 17601 // Delete package internally 17602 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17603 synchronized (mInstallLock) { 17604 boolean res = deletePackageLI(pkgName, null, false, null, 17605 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 17606 if (res) { 17607 pkgList.add(pkgName); 17608 } else { 17609 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 17610 failedList.add(args); 17611 } 17612 } 17613 } 17614 17615 // reader 17616 synchronized (mPackages) { 17617 // We didn't update the settings after removing each package; 17618 // write them now for all packages. 17619 mSettings.writeLPr(); 17620 } 17621 17622 // We have to absolutely send UPDATED_MEDIA_STATUS only 17623 // after confirming that all the receivers processed the ordered 17624 // broadcast when packages get disabled, force a gc to clean things up. 17625 // and unload all the containers. 17626 if (pkgList.size() > 0) { 17627 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 17628 new IIntentReceiver.Stub() { 17629 public void performReceive(Intent intent, int resultCode, String data, 17630 Bundle extras, boolean ordered, boolean sticky, 17631 int sendingUser) throws RemoteException { 17632 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 17633 reportStatus ? 1 : 0, 1, keys); 17634 mHandler.sendMessage(msg); 17635 } 17636 }); 17637 } else { 17638 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 17639 keys); 17640 mHandler.sendMessage(msg); 17641 } 17642 } 17643 17644 private void loadPrivatePackages(final VolumeInfo vol) { 17645 mHandler.post(new Runnable() { 17646 @Override 17647 public void run() { 17648 loadPrivatePackagesInner(vol); 17649 } 17650 }); 17651 } 17652 17653 private void loadPrivatePackagesInner(VolumeInfo vol) { 17654 final String volumeUuid = vol.fsUuid; 17655 if (TextUtils.isEmpty(volumeUuid)) { 17656 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 17657 return; 17658 } 17659 17660 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 17661 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 17662 17663 final VersionInfo ver; 17664 final List<PackageSetting> packages; 17665 synchronized (mPackages) { 17666 ver = mSettings.findOrCreateVersion(volumeUuid); 17667 packages = mSettings.getVolumePackagesLPr(volumeUuid); 17668 } 17669 17670 // TODO: introduce a new concept similar to "frozen" to prevent these 17671 // apps from being launched until after data has been fully reconciled 17672 for (PackageSetting ps : packages) { 17673 synchronized (mInstallLock) { 17674 final PackageParser.Package pkg; 17675 try { 17676 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 17677 loaded.add(pkg.applicationInfo); 17678 17679 } catch (PackageManagerException e) { 17680 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 17681 } 17682 17683 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 17684 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 17685 } 17686 } 17687 } 17688 17689 // Reconcile app data for all started/unlocked users 17690 final StorageManager sm = mContext.getSystemService(StorageManager.class); 17691 final UserManager um = mContext.getSystemService(UserManager.class); 17692 for (UserInfo user : um.getUsers()) { 17693 final int flags; 17694 if (um.isUserUnlocked(user.id)) { 17695 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17696 } else if (um.isUserRunning(user.id)) { 17697 flags = StorageManager.FLAG_STORAGE_DE; 17698 } else { 17699 continue; 17700 } 17701 17702 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 17703 reconcileAppsData(volumeUuid, user.id, flags); 17704 } 17705 17706 synchronized (mPackages) { 17707 int updateFlags = UPDATE_PERMISSIONS_ALL; 17708 if (ver.sdkVersion != mSdkVersion) { 17709 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17710 + mSdkVersion + "; regranting permissions for " + volumeUuid); 17711 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17712 } 17713 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17714 17715 // Yay, everything is now upgraded 17716 ver.forceCurrent(); 17717 17718 mSettings.writeLPr(); 17719 } 17720 17721 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 17722 sendResourcesChangedBroadcast(true, false, loaded, null); 17723 } 17724 17725 private void unloadPrivatePackages(final VolumeInfo vol) { 17726 mHandler.post(new Runnable() { 17727 @Override 17728 public void run() { 17729 unloadPrivatePackagesInner(vol); 17730 } 17731 }); 17732 } 17733 17734 private void unloadPrivatePackagesInner(VolumeInfo vol) { 17735 final String volumeUuid = vol.fsUuid; 17736 if (TextUtils.isEmpty(volumeUuid)) { 17737 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 17738 return; 17739 } 17740 17741 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 17742 synchronized (mInstallLock) { 17743 synchronized (mPackages) { 17744 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 17745 for (PackageSetting ps : packages) { 17746 if (ps.pkg == null) continue; 17747 17748 final ApplicationInfo info = ps.pkg.applicationInfo; 17749 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17750 if (deletePackageLI(ps.name, null, false, null, 17751 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 17752 unloaded.add(info); 17753 } else { 17754 Slog.w(TAG, "Failed to unload " + ps.codePath); 17755 } 17756 } 17757 17758 mSettings.writeLPr(); 17759 } 17760 } 17761 17762 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 17763 sendResourcesChangedBroadcast(false, false, unloaded, null); 17764 } 17765 17766 /** 17767 * Examine all users present on given mounted volume, and destroy data 17768 * belonging to users that are no longer valid, or whose user ID has been 17769 * recycled. 17770 */ 17771 private void reconcileUsers(String volumeUuid) { 17772 // TODO: also reconcile DE directories 17773 final File[] files = FileUtils 17774 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 17775 for (File file : files) { 17776 if (!file.isDirectory()) continue; 17777 17778 final int userId; 17779 final UserInfo info; 17780 try { 17781 userId = Integer.parseInt(file.getName()); 17782 info = sUserManager.getUserInfo(userId); 17783 } catch (NumberFormatException e) { 17784 Slog.w(TAG, "Invalid user directory " + file); 17785 continue; 17786 } 17787 17788 boolean destroyUser = false; 17789 if (info == null) { 17790 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17791 + " because no matching user was found"); 17792 destroyUser = true; 17793 } else { 17794 try { 17795 UserManagerService.enforceSerialNumber(file, info.serialNumber); 17796 } catch (IOException e) { 17797 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17798 + " because we failed to enforce serial number: " + e); 17799 destroyUser = true; 17800 } 17801 } 17802 17803 if (destroyUser) { 17804 synchronized (mInstallLock) { 17805 try { 17806 mInstaller.removeUserDataDirs(volumeUuid, userId); 17807 } catch (InstallerException e) { 17808 Slog.w(TAG, "Failed to clean up user dirs", e); 17809 } 17810 } 17811 } 17812 } 17813 } 17814 17815 private void assertPackageKnown(String volumeUuid, String packageName) 17816 throws PackageManagerException { 17817 synchronized (mPackages) { 17818 final PackageSetting ps = mSettings.mPackages.get(packageName); 17819 if (ps == null) { 17820 throw new PackageManagerException("Package " + packageName + " is unknown"); 17821 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 17822 throw new PackageManagerException( 17823 "Package " + packageName + " found on unknown volume " + volumeUuid 17824 + "; expected volume " + ps.volumeUuid); 17825 } 17826 } 17827 } 17828 17829 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 17830 throws PackageManagerException { 17831 synchronized (mPackages) { 17832 final PackageSetting ps = mSettings.mPackages.get(packageName); 17833 if (ps == null) { 17834 throw new PackageManagerException("Package " + packageName + " is unknown"); 17835 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 17836 throw new PackageManagerException( 17837 "Package " + packageName + " found on unknown volume " + volumeUuid 17838 + "; expected volume " + ps.volumeUuid); 17839 } else if (!ps.getInstalled(userId)) { 17840 throw new PackageManagerException( 17841 "Package " + packageName + " not installed for user " + userId); 17842 } 17843 } 17844 } 17845 17846 /** 17847 * Examine all apps present on given mounted volume, and destroy apps that 17848 * aren't expected, either due to uninstallation or reinstallation on 17849 * another volume. 17850 */ 17851 private void reconcileApps(String volumeUuid) { 17852 final File[] files = FileUtils 17853 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 17854 for (File file : files) { 17855 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 17856 && !PackageInstallerService.isStageName(file.getName()); 17857 if (!isPackage) { 17858 // Ignore entries which are not packages 17859 continue; 17860 } 17861 17862 try { 17863 final PackageLite pkg = PackageParser.parsePackageLite(file, 17864 PackageParser.PARSE_MUST_BE_APK); 17865 assertPackageKnown(volumeUuid, pkg.packageName); 17866 17867 } catch (PackageParserException | PackageManagerException e) { 17868 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17869 synchronized (mInstallLock) { 17870 removeCodePathLI(file); 17871 } 17872 } 17873 } 17874 } 17875 17876 /** 17877 * Reconcile all app data for the given user. 17878 * <p> 17879 * Verifies that directories exist and that ownership and labeling is 17880 * correct for all installed apps on all mounted volumes. 17881 */ 17882 void reconcileAppsData(int userId, int flags) { 17883 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17884 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 17885 final String volumeUuid = vol.getFsUuid(); 17886 reconcileAppsData(volumeUuid, userId, flags); 17887 } 17888 } 17889 17890 /** 17891 * Reconcile all app data on given mounted volume. 17892 * <p> 17893 * Destroys app data that isn't expected, either due to uninstallation or 17894 * reinstallation on another volume. 17895 * <p> 17896 * Verifies that directories exist and that ownership and labeling is 17897 * correct for all installed apps. 17898 */ 17899 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 17900 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 17901 + Integer.toHexString(flags)); 17902 17903 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 17904 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 17905 17906 boolean restoreconNeeded = false; 17907 17908 // First look for stale data that doesn't belong, and check if things 17909 // have changed since we did our last restorecon 17910 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 17911 if (!isUserKeyUnlocked(userId)) { 17912 throw new RuntimeException( 17913 "Yikes, someone asked us to reconcile CE storage while " + userId 17914 + " was still locked; this would have caused massive data loss!"); 17915 } 17916 17917 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 17918 17919 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 17920 for (File file : files) { 17921 final String packageName = file.getName(); 17922 try { 17923 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 17924 } catch (PackageManagerException e) { 17925 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17926 synchronized (mInstallLock) { 17927 destroyAppDataLI(volumeUuid, packageName, userId, 17928 StorageManager.FLAG_STORAGE_CE); 17929 } 17930 } 17931 } 17932 } 17933 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 17934 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 17935 17936 final File[] files = FileUtils.listFilesOrEmpty(deDir); 17937 for (File file : files) { 17938 final String packageName = file.getName(); 17939 try { 17940 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 17941 } catch (PackageManagerException e) { 17942 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17943 synchronized (mInstallLock) { 17944 destroyAppDataLI(volumeUuid, packageName, userId, 17945 StorageManager.FLAG_STORAGE_DE); 17946 } 17947 } 17948 } 17949 } 17950 17951 // Ensure that data directories are ready to roll for all packages 17952 // installed for this volume and user 17953 final List<PackageSetting> packages; 17954 synchronized (mPackages) { 17955 packages = mSettings.getVolumePackagesLPr(volumeUuid); 17956 } 17957 int preparedCount = 0; 17958 for (PackageSetting ps : packages) { 17959 final String packageName = ps.name; 17960 if (ps.pkg == null) { 17961 Slog.w(TAG, "Odd, missing scanned package " + packageName); 17962 // TODO: might be due to legacy ASEC apps; we should circle back 17963 // and reconcile again once they're scanned 17964 continue; 17965 } 17966 17967 if (ps.getInstalled(userId)) { 17968 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 17969 preparedCount++; 17970 } 17971 } 17972 17973 if (restoreconNeeded) { 17974 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 17975 SELinuxMMAC.setRestoreconDone(ceDir); 17976 } 17977 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 17978 SELinuxMMAC.setRestoreconDone(deDir); 17979 } 17980 } 17981 17982 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 17983 + " packages; restoreconNeeded was " + restoreconNeeded); 17984 } 17985 17986 /** 17987 * Prepare app data for the given app just after it was installed or 17988 * upgraded. This method carefully only touches users that it's installed 17989 * for, and it forces a restorecon to handle any seinfo changes. 17990 * <p> 17991 * Verifies that directories exist and that ownership and labeling is 17992 * correct for all installed apps. If there is an ownership mismatch, it 17993 * will try recovering system apps by wiping data; third-party app data is 17994 * left intact. 17995 */ 17996 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 17997 prepareAppDataAfterInstallInternal(pkg); 17998 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17999 for (int i = 0; i < childCount; i++) { 18000 PackageParser.Package childPackage = pkg.childPackages.get(i); 18001 prepareAppDataAfterInstallInternal(childPackage); 18002 } 18003 } 18004 18005 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 18006 final PackageSetting ps; 18007 synchronized (mPackages) { 18008 ps = mSettings.mPackages.get(pkg.packageName); 18009 } 18010 18011 final UserManager um = mContext.getSystemService(UserManager.class); 18012 for (UserInfo user : um.getUsers()) { 18013 final int flags; 18014 if (um.isUserUnlocked(user.id)) { 18015 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18016 } else if (um.isUserRunning(user.id)) { 18017 flags = StorageManager.FLAG_STORAGE_DE; 18018 } else { 18019 continue; 18020 } 18021 18022 if (ps.getInstalled(user.id)) { 18023 // Whenever an app changes, force a restorecon of its data 18024 // TODO: when user data is locked, mark that we're still dirty 18025 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 18026 } 18027 } 18028 } 18029 18030 /** 18031 * Prepare app data for the given app. 18032 * <p> 18033 * Verifies that directories exist and that ownership and labeling is 18034 * correct for all installed apps. If there is an ownership mismatch, this 18035 * will try recovering system apps by wiping data; third-party app data is 18036 * left intact. 18037 */ 18038 private void prepareAppData(String volumeUuid, int userId, int flags, 18039 PackageParser.Package pkg, boolean restoreconNeeded) { 18040 if (DEBUG_APP_DATA) { 18041 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18042 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18043 } 18044 18045 final String packageName = pkg.packageName; 18046 final ApplicationInfo app = pkg.applicationInfo; 18047 final int appId = UserHandle.getAppId(app.uid); 18048 18049 Preconditions.checkNotNull(app.seinfo); 18050 18051 synchronized (mInstallLock) { 18052 try { 18053 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18054 appId, app.seinfo, app.targetSdkVersion); 18055 } catch (InstallerException e) { 18056 if (app.isSystemApp()) { 18057 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18058 + ", but trying to recover: " + e); 18059 destroyAppDataLI(volumeUuid, packageName, userId, flags); 18060 try { 18061 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18062 appId, app.seinfo, app.targetSdkVersion); 18063 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18064 } catch (InstallerException e2) { 18065 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18066 } 18067 } else { 18068 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18069 } 18070 } 18071 18072 if (restoreconNeeded) { 18073 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18074 } 18075 18076 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18077 // Create a native library symlink only if we have native libraries 18078 // and if the native libraries are 32 bit libraries. We do not provide 18079 // this symlink for 64 bit libraries. 18080 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18081 final String nativeLibPath = app.nativeLibraryDir; 18082 try { 18083 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18084 nativeLibPath, userId); 18085 } catch (InstallerException e) { 18086 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18087 } 18088 } 18089 } 18090 } 18091 } 18092 18093 private void unfreezePackage(String packageName) { 18094 synchronized (mPackages) { 18095 final PackageSetting ps = mSettings.mPackages.get(packageName); 18096 if (ps != null) { 18097 ps.frozen = false; 18098 } 18099 } 18100 } 18101 18102 @Override 18103 public int movePackage(final String packageName, final String volumeUuid) { 18104 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18105 18106 final int moveId = mNextMoveId.getAndIncrement(); 18107 mHandler.post(new Runnable() { 18108 @Override 18109 public void run() { 18110 try { 18111 movePackageInternal(packageName, volumeUuid, moveId); 18112 } catch (PackageManagerException e) { 18113 Slog.w(TAG, "Failed to move " + packageName, e); 18114 mMoveCallbacks.notifyStatusChanged(moveId, 18115 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18116 } 18117 } 18118 }); 18119 return moveId; 18120 } 18121 18122 private void movePackageInternal(final String packageName, final String volumeUuid, 18123 final int moveId) throws PackageManagerException { 18124 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 18125 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18126 final PackageManager pm = mContext.getPackageManager(); 18127 18128 final boolean currentAsec; 18129 final String currentVolumeUuid; 18130 final File codeFile; 18131 final String installerPackageName; 18132 final String packageAbiOverride; 18133 final int appId; 18134 final String seinfo; 18135 final String label; 18136 final int targetSdkVersion; 18137 18138 // reader 18139 synchronized (mPackages) { 18140 final PackageParser.Package pkg = mPackages.get(packageName); 18141 final PackageSetting ps = mSettings.mPackages.get(packageName); 18142 if (pkg == null || ps == null) { 18143 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 18144 } 18145 18146 if (pkg.applicationInfo.isSystemApp()) { 18147 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 18148 "Cannot move system application"); 18149 } 18150 18151 if (pkg.applicationInfo.isExternalAsec()) { 18152 currentAsec = true; 18153 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 18154 } else if (pkg.applicationInfo.isForwardLocked()) { 18155 currentAsec = true; 18156 currentVolumeUuid = "forward_locked"; 18157 } else { 18158 currentAsec = false; 18159 currentVolumeUuid = ps.volumeUuid; 18160 18161 final File probe = new File(pkg.codePath); 18162 final File probeOat = new File(probe, "oat"); 18163 if (!probe.isDirectory() || !probeOat.isDirectory()) { 18164 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18165 "Move only supported for modern cluster style installs"); 18166 } 18167 } 18168 18169 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 18170 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18171 "Package already moved to " + volumeUuid); 18172 } 18173 18174 if (ps.frozen) { 18175 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 18176 "Failed to move already frozen package"); 18177 } 18178 ps.frozen = true; 18179 18180 codeFile = new File(pkg.codePath); 18181 installerPackageName = ps.installerPackageName; 18182 packageAbiOverride = ps.cpuAbiOverrideString; 18183 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18184 seinfo = pkg.applicationInfo.seinfo; 18185 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 18186 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 18187 } 18188 18189 // Now that we're guarded by frozen state, kill app during move 18190 final long token = Binder.clearCallingIdentity(); 18191 try { 18192 killApplication(packageName, appId, "move pkg"); 18193 } finally { 18194 Binder.restoreCallingIdentity(token); 18195 } 18196 18197 final Bundle extras = new Bundle(); 18198 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 18199 extras.putString(Intent.EXTRA_TITLE, label); 18200 mMoveCallbacks.notifyCreated(moveId, extras); 18201 18202 int installFlags; 18203 final boolean moveCompleteApp; 18204 final File measurePath; 18205 18206 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 18207 installFlags = INSTALL_INTERNAL; 18208 moveCompleteApp = !currentAsec; 18209 measurePath = Environment.getDataAppDirectory(volumeUuid); 18210 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 18211 installFlags = INSTALL_EXTERNAL; 18212 moveCompleteApp = false; 18213 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 18214 } else { 18215 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 18216 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 18217 || !volume.isMountedWritable()) { 18218 unfreezePackage(packageName); 18219 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18220 "Move location not mounted private volume"); 18221 } 18222 18223 Preconditions.checkState(!currentAsec); 18224 18225 installFlags = INSTALL_INTERNAL; 18226 moveCompleteApp = true; 18227 measurePath = Environment.getDataAppDirectory(volumeUuid); 18228 } 18229 18230 final PackageStats stats = new PackageStats(null, -1); 18231 synchronized (mInstaller) { 18232 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 18233 unfreezePackage(packageName); 18234 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18235 "Failed to measure package size"); 18236 } 18237 } 18238 18239 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 18240 + stats.dataSize); 18241 18242 final long startFreeBytes = measurePath.getFreeSpace(); 18243 final long sizeBytes; 18244 if (moveCompleteApp) { 18245 sizeBytes = stats.codeSize + stats.dataSize; 18246 } else { 18247 sizeBytes = stats.codeSize; 18248 } 18249 18250 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 18251 unfreezePackage(packageName); 18252 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18253 "Not enough free space to move"); 18254 } 18255 18256 mMoveCallbacks.notifyStatusChanged(moveId, 10); 18257 18258 final CountDownLatch installedLatch = new CountDownLatch(1); 18259 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 18260 @Override 18261 public void onUserActionRequired(Intent intent) throws RemoteException { 18262 throw new IllegalStateException(); 18263 } 18264 18265 @Override 18266 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 18267 Bundle extras) throws RemoteException { 18268 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 18269 + PackageManager.installStatusToString(returnCode, msg)); 18270 18271 installedLatch.countDown(); 18272 18273 // Regardless of success or failure of the move operation, 18274 // always unfreeze the package 18275 unfreezePackage(packageName); 18276 18277 final int status = PackageManager.installStatusToPublicStatus(returnCode); 18278 switch (status) { 18279 case PackageInstaller.STATUS_SUCCESS: 18280 mMoveCallbacks.notifyStatusChanged(moveId, 18281 PackageManager.MOVE_SUCCEEDED); 18282 break; 18283 case PackageInstaller.STATUS_FAILURE_STORAGE: 18284 mMoveCallbacks.notifyStatusChanged(moveId, 18285 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 18286 break; 18287 default: 18288 mMoveCallbacks.notifyStatusChanged(moveId, 18289 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18290 break; 18291 } 18292 } 18293 }; 18294 18295 final MoveInfo move; 18296 if (moveCompleteApp) { 18297 // Kick off a thread to report progress estimates 18298 new Thread() { 18299 @Override 18300 public void run() { 18301 while (true) { 18302 try { 18303 if (installedLatch.await(1, TimeUnit.SECONDS)) { 18304 break; 18305 } 18306 } catch (InterruptedException ignored) { 18307 } 18308 18309 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 18310 final int progress = 10 + (int) MathUtils.constrain( 18311 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 18312 mMoveCallbacks.notifyStatusChanged(moveId, progress); 18313 } 18314 } 18315 }.start(); 18316 18317 final String dataAppName = codeFile.getName(); 18318 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 18319 dataAppName, appId, seinfo, targetSdkVersion); 18320 } else { 18321 move = null; 18322 } 18323 18324 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 18325 18326 final Message msg = mHandler.obtainMessage(INIT_COPY); 18327 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 18328 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 18329 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 18330 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 18331 msg.obj = params; 18332 18333 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 18334 System.identityHashCode(msg.obj)); 18335 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 18336 System.identityHashCode(msg.obj)); 18337 18338 mHandler.sendMessage(msg); 18339 } 18340 18341 @Override 18342 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 18343 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18344 18345 final int realMoveId = mNextMoveId.getAndIncrement(); 18346 final Bundle extras = new Bundle(); 18347 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 18348 mMoveCallbacks.notifyCreated(realMoveId, extras); 18349 18350 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 18351 @Override 18352 public void onCreated(int moveId, Bundle extras) { 18353 // Ignored 18354 } 18355 18356 @Override 18357 public void onStatusChanged(int moveId, int status, long estMillis) { 18358 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 18359 } 18360 }; 18361 18362 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18363 storage.setPrimaryStorageUuid(volumeUuid, callback); 18364 return realMoveId; 18365 } 18366 18367 @Override 18368 public int getMoveStatus(int moveId) { 18369 mContext.enforceCallingOrSelfPermission( 18370 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18371 return mMoveCallbacks.mLastStatus.get(moveId); 18372 } 18373 18374 @Override 18375 public void registerMoveCallback(IPackageMoveObserver callback) { 18376 mContext.enforceCallingOrSelfPermission( 18377 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18378 mMoveCallbacks.register(callback); 18379 } 18380 18381 @Override 18382 public void unregisterMoveCallback(IPackageMoveObserver callback) { 18383 mContext.enforceCallingOrSelfPermission( 18384 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18385 mMoveCallbacks.unregister(callback); 18386 } 18387 18388 @Override 18389 public boolean setInstallLocation(int loc) { 18390 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 18391 null); 18392 if (getInstallLocation() == loc) { 18393 return true; 18394 } 18395 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 18396 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 18397 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 18398 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 18399 return true; 18400 } 18401 return false; 18402 } 18403 18404 @Override 18405 public int getInstallLocation() { 18406 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 18407 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 18408 PackageHelper.APP_INSTALL_AUTO); 18409 } 18410 18411 /** Called by UserManagerService */ 18412 void cleanUpUser(UserManagerService userManager, int userHandle) { 18413 synchronized (mPackages) { 18414 mDirtyUsers.remove(userHandle); 18415 mUserNeedsBadging.delete(userHandle); 18416 mSettings.removeUserLPw(userHandle); 18417 mPendingBroadcasts.remove(userHandle); 18418 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 18419 } 18420 synchronized (mInstallLock) { 18421 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18422 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18423 final String volumeUuid = vol.getFsUuid(); 18424 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 18425 try { 18426 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 18427 } catch (InstallerException e) { 18428 Slog.w(TAG, "Failed to remove user data", e); 18429 } 18430 } 18431 synchronized (mPackages) { 18432 removeUnusedPackagesLILPw(userManager, userHandle); 18433 } 18434 } 18435 } 18436 18437 /** 18438 * We're removing userHandle and would like to remove any downloaded packages 18439 * that are no longer in use by any other user. 18440 * @param userHandle the user being removed 18441 */ 18442 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 18443 final boolean DEBUG_CLEAN_APKS = false; 18444 int [] users = userManager.getUserIds(); 18445 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 18446 while (psit.hasNext()) { 18447 PackageSetting ps = psit.next(); 18448 if (ps.pkg == null) { 18449 continue; 18450 } 18451 final String packageName = ps.pkg.packageName; 18452 // Skip over if system app 18453 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 18454 continue; 18455 } 18456 if (DEBUG_CLEAN_APKS) { 18457 Slog.i(TAG, "Checking package " + packageName); 18458 } 18459 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 18460 if (keep) { 18461 if (DEBUG_CLEAN_APKS) { 18462 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 18463 } 18464 } else { 18465 for (int i = 0; i < users.length; i++) { 18466 if (users[i] != userHandle && ps.getInstalled(users[i])) { 18467 keep = true; 18468 if (DEBUG_CLEAN_APKS) { 18469 Slog.i(TAG, " Keeping package " + packageName + " for user " 18470 + users[i]); 18471 } 18472 break; 18473 } 18474 } 18475 } 18476 if (!keep) { 18477 if (DEBUG_CLEAN_APKS) { 18478 Slog.i(TAG, " Removing package " + packageName); 18479 } 18480 mHandler.post(new Runnable() { 18481 public void run() { 18482 deletePackageX(packageName, userHandle, 0); 18483 } //end run 18484 }); 18485 } 18486 } 18487 } 18488 18489 /** Called by UserManagerService */ 18490 void createNewUser(int userHandle) { 18491 synchronized (mInstallLock) { 18492 try { 18493 mInstaller.createUserConfig(userHandle); 18494 } catch (InstallerException e) { 18495 Slog.w(TAG, "Failed to create user config", e); 18496 } 18497 mSettings.createNewUserLI(this, mInstaller, userHandle); 18498 } 18499 synchronized (mPackages) { 18500 applyFactoryDefaultBrowserLPw(userHandle); 18501 primeDomainVerificationsLPw(userHandle); 18502 } 18503 } 18504 18505 void newUserCreated(final int userHandle) { 18506 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 18507 // If permission review for legacy apps is required, we represent 18508 // dagerous permissions for such apps as always granted runtime 18509 // permissions to keep per user flag state whether review is needed. 18510 // Hence, if a new user is added we have to propagate dangerous 18511 // permission grants for these legacy apps. 18512 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 18513 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 18514 | UPDATE_PERMISSIONS_REPLACE_ALL); 18515 } 18516 } 18517 18518 @Override 18519 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 18520 mContext.enforceCallingOrSelfPermission( 18521 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 18522 "Only package verification agents can read the verifier device identity"); 18523 18524 synchronized (mPackages) { 18525 return mSettings.getVerifierDeviceIdentityLPw(); 18526 } 18527 } 18528 18529 @Override 18530 public void setPermissionEnforced(String permission, boolean enforced) { 18531 // TODO: Now that we no longer change GID for storage, this should to away. 18532 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 18533 "setPermissionEnforced"); 18534 if (READ_EXTERNAL_STORAGE.equals(permission)) { 18535 synchronized (mPackages) { 18536 if (mSettings.mReadExternalStorageEnforced == null 18537 || mSettings.mReadExternalStorageEnforced != enforced) { 18538 mSettings.mReadExternalStorageEnforced = enforced; 18539 mSettings.writeLPr(); 18540 } 18541 } 18542 // kill any non-foreground processes so we restart them and 18543 // grant/revoke the GID. 18544 final IActivityManager am = ActivityManagerNative.getDefault(); 18545 if (am != null) { 18546 final long token = Binder.clearCallingIdentity(); 18547 try { 18548 am.killProcessesBelowForeground("setPermissionEnforcement"); 18549 } catch (RemoteException e) { 18550 } finally { 18551 Binder.restoreCallingIdentity(token); 18552 } 18553 } 18554 } else { 18555 throw new IllegalArgumentException("No selective enforcement for " + permission); 18556 } 18557 } 18558 18559 @Override 18560 @Deprecated 18561 public boolean isPermissionEnforced(String permission) { 18562 return true; 18563 } 18564 18565 @Override 18566 public boolean isStorageLow() { 18567 final long token = Binder.clearCallingIdentity(); 18568 try { 18569 final DeviceStorageMonitorInternal 18570 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 18571 if (dsm != null) { 18572 return dsm.isMemoryLow(); 18573 } else { 18574 return false; 18575 } 18576 } finally { 18577 Binder.restoreCallingIdentity(token); 18578 } 18579 } 18580 18581 @Override 18582 public IPackageInstaller getPackageInstaller() { 18583 return mInstallerService; 18584 } 18585 18586 private boolean userNeedsBadging(int userId) { 18587 int index = mUserNeedsBadging.indexOfKey(userId); 18588 if (index < 0) { 18589 final UserInfo userInfo; 18590 final long token = Binder.clearCallingIdentity(); 18591 try { 18592 userInfo = sUserManager.getUserInfo(userId); 18593 } finally { 18594 Binder.restoreCallingIdentity(token); 18595 } 18596 final boolean b; 18597 if (userInfo != null && userInfo.isManagedProfile()) { 18598 b = true; 18599 } else { 18600 b = false; 18601 } 18602 mUserNeedsBadging.put(userId, b); 18603 return b; 18604 } 18605 return mUserNeedsBadging.valueAt(index); 18606 } 18607 18608 @Override 18609 public KeySet getKeySetByAlias(String packageName, String alias) { 18610 if (packageName == null || alias == null) { 18611 return null; 18612 } 18613 synchronized(mPackages) { 18614 final PackageParser.Package pkg = mPackages.get(packageName); 18615 if (pkg == null) { 18616 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18617 throw new IllegalArgumentException("Unknown package: " + packageName); 18618 } 18619 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18620 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 18621 } 18622 } 18623 18624 @Override 18625 public KeySet getSigningKeySet(String packageName) { 18626 if (packageName == null) { 18627 return null; 18628 } 18629 synchronized(mPackages) { 18630 final PackageParser.Package pkg = mPackages.get(packageName); 18631 if (pkg == null) { 18632 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18633 throw new IllegalArgumentException("Unknown package: " + packageName); 18634 } 18635 if (pkg.applicationInfo.uid != Binder.getCallingUid() 18636 && Process.SYSTEM_UID != Binder.getCallingUid()) { 18637 throw new SecurityException("May not access signing KeySet of other apps."); 18638 } 18639 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18640 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 18641 } 18642 } 18643 18644 @Override 18645 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 18646 if (packageName == null || ks == null) { 18647 return false; 18648 } 18649 synchronized(mPackages) { 18650 final PackageParser.Package pkg = mPackages.get(packageName); 18651 if (pkg == null) { 18652 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18653 throw new IllegalArgumentException("Unknown package: " + packageName); 18654 } 18655 IBinder ksh = ks.getToken(); 18656 if (ksh instanceof KeySetHandle) { 18657 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18658 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 18659 } 18660 return false; 18661 } 18662 } 18663 18664 @Override 18665 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 18666 if (packageName == null || ks == null) { 18667 return false; 18668 } 18669 synchronized(mPackages) { 18670 final PackageParser.Package pkg = mPackages.get(packageName); 18671 if (pkg == null) { 18672 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18673 throw new IllegalArgumentException("Unknown package: " + packageName); 18674 } 18675 IBinder ksh = ks.getToken(); 18676 if (ksh instanceof KeySetHandle) { 18677 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18678 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 18679 } 18680 return false; 18681 } 18682 } 18683 18684 private void deletePackageIfUnusedLPr(final String packageName) { 18685 PackageSetting ps = mSettings.mPackages.get(packageName); 18686 if (ps == null) { 18687 return; 18688 } 18689 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 18690 // TODO Implement atomic delete if package is unused 18691 // It is currently possible that the package will be deleted even if it is installed 18692 // after this method returns. 18693 mHandler.post(new Runnable() { 18694 public void run() { 18695 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 18696 } 18697 }); 18698 } 18699 } 18700 18701 /** 18702 * Check and throw if the given before/after packages would be considered a 18703 * downgrade. 18704 */ 18705 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 18706 throws PackageManagerException { 18707 if (after.versionCode < before.mVersionCode) { 18708 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18709 "Update version code " + after.versionCode + " is older than current " 18710 + before.mVersionCode); 18711 } else if (after.versionCode == before.mVersionCode) { 18712 if (after.baseRevisionCode < before.baseRevisionCode) { 18713 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18714 "Update base revision code " + after.baseRevisionCode 18715 + " is older than current " + before.baseRevisionCode); 18716 } 18717 18718 if (!ArrayUtils.isEmpty(after.splitNames)) { 18719 for (int i = 0; i < after.splitNames.length; i++) { 18720 final String splitName = after.splitNames[i]; 18721 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 18722 if (j != -1) { 18723 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 18724 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18725 "Update split " + splitName + " revision code " 18726 + after.splitRevisionCodes[i] + " is older than current " 18727 + before.splitRevisionCodes[j]); 18728 } 18729 } 18730 } 18731 } 18732 } 18733 } 18734 18735 private static class MoveCallbacks extends Handler { 18736 private static final int MSG_CREATED = 1; 18737 private static final int MSG_STATUS_CHANGED = 2; 18738 18739 private final RemoteCallbackList<IPackageMoveObserver> 18740 mCallbacks = new RemoteCallbackList<>(); 18741 18742 private final SparseIntArray mLastStatus = new SparseIntArray(); 18743 18744 public MoveCallbacks(Looper looper) { 18745 super(looper); 18746 } 18747 18748 public void register(IPackageMoveObserver callback) { 18749 mCallbacks.register(callback); 18750 } 18751 18752 public void unregister(IPackageMoveObserver callback) { 18753 mCallbacks.unregister(callback); 18754 } 18755 18756 @Override 18757 public void handleMessage(Message msg) { 18758 final SomeArgs args = (SomeArgs) msg.obj; 18759 final int n = mCallbacks.beginBroadcast(); 18760 for (int i = 0; i < n; i++) { 18761 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 18762 try { 18763 invokeCallback(callback, msg.what, args); 18764 } catch (RemoteException ignored) { 18765 } 18766 } 18767 mCallbacks.finishBroadcast(); 18768 args.recycle(); 18769 } 18770 18771 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 18772 throws RemoteException { 18773 switch (what) { 18774 case MSG_CREATED: { 18775 callback.onCreated(args.argi1, (Bundle) args.arg2); 18776 break; 18777 } 18778 case MSG_STATUS_CHANGED: { 18779 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 18780 break; 18781 } 18782 } 18783 } 18784 18785 private void notifyCreated(int moveId, Bundle extras) { 18786 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 18787 18788 final SomeArgs args = SomeArgs.obtain(); 18789 args.argi1 = moveId; 18790 args.arg2 = extras; 18791 obtainMessage(MSG_CREATED, args).sendToTarget(); 18792 } 18793 18794 private void notifyStatusChanged(int moveId, int status) { 18795 notifyStatusChanged(moveId, status, -1); 18796 } 18797 18798 private void notifyStatusChanged(int moveId, int status, long estMillis) { 18799 Slog.v(TAG, "Move " + moveId + " status " + status); 18800 18801 final SomeArgs args = SomeArgs.obtain(); 18802 args.argi1 = moveId; 18803 args.argi2 = status; 18804 args.arg3 = estMillis; 18805 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 18806 18807 synchronized (mLastStatus) { 18808 mLastStatus.put(moveId, status); 18809 } 18810 } 18811 } 18812 18813 private final static class OnPermissionChangeListeners extends Handler { 18814 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 18815 18816 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 18817 new RemoteCallbackList<>(); 18818 18819 public OnPermissionChangeListeners(Looper looper) { 18820 super(looper); 18821 } 18822 18823 @Override 18824 public void handleMessage(Message msg) { 18825 switch (msg.what) { 18826 case MSG_ON_PERMISSIONS_CHANGED: { 18827 final int uid = msg.arg1; 18828 handleOnPermissionsChanged(uid); 18829 } break; 18830 } 18831 } 18832 18833 public void addListenerLocked(IOnPermissionsChangeListener listener) { 18834 mPermissionListeners.register(listener); 18835 18836 } 18837 18838 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 18839 mPermissionListeners.unregister(listener); 18840 } 18841 18842 public void onPermissionsChanged(int uid) { 18843 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 18844 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 18845 } 18846 } 18847 18848 private void handleOnPermissionsChanged(int uid) { 18849 final int count = mPermissionListeners.beginBroadcast(); 18850 try { 18851 for (int i = 0; i < count; i++) { 18852 IOnPermissionsChangeListener callback = mPermissionListeners 18853 .getBroadcastItem(i); 18854 try { 18855 callback.onPermissionsChanged(uid); 18856 } catch (RemoteException e) { 18857 Log.e(TAG, "Permission listener is dead", e); 18858 } 18859 } 18860 } finally { 18861 mPermissionListeners.finishBroadcast(); 18862 } 18863 } 18864 } 18865 18866 private class PackageManagerInternalImpl extends PackageManagerInternal { 18867 @Override 18868 public void setLocationPackagesProvider(PackagesProvider provider) { 18869 synchronized (mPackages) { 18870 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 18871 } 18872 } 18873 18874 @Override 18875 public void setImePackagesProvider(PackagesProvider provider) { 18876 synchronized (mPackages) { 18877 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 18878 } 18879 } 18880 18881 @Override 18882 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 18883 synchronized (mPackages) { 18884 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 18885 } 18886 } 18887 18888 @Override 18889 public void setSmsAppPackagesProvider(PackagesProvider provider) { 18890 synchronized (mPackages) { 18891 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 18892 } 18893 } 18894 18895 @Override 18896 public void setDialerAppPackagesProvider(PackagesProvider provider) { 18897 synchronized (mPackages) { 18898 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 18899 } 18900 } 18901 18902 @Override 18903 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 18904 synchronized (mPackages) { 18905 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 18906 } 18907 } 18908 18909 @Override 18910 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 18911 synchronized (mPackages) { 18912 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 18913 } 18914 } 18915 18916 @Override 18917 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 18918 synchronized (mPackages) { 18919 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 18920 packageName, userId); 18921 } 18922 } 18923 18924 @Override 18925 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 18926 synchronized (mPackages) { 18927 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 18928 packageName, userId); 18929 } 18930 } 18931 18932 @Override 18933 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 18934 synchronized (mPackages) { 18935 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 18936 packageName, userId); 18937 } 18938 } 18939 18940 @Override 18941 public void setKeepUninstalledPackages(final List<String> packageList) { 18942 Preconditions.checkNotNull(packageList); 18943 List<String> removedFromList = null; 18944 synchronized (mPackages) { 18945 if (mKeepUninstalledPackages != null) { 18946 final int packagesCount = mKeepUninstalledPackages.size(); 18947 for (int i = 0; i < packagesCount; i++) { 18948 String oldPackage = mKeepUninstalledPackages.get(i); 18949 if (packageList != null && packageList.contains(oldPackage)) { 18950 continue; 18951 } 18952 if (removedFromList == null) { 18953 removedFromList = new ArrayList<>(); 18954 } 18955 removedFromList.add(oldPackage); 18956 } 18957 } 18958 mKeepUninstalledPackages = new ArrayList<>(packageList); 18959 if (removedFromList != null) { 18960 final int removedCount = removedFromList.size(); 18961 for (int i = 0; i < removedCount; i++) { 18962 deletePackageIfUnusedLPr(removedFromList.get(i)); 18963 } 18964 } 18965 } 18966 } 18967 18968 @Override 18969 public boolean isPermissionsReviewRequired(String packageName, int userId) { 18970 synchronized (mPackages) { 18971 // If we do not support permission review, done. 18972 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 18973 return false; 18974 } 18975 18976 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 18977 if (packageSetting == null) { 18978 return false; 18979 } 18980 18981 // Permission review applies only to apps not supporting the new permission model. 18982 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 18983 return false; 18984 } 18985 18986 // Legacy apps have the permission and get user consent on launch. 18987 PermissionsState permissionsState = packageSetting.getPermissionsState(); 18988 return permissionsState.isPermissionReviewRequired(userId); 18989 } 18990 } 18991 } 18992 18993 @Override 18994 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 18995 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 18996 synchronized (mPackages) { 18997 final long identity = Binder.clearCallingIdentity(); 18998 try { 18999 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 19000 packageNames, userId); 19001 } finally { 19002 Binder.restoreCallingIdentity(identity); 19003 } 19004 } 19005 } 19006 19007 private static void enforceSystemOrPhoneCaller(String tag) { 19008 int callingUid = Binder.getCallingUid(); 19009 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 19010 throw new SecurityException( 19011 "Cannot call " + tag + " from UID " + callingUid); 19012 } 19013 } 19014 19015 boolean isHistoricalPackageUsageAvailable() { 19016 return mPackageUsage.isHistoricalPackageUsageAvailable(); 19017 } 19018} 19019