PackageManagerService.java revision a89087542f774c585b6a6ec535fc294721710521
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 34import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 61import static android.content.pm.PackageManager.MATCH_ALL; 62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 63import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 64import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 65import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 66import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 67import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 68import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 69import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 70import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 71import static android.content.pm.PackageManager.PERMISSION_DENIED; 72import static android.content.pm.PackageManager.PERMISSION_GRANTED; 73import static android.content.pm.PackageParser.isApkFile; 74import static android.os.Process.PACKAGE_INFO_GID; 75import static android.os.Process.SYSTEM_UID; 76import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 77import static android.system.OsConstants.O_CREAT; 78import static android.system.OsConstants.O_RDWR; 79 80import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 81import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 82import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 83import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 84import static com.android.internal.util.ArrayUtils.appendInt; 85import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 86import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 87import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 88import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 89import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 90import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 91import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 92import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 93import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 94 95import android.Manifest; 96import android.annotation.NonNull; 97import android.annotation.Nullable; 98import android.app.ActivityManager; 99import android.app.ActivityManagerNative; 100import android.app.AppGlobals; 101import android.app.IActivityManager; 102import android.app.admin.IDevicePolicyManager; 103import android.app.backup.IBackupManager; 104import android.content.BroadcastReceiver; 105import android.content.ComponentName; 106import android.content.Context; 107import android.content.IIntentReceiver; 108import android.content.Intent; 109import android.content.IntentFilter; 110import android.content.IntentSender; 111import android.content.IntentSender.SendIntentException; 112import android.content.ServiceConnection; 113import android.content.pm.ActivityInfo; 114import android.content.pm.ApplicationInfo; 115import android.content.pm.AppsQueryHelper; 116import android.content.pm.ComponentInfo; 117import android.content.pm.EphemeralApplicationInfo; 118import android.content.pm.EphemeralResolveInfo; 119import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 120import android.content.pm.FeatureInfo; 121import android.content.pm.IOnPermissionsChangeListener; 122import android.content.pm.IPackageDataObserver; 123import android.content.pm.IPackageDeleteObserver; 124import android.content.pm.IPackageDeleteObserver2; 125import android.content.pm.IPackageInstallObserver2; 126import android.content.pm.IPackageInstaller; 127import android.content.pm.IPackageManager; 128import android.content.pm.IPackageMoveObserver; 129import android.content.pm.IPackageStatsObserver; 130import android.content.pm.InstrumentationInfo; 131import android.content.pm.IntentFilterVerificationInfo; 132import android.content.pm.KeySet; 133import android.content.pm.PackageCleanItem; 134import android.content.pm.PackageInfo; 135import android.content.pm.PackageInfoLite; 136import android.content.pm.PackageInstaller; 137import android.content.pm.PackageManager; 138import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 139import android.content.pm.PackageManagerInternal; 140import android.content.pm.PackageParser; 141import android.content.pm.PackageParser.ActivityIntentInfo; 142import android.content.pm.PackageParser.Package; 143import android.content.pm.PackageParser.PackageLite; 144import android.content.pm.PackageParser.PackageParserException; 145import android.content.pm.PackageStats; 146import android.content.pm.PackageUserState; 147import android.content.pm.ParceledListSlice; 148import android.content.pm.PermissionGroupInfo; 149import android.content.pm.PermissionInfo; 150import android.content.pm.ProviderInfo; 151import android.content.pm.ResolveInfo; 152import android.content.pm.ServiceInfo; 153import android.content.pm.Signature; 154import android.content.pm.UserInfo; 155import android.content.pm.VerificationParams; 156import android.content.pm.VerifierDeviceIdentity; 157import android.content.pm.VerifierInfo; 158import android.content.res.Resources; 159import android.graphics.Bitmap; 160import android.hardware.display.DisplayManager; 161import android.net.Uri; 162import android.os.Binder; 163import android.os.Build; 164import android.os.Bundle; 165import android.os.Debug; 166import android.os.Environment; 167import android.os.Environment.UserEnvironment; 168import android.os.FileUtils; 169import android.os.Handler; 170import android.os.IBinder; 171import android.os.Looper; 172import android.os.Message; 173import android.os.Parcel; 174import android.os.ParcelFileDescriptor; 175import android.os.Process; 176import android.os.RemoteCallbackList; 177import android.os.RemoteException; 178import android.os.ResultReceiver; 179import android.os.SELinux; 180import android.os.ServiceManager; 181import android.os.SystemClock; 182import android.os.SystemProperties; 183import android.os.Trace; 184import android.os.UserHandle; 185import android.os.UserManager; 186import android.os.storage.IMountService; 187import android.os.storage.MountServiceInternal; 188import android.os.storage.StorageEventListener; 189import android.os.storage.StorageManager; 190import android.os.storage.VolumeInfo; 191import android.os.storage.VolumeRecord; 192import android.security.KeyStore; 193import android.security.SystemKeyStore; 194import android.system.ErrnoException; 195import android.system.Os; 196import android.text.TextUtils; 197import android.text.format.DateUtils; 198import android.util.ArrayMap; 199import android.util.ArraySet; 200import android.util.AtomicFile; 201import android.util.DisplayMetrics; 202import android.util.EventLog; 203import android.util.ExceptionUtils; 204import android.util.Log; 205import android.util.LogPrinter; 206import android.util.MathUtils; 207import android.util.PrintStreamPrinter; 208import android.util.Slog; 209import android.util.SparseArray; 210import android.util.SparseBooleanArray; 211import android.util.SparseIntArray; 212import android.util.Xml; 213import android.view.Display; 214 215import com.android.internal.R; 216import com.android.internal.annotations.GuardedBy; 217import com.android.internal.app.IMediaContainerService; 218import com.android.internal.app.ResolverActivity; 219import com.android.internal.content.NativeLibraryHelper; 220import com.android.internal.content.PackageHelper; 221import com.android.internal.os.IParcelFileDescriptorFactory; 222import com.android.internal.os.InstallerConnection.InstallerException; 223import com.android.internal.os.SomeArgs; 224import com.android.internal.os.Zygote; 225import com.android.internal.util.ArrayUtils; 226import com.android.internal.util.FastPrintWriter; 227import com.android.internal.util.FastXmlSerializer; 228import com.android.internal.util.IndentingPrintWriter; 229import com.android.internal.util.Preconditions; 230import com.android.internal.util.XmlUtils; 231import com.android.server.EventLogTags; 232import com.android.server.FgThread; 233import com.android.server.IntentResolver; 234import com.android.server.LocalServices; 235import com.android.server.ServiceThread; 236import com.android.server.SystemConfig; 237import com.android.server.Watchdog; 238import com.android.server.pm.Installer.StorageFlags; 239import com.android.server.pm.PermissionsState.PermissionState; 240import com.android.server.pm.Settings.DatabaseVersion; 241import com.android.server.pm.Settings.VersionInfo; 242import com.android.server.storage.DeviceStorageMonitorInternal; 243 244import dalvik.system.DexFile; 245import dalvik.system.VMRuntime; 246 247import libcore.io.IoUtils; 248import libcore.util.EmptyArray; 249 250import org.xmlpull.v1.XmlPullParser; 251import org.xmlpull.v1.XmlPullParserException; 252import org.xmlpull.v1.XmlSerializer; 253 254import java.io.BufferedInputStream; 255import java.io.BufferedOutputStream; 256import java.io.BufferedReader; 257import java.io.ByteArrayInputStream; 258import java.io.ByteArrayOutputStream; 259import java.io.File; 260import java.io.FileDescriptor; 261import java.io.FileNotFoundException; 262import java.io.FileOutputStream; 263import java.io.FileReader; 264import java.io.FilenameFilter; 265import java.io.IOException; 266import java.io.InputStream; 267import java.io.PrintStream; 268import java.io.PrintWriter; 269import java.nio.charset.StandardCharsets; 270import java.security.MessageDigest; 271import java.security.NoSuchAlgorithmException; 272import java.security.PublicKey; 273import java.security.cert.CertificateEncodingException; 274import java.security.cert.CertificateException; 275import java.text.SimpleDateFormat; 276import java.util.ArrayList; 277import java.util.Arrays; 278import java.util.Collection; 279import java.util.Collections; 280import java.util.Comparator; 281import java.util.Date; 282import java.util.HashSet; 283import java.util.Iterator; 284import java.util.List; 285import java.util.Map; 286import java.util.Objects; 287import java.util.Set; 288import java.util.concurrent.CountDownLatch; 289import java.util.concurrent.TimeUnit; 290import java.util.concurrent.atomic.AtomicBoolean; 291import java.util.concurrent.atomic.AtomicInteger; 292import java.util.concurrent.atomic.AtomicLong; 293 294/** 295 * Keep track of all those .apks everywhere. 296 * 297 * This is very central to the platform's security; please run the unit 298 * tests whenever making modifications here: 299 * 300runtest -c android.content.pm.PackageManagerTests frameworks-core 301 * 302 * {@hide} 303 */ 304public class PackageManagerService extends IPackageManager.Stub { 305 static final String TAG = "PackageManager"; 306 static final boolean DEBUG_SETTINGS = false; 307 static final boolean DEBUG_PREFERRED = false; 308 static final boolean DEBUG_UPGRADE = false; 309 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 310 private static final boolean DEBUG_BACKUP = false; 311 private static final boolean DEBUG_INSTALL = false; 312 private static final boolean DEBUG_REMOVE = false; 313 private static final boolean DEBUG_BROADCASTS = false; 314 private static final boolean DEBUG_SHOW_INFO = false; 315 private static final boolean DEBUG_PACKAGE_INFO = false; 316 private static final boolean DEBUG_INTENT_MATCHING = false; 317 private static final boolean DEBUG_PACKAGE_SCANNING = false; 318 private static final boolean DEBUG_VERIFY = false; 319 320 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 321 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 322 // user, but by default initialize to this. 323 static final boolean DEBUG_DEXOPT = false; 324 325 private static final boolean DEBUG_ABI_SELECTION = false; 326 private static final boolean DEBUG_EPHEMERAL = false; 327 private static final boolean DEBUG_TRIAGED_MISSING = false; 328 private static final boolean DEBUG_APP_DATA = false; 329 330 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 331 332 private static final boolean DISABLE_EPHEMERAL_APPS = true; 333 334 private static final int RADIO_UID = Process.PHONE_UID; 335 private static final int LOG_UID = Process.LOG_UID; 336 private static final int NFC_UID = Process.NFC_UID; 337 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 338 private static final int SHELL_UID = Process.SHELL_UID; 339 340 // Cap the size of permission trees that 3rd party apps can define 341 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 342 343 // Suffix used during package installation when copying/moving 344 // package apks to install directory. 345 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 346 347 static final int SCAN_NO_DEX = 1<<1; 348 static final int SCAN_FORCE_DEX = 1<<2; 349 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 350 static final int SCAN_NEW_INSTALL = 1<<4; 351 static final int SCAN_NO_PATHS = 1<<5; 352 static final int SCAN_UPDATE_TIME = 1<<6; 353 static final int SCAN_DEFER_DEX = 1<<7; 354 static final int SCAN_BOOTING = 1<<8; 355 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 356 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 357 static final int SCAN_REPLACING = 1<<11; 358 static final int SCAN_REQUIRE_KNOWN = 1<<12; 359 static final int SCAN_MOVE = 1<<13; 360 static final int SCAN_INITIAL = 1<<14; 361 362 static final int REMOVE_CHATTY = 1<<16; 363 364 private static final int[] EMPTY_INT_ARRAY = new int[0]; 365 366 /** 367 * Timeout (in milliseconds) after which the watchdog should declare that 368 * our handler thread is wedged. The usual default for such things is one 369 * minute but we sometimes do very lengthy I/O operations on this thread, 370 * such as installing multi-gigabyte applications, so ours needs to be longer. 371 */ 372 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 373 374 /** 375 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 376 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 377 * settings entry if available, otherwise we use the hardcoded default. If it's been 378 * more than this long since the last fstrim, we force one during the boot sequence. 379 * 380 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 381 * one gets run at the next available charging+idle time. This final mandatory 382 * no-fstrim check kicks in only of the other scheduling criteria is never met. 383 */ 384 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 385 386 /** 387 * Whether verification is enabled by default. 388 */ 389 private static final boolean DEFAULT_VERIFY_ENABLE = true; 390 391 /** 392 * The default maximum time to wait for the verification agent to return in 393 * milliseconds. 394 */ 395 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 396 397 /** 398 * The default response for package verification timeout. 399 * 400 * This can be either PackageManager.VERIFICATION_ALLOW or 401 * PackageManager.VERIFICATION_REJECT. 402 */ 403 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 404 405 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 406 407 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 408 DEFAULT_CONTAINER_PACKAGE, 409 "com.android.defcontainer.DefaultContainerService"); 410 411 private static final String KILL_APP_REASON_GIDS_CHANGED = 412 "permission grant or revoke changed gids"; 413 414 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 415 "permissions revoked"; 416 417 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 418 419 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 420 421 /** Permission grant: not grant the permission. */ 422 private static final int GRANT_DENIED = 1; 423 424 /** Permission grant: grant the permission as an install permission. */ 425 private static final int GRANT_INSTALL = 2; 426 427 /** Permission grant: grant the permission as a runtime one. */ 428 private static final int GRANT_RUNTIME = 3; 429 430 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 431 private static final int GRANT_UPGRADE = 4; 432 433 /** Canonical intent used to identify what counts as a "web browser" app */ 434 private static final Intent sBrowserIntent; 435 static { 436 sBrowserIntent = new Intent(); 437 sBrowserIntent.setAction(Intent.ACTION_VIEW); 438 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 439 sBrowserIntent.setData(Uri.parse("http:")); 440 } 441 442 final ServiceThread mHandlerThread; 443 444 final PackageHandler mHandler; 445 446 /** 447 * Messages for {@link #mHandler} that need to wait for system ready before 448 * being dispatched. 449 */ 450 private ArrayList<Message> mPostSystemReadyMessages; 451 452 final int mSdkVersion = Build.VERSION.SDK_INT; 453 454 final Context mContext; 455 final boolean mFactoryTest; 456 final boolean mOnlyCore; 457 final DisplayMetrics mMetrics; 458 final int mDefParseFlags; 459 final String[] mSeparateProcesses; 460 final boolean mIsUpgrade; 461 462 /** The location for ASEC container files on internal storage. */ 463 final String mAsecInternalPath; 464 465 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 466 // LOCK HELD. Can be called with mInstallLock held. 467 @GuardedBy("mInstallLock") 468 final Installer mInstaller; 469 470 /** Directory where installed third-party apps stored */ 471 final File mAppInstallDir; 472 final File mEphemeralInstallDir; 473 474 /** 475 * Directory to which applications installed internally have their 476 * 32 bit native libraries copied. 477 */ 478 private File mAppLib32InstallDir; 479 480 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 481 // apps. 482 final File mDrmAppPrivateInstallDir; 483 484 // ---------------------------------------------------------------- 485 486 // Lock for state used when installing and doing other long running 487 // operations. Methods that must be called with this lock held have 488 // the suffix "LI". 489 final Object mInstallLock = new Object(); 490 491 // ---------------------------------------------------------------- 492 493 // Keys are String (package name), values are Package. This also serves 494 // as the lock for the global state. Methods that must be called with 495 // this lock held have the prefix "LP". 496 @GuardedBy("mPackages") 497 final ArrayMap<String, PackageParser.Package> mPackages = 498 new ArrayMap<String, PackageParser.Package>(); 499 500 // Tracks available target package names -> overlay package paths. 501 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 502 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 503 504 /** 505 * Tracks new system packages [received in an OTA] that we expect to 506 * find updated user-installed versions. Keys are package name, values 507 * are package location. 508 */ 509 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 510 511 /** 512 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 513 */ 514 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 515 /** 516 * Whether or not system app permissions should be promoted from install to runtime. 517 */ 518 boolean mPromoteSystemApps; 519 520 final Settings mSettings; 521 boolean mRestoredSettings; 522 523 // System configuration read by SystemConfig. 524 final int[] mGlobalGids; 525 final SparseArray<ArraySet<String>> mSystemPermissions; 526 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 527 528 // If mac_permissions.xml was found for seinfo labeling. 529 boolean mFoundPolicyFile; 530 531 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 532 533 public static final class SharedLibraryEntry { 534 public final String path; 535 public final String apk; 536 537 SharedLibraryEntry(String _path, String _apk) { 538 path = _path; 539 apk = _apk; 540 } 541 } 542 543 // Currently known shared libraries. 544 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 545 new ArrayMap<String, SharedLibraryEntry>(); 546 547 // All available activities, for your resolving pleasure. 548 final ActivityIntentResolver mActivities = 549 new ActivityIntentResolver(); 550 551 // All available receivers, for your resolving pleasure. 552 final ActivityIntentResolver mReceivers = 553 new ActivityIntentResolver(); 554 555 // All available services, for your resolving pleasure. 556 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 557 558 // All available providers, for your resolving pleasure. 559 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 560 561 // Mapping from provider base names (first directory in content URI codePath) 562 // to the provider information. 563 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 564 new ArrayMap<String, PackageParser.Provider>(); 565 566 // Mapping from instrumentation class names to info about them. 567 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 568 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 569 570 // Mapping from permission names to info about them. 571 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 572 new ArrayMap<String, PackageParser.PermissionGroup>(); 573 574 // Packages whose data we have transfered into another package, thus 575 // should no longer exist. 576 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 577 578 // Broadcast actions that are only available to the system. 579 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 580 581 /** List of packages waiting for verification. */ 582 final SparseArray<PackageVerificationState> mPendingVerification 583 = new SparseArray<PackageVerificationState>(); 584 585 /** Set of packages associated with each app op permission. */ 586 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 587 588 final PackageInstallerService mInstallerService; 589 590 private final PackageDexOptimizer mPackageDexOptimizer; 591 592 private AtomicInteger mNextMoveId = new AtomicInteger(); 593 private final MoveCallbacks mMoveCallbacks; 594 595 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 596 597 // Cache of users who need badging. 598 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 599 600 /** Token for keys in mPendingVerification. */ 601 private int mPendingVerificationToken = 0; 602 603 volatile boolean mSystemReady; 604 volatile boolean mSafeMode; 605 volatile boolean mHasSystemUidErrors; 606 607 ApplicationInfo mAndroidApplication; 608 final ActivityInfo mResolveActivity = new ActivityInfo(); 609 final ResolveInfo mResolveInfo = new ResolveInfo(); 610 ComponentName mResolveComponentName; 611 PackageParser.Package mPlatformPackage; 612 ComponentName mCustomResolverComponentName; 613 614 boolean mResolverReplaced = false; 615 616 private final @Nullable ComponentName mIntentFilterVerifierComponent; 617 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 618 619 private int mIntentFilterVerificationToken = 0; 620 621 /** Component that knows whether or not an ephemeral application exists */ 622 final ComponentName mEphemeralResolverComponent; 623 /** The service connection to the ephemeral resolver */ 624 final EphemeralResolverConnection mEphemeralResolverConnection; 625 626 /** Component used to install ephemeral applications */ 627 final ComponentName mEphemeralInstallerComponent; 628 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 629 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 630 631 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 632 = new SparseArray<IntentFilterVerificationState>(); 633 634 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 635 new DefaultPermissionGrantPolicy(this); 636 637 // List of packages names to keep cached, even if they are uninstalled for all users 638 private List<String> mKeepUninstalledPackages; 639 640 private boolean mUseJitProfiles = 641 SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false); 642 643 private static class IFVerificationParams { 644 PackageParser.Package pkg; 645 boolean replacing; 646 int userId; 647 int verifierUid; 648 649 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 650 int _userId, int _verifierUid) { 651 pkg = _pkg; 652 replacing = _replacing; 653 userId = _userId; 654 replacing = _replacing; 655 verifierUid = _verifierUid; 656 } 657 } 658 659 private interface IntentFilterVerifier<T extends IntentFilter> { 660 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 661 T filter, String packageName); 662 void startVerifications(int userId); 663 void receiveVerificationResponse(int verificationId); 664 } 665 666 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 667 private Context mContext; 668 private ComponentName mIntentFilterVerifierComponent; 669 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 670 671 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 672 mContext = context; 673 mIntentFilterVerifierComponent = verifierComponent; 674 } 675 676 private String getDefaultScheme() { 677 return IntentFilter.SCHEME_HTTPS; 678 } 679 680 @Override 681 public void startVerifications(int userId) { 682 // Launch verifications requests 683 int count = mCurrentIntentFilterVerifications.size(); 684 for (int n=0; n<count; n++) { 685 int verificationId = mCurrentIntentFilterVerifications.get(n); 686 final IntentFilterVerificationState ivs = 687 mIntentFilterVerificationStates.get(verificationId); 688 689 String packageName = ivs.getPackageName(); 690 691 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 692 final int filterCount = filters.size(); 693 ArraySet<String> domainsSet = new ArraySet<>(); 694 for (int m=0; m<filterCount; m++) { 695 PackageParser.ActivityIntentInfo filter = filters.get(m); 696 domainsSet.addAll(filter.getHostsList()); 697 } 698 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 699 synchronized (mPackages) { 700 if (mSettings.createIntentFilterVerificationIfNeededLPw( 701 packageName, domainsList) != null) { 702 scheduleWriteSettingsLocked(); 703 } 704 } 705 sendVerificationRequest(userId, verificationId, ivs); 706 } 707 mCurrentIntentFilterVerifications.clear(); 708 } 709 710 private void sendVerificationRequest(int userId, int verificationId, 711 IntentFilterVerificationState ivs) { 712 713 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 714 verificationIntent.putExtra( 715 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 716 verificationId); 717 verificationIntent.putExtra( 718 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 719 getDefaultScheme()); 720 verificationIntent.putExtra( 721 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 722 ivs.getHostsString()); 723 verificationIntent.putExtra( 724 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 725 ivs.getPackageName()); 726 verificationIntent.setComponent(mIntentFilterVerifierComponent); 727 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 728 729 UserHandle user = new UserHandle(userId); 730 mContext.sendBroadcastAsUser(verificationIntent, user); 731 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 732 "Sending IntentFilter verification broadcast"); 733 } 734 735 public void receiveVerificationResponse(int verificationId) { 736 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 737 738 final boolean verified = ivs.isVerified(); 739 740 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 741 final int count = filters.size(); 742 if (DEBUG_DOMAIN_VERIFICATION) { 743 Slog.i(TAG, "Received verification response " + verificationId 744 + " for " + count + " filters, verified=" + verified); 745 } 746 for (int n=0; n<count; n++) { 747 PackageParser.ActivityIntentInfo filter = filters.get(n); 748 filter.setVerified(verified); 749 750 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 751 + " verified with result:" + verified + " and hosts:" 752 + ivs.getHostsString()); 753 } 754 755 mIntentFilterVerificationStates.remove(verificationId); 756 757 final String packageName = ivs.getPackageName(); 758 IntentFilterVerificationInfo ivi = null; 759 760 synchronized (mPackages) { 761 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 762 } 763 if (ivi == null) { 764 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 765 + verificationId + " packageName:" + packageName); 766 return; 767 } 768 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 769 "Updating IntentFilterVerificationInfo for package " + packageName 770 +" verificationId:" + verificationId); 771 772 synchronized (mPackages) { 773 if (verified) { 774 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 775 } else { 776 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 777 } 778 scheduleWriteSettingsLocked(); 779 780 final int userId = ivs.getUserId(); 781 if (userId != UserHandle.USER_ALL) { 782 final int userStatus = 783 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 784 785 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 786 boolean needUpdate = false; 787 788 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 789 // already been set by the User thru the Disambiguation dialog 790 switch (userStatus) { 791 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 792 if (verified) { 793 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 794 } else { 795 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 796 } 797 needUpdate = true; 798 break; 799 800 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 801 if (verified) { 802 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 803 needUpdate = true; 804 } 805 break; 806 807 default: 808 // Nothing to do 809 } 810 811 if (needUpdate) { 812 mSettings.updateIntentFilterVerificationStatusLPw( 813 packageName, updatedStatus, userId); 814 scheduleWritePackageRestrictionsLocked(userId); 815 } 816 } 817 } 818 } 819 820 @Override 821 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 822 ActivityIntentInfo filter, String packageName) { 823 if (!hasValidDomains(filter)) { 824 return false; 825 } 826 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 827 if (ivs == null) { 828 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 829 packageName); 830 } 831 if (DEBUG_DOMAIN_VERIFICATION) { 832 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 833 } 834 ivs.addFilter(filter); 835 return true; 836 } 837 838 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 839 int userId, int verificationId, String packageName) { 840 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 841 verifierUid, userId, packageName); 842 ivs.setPendingState(); 843 synchronized (mPackages) { 844 mIntentFilterVerificationStates.append(verificationId, ivs); 845 mCurrentIntentFilterVerifications.add(verificationId); 846 } 847 return ivs; 848 } 849 } 850 851 private static boolean hasValidDomains(ActivityIntentInfo filter) { 852 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 853 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 854 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 855 } 856 857 // Set of pending broadcasts for aggregating enable/disable of components. 858 static class PendingPackageBroadcasts { 859 // for each user id, a map of <package name -> components within that package> 860 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 861 862 public PendingPackageBroadcasts() { 863 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 864 } 865 866 public ArrayList<String> get(int userId, String packageName) { 867 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 868 return packages.get(packageName); 869 } 870 871 public void put(int userId, String packageName, ArrayList<String> components) { 872 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 873 packages.put(packageName, components); 874 } 875 876 public void remove(int userId, String packageName) { 877 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 878 if (packages != null) { 879 packages.remove(packageName); 880 } 881 } 882 883 public void remove(int userId) { 884 mUidMap.remove(userId); 885 } 886 887 public int userIdCount() { 888 return mUidMap.size(); 889 } 890 891 public int userIdAt(int n) { 892 return mUidMap.keyAt(n); 893 } 894 895 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 896 return mUidMap.get(userId); 897 } 898 899 public int size() { 900 // total number of pending broadcast entries across all userIds 901 int num = 0; 902 for (int i = 0; i< mUidMap.size(); i++) { 903 num += mUidMap.valueAt(i).size(); 904 } 905 return num; 906 } 907 908 public void clear() { 909 mUidMap.clear(); 910 } 911 912 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 913 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 914 if (map == null) { 915 map = new ArrayMap<String, ArrayList<String>>(); 916 mUidMap.put(userId, map); 917 } 918 return map; 919 } 920 } 921 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 922 923 // Service Connection to remote media container service to copy 924 // package uri's from external media onto secure containers 925 // or internal storage. 926 private IMediaContainerService mContainerService = null; 927 928 static final int SEND_PENDING_BROADCAST = 1; 929 static final int MCS_BOUND = 3; 930 static final int END_COPY = 4; 931 static final int INIT_COPY = 5; 932 static final int MCS_UNBIND = 6; 933 static final int START_CLEANING_PACKAGE = 7; 934 static final int FIND_INSTALL_LOC = 8; 935 static final int POST_INSTALL = 9; 936 static final int MCS_RECONNECT = 10; 937 static final int MCS_GIVE_UP = 11; 938 static final int UPDATED_MEDIA_STATUS = 12; 939 static final int WRITE_SETTINGS = 13; 940 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 941 static final int PACKAGE_VERIFIED = 15; 942 static final int CHECK_PENDING_VERIFICATION = 16; 943 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 944 static final int INTENT_FILTER_VERIFIED = 18; 945 946 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 947 948 // Delay time in millisecs 949 static final int BROADCAST_DELAY = 10 * 1000; 950 951 static UserManagerService sUserManager; 952 953 // Stores a list of users whose package restrictions file needs to be updated 954 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 955 956 final private DefaultContainerConnection mDefContainerConn = 957 new DefaultContainerConnection(); 958 class DefaultContainerConnection implements ServiceConnection { 959 public void onServiceConnected(ComponentName name, IBinder service) { 960 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 961 IMediaContainerService imcs = 962 IMediaContainerService.Stub.asInterface(service); 963 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 964 } 965 966 public void onServiceDisconnected(ComponentName name) { 967 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 968 } 969 } 970 971 // Recordkeeping of restore-after-install operations that are currently in flight 972 // between the Package Manager and the Backup Manager 973 static class PostInstallData { 974 public InstallArgs args; 975 public PackageInstalledInfo res; 976 977 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 978 args = _a; 979 res = _r; 980 } 981 } 982 983 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 984 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 985 986 // XML tags for backup/restore of various bits of state 987 private static final String TAG_PREFERRED_BACKUP = "pa"; 988 private static final String TAG_DEFAULT_APPS = "da"; 989 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 990 991 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 992 private static final String TAG_ALL_GRANTS = "rt-grants"; 993 private static final String TAG_GRANT = "grant"; 994 private static final String ATTR_PACKAGE_NAME = "pkg"; 995 996 private static final String TAG_PERMISSION = "perm"; 997 private static final String ATTR_PERMISSION_NAME = "name"; 998 private static final String ATTR_IS_GRANTED = "g"; 999 private static final String ATTR_USER_SET = "set"; 1000 private static final String ATTR_USER_FIXED = "fixed"; 1001 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1002 1003 // System/policy permission grants are not backed up 1004 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1005 FLAG_PERMISSION_POLICY_FIXED 1006 | FLAG_PERMISSION_SYSTEM_FIXED 1007 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1008 1009 // And we back up these user-adjusted states 1010 private static final int USER_RUNTIME_GRANT_MASK = 1011 FLAG_PERMISSION_USER_SET 1012 | FLAG_PERMISSION_USER_FIXED 1013 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1014 1015 final @Nullable String mRequiredVerifierPackage; 1016 final @Nullable String mRequiredInstallerPackage; 1017 1018 private final PackageUsage mPackageUsage = new PackageUsage(); 1019 1020 private class PackageUsage { 1021 private static final int WRITE_INTERVAL 1022 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1023 1024 private final Object mFileLock = new Object(); 1025 private final AtomicLong mLastWritten = new AtomicLong(0); 1026 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1027 1028 private boolean mIsHistoricalPackageUsageAvailable = true; 1029 1030 boolean isHistoricalPackageUsageAvailable() { 1031 return mIsHistoricalPackageUsageAvailable; 1032 } 1033 1034 void write(boolean force) { 1035 if (force) { 1036 writeInternal(); 1037 return; 1038 } 1039 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1040 && !DEBUG_DEXOPT) { 1041 return; 1042 } 1043 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1044 new Thread("PackageUsage_DiskWriter") { 1045 @Override 1046 public void run() { 1047 try { 1048 writeInternal(); 1049 } finally { 1050 mBackgroundWriteRunning.set(false); 1051 } 1052 } 1053 }.start(); 1054 } 1055 } 1056 1057 private void writeInternal() { 1058 synchronized (mPackages) { 1059 synchronized (mFileLock) { 1060 AtomicFile file = getFile(); 1061 FileOutputStream f = null; 1062 try { 1063 f = file.startWrite(); 1064 BufferedOutputStream out = new BufferedOutputStream(f); 1065 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1066 StringBuilder sb = new StringBuilder(); 1067 for (PackageParser.Package pkg : mPackages.values()) { 1068 if (pkg.mLastPackageUsageTimeInMills == 0) { 1069 continue; 1070 } 1071 sb.setLength(0); 1072 sb.append(pkg.packageName); 1073 sb.append(' '); 1074 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1075 sb.append('\n'); 1076 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1077 } 1078 out.flush(); 1079 file.finishWrite(f); 1080 } catch (IOException e) { 1081 if (f != null) { 1082 file.failWrite(f); 1083 } 1084 Log.e(TAG, "Failed to write package usage times", e); 1085 } 1086 } 1087 } 1088 mLastWritten.set(SystemClock.elapsedRealtime()); 1089 } 1090 1091 void readLP() { 1092 synchronized (mFileLock) { 1093 AtomicFile file = getFile(); 1094 BufferedInputStream in = null; 1095 try { 1096 in = new BufferedInputStream(file.openRead()); 1097 StringBuffer sb = new StringBuffer(); 1098 while (true) { 1099 String packageName = readToken(in, sb, ' '); 1100 if (packageName == null) { 1101 break; 1102 } 1103 String timeInMillisString = readToken(in, sb, '\n'); 1104 if (timeInMillisString == null) { 1105 throw new IOException("Failed to find last usage time for package " 1106 + packageName); 1107 } 1108 PackageParser.Package pkg = mPackages.get(packageName); 1109 if (pkg == null) { 1110 continue; 1111 } 1112 long timeInMillis; 1113 try { 1114 timeInMillis = Long.parseLong(timeInMillisString); 1115 } catch (NumberFormatException e) { 1116 throw new IOException("Failed to parse " + timeInMillisString 1117 + " as a long.", e); 1118 } 1119 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1120 } 1121 } catch (FileNotFoundException expected) { 1122 mIsHistoricalPackageUsageAvailable = false; 1123 } catch (IOException e) { 1124 Log.w(TAG, "Failed to read package usage times", e); 1125 } finally { 1126 IoUtils.closeQuietly(in); 1127 } 1128 } 1129 mLastWritten.set(SystemClock.elapsedRealtime()); 1130 } 1131 1132 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1133 throws IOException { 1134 sb.setLength(0); 1135 while (true) { 1136 int ch = in.read(); 1137 if (ch == -1) { 1138 if (sb.length() == 0) { 1139 return null; 1140 } 1141 throw new IOException("Unexpected EOF"); 1142 } 1143 if (ch == endOfToken) { 1144 return sb.toString(); 1145 } 1146 sb.append((char)ch); 1147 } 1148 } 1149 1150 private AtomicFile getFile() { 1151 File dataDir = Environment.getDataDirectory(); 1152 File systemDir = new File(dataDir, "system"); 1153 File fname = new File(systemDir, "package-usage.list"); 1154 return new AtomicFile(fname); 1155 } 1156 } 1157 1158 class PackageHandler extends Handler { 1159 private boolean mBound = false; 1160 final ArrayList<HandlerParams> mPendingInstalls = 1161 new ArrayList<HandlerParams>(); 1162 1163 private boolean connectToService() { 1164 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1165 " DefaultContainerService"); 1166 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1167 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1168 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1169 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1170 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1171 mBound = true; 1172 return true; 1173 } 1174 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1175 return false; 1176 } 1177 1178 private void disconnectService() { 1179 mContainerService = null; 1180 mBound = false; 1181 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1182 mContext.unbindService(mDefContainerConn); 1183 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1184 } 1185 1186 PackageHandler(Looper looper) { 1187 super(looper); 1188 } 1189 1190 public void handleMessage(Message msg) { 1191 try { 1192 doHandleMessage(msg); 1193 } finally { 1194 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1195 } 1196 } 1197 1198 void doHandleMessage(Message msg) { 1199 switch (msg.what) { 1200 case INIT_COPY: { 1201 HandlerParams params = (HandlerParams) msg.obj; 1202 int idx = mPendingInstalls.size(); 1203 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1204 // If a bind was already initiated we dont really 1205 // need to do anything. The pending install 1206 // will be processed later on. 1207 if (!mBound) { 1208 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1209 System.identityHashCode(mHandler)); 1210 // If this is the only one pending we might 1211 // have to bind to the service again. 1212 if (!connectToService()) { 1213 Slog.e(TAG, "Failed to bind to media container service"); 1214 params.serviceError(); 1215 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1216 System.identityHashCode(mHandler)); 1217 if (params.traceMethod != null) { 1218 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1219 params.traceCookie); 1220 } 1221 return; 1222 } else { 1223 // Once we bind to the service, the first 1224 // pending request will be processed. 1225 mPendingInstalls.add(idx, params); 1226 } 1227 } else { 1228 mPendingInstalls.add(idx, params); 1229 // Already bound to the service. Just make 1230 // sure we trigger off processing the first request. 1231 if (idx == 0) { 1232 mHandler.sendEmptyMessage(MCS_BOUND); 1233 } 1234 } 1235 break; 1236 } 1237 case MCS_BOUND: { 1238 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1239 if (msg.obj != null) { 1240 mContainerService = (IMediaContainerService) msg.obj; 1241 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1242 System.identityHashCode(mHandler)); 1243 } 1244 if (mContainerService == null) { 1245 if (!mBound) { 1246 // Something seriously wrong since we are not bound and we are not 1247 // waiting for connection. Bail out. 1248 Slog.e(TAG, "Cannot bind to media container service"); 1249 for (HandlerParams params : mPendingInstalls) { 1250 // Indicate service bind error 1251 params.serviceError(); 1252 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1253 System.identityHashCode(params)); 1254 if (params.traceMethod != null) { 1255 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1256 params.traceMethod, params.traceCookie); 1257 } 1258 return; 1259 } 1260 mPendingInstalls.clear(); 1261 } else { 1262 Slog.w(TAG, "Waiting to connect to media container service"); 1263 } 1264 } else if (mPendingInstalls.size() > 0) { 1265 HandlerParams params = mPendingInstalls.get(0); 1266 if (params != null) { 1267 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1268 System.identityHashCode(params)); 1269 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1270 if (params.startCopy()) { 1271 // We are done... look for more work or to 1272 // go idle. 1273 if (DEBUG_SD_INSTALL) Log.i(TAG, 1274 "Checking for more work or unbind..."); 1275 // Delete pending install 1276 if (mPendingInstalls.size() > 0) { 1277 mPendingInstalls.remove(0); 1278 } 1279 if (mPendingInstalls.size() == 0) { 1280 if (mBound) { 1281 if (DEBUG_SD_INSTALL) Log.i(TAG, 1282 "Posting delayed MCS_UNBIND"); 1283 removeMessages(MCS_UNBIND); 1284 Message ubmsg = obtainMessage(MCS_UNBIND); 1285 // Unbind after a little delay, to avoid 1286 // continual thrashing. 1287 sendMessageDelayed(ubmsg, 10000); 1288 } 1289 } else { 1290 // There are more pending requests in queue. 1291 // Just post MCS_BOUND message to trigger processing 1292 // of next pending install. 1293 if (DEBUG_SD_INSTALL) Log.i(TAG, 1294 "Posting MCS_BOUND for next work"); 1295 mHandler.sendEmptyMessage(MCS_BOUND); 1296 } 1297 } 1298 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1299 } 1300 } else { 1301 // Should never happen ideally. 1302 Slog.w(TAG, "Empty queue"); 1303 } 1304 break; 1305 } 1306 case MCS_RECONNECT: { 1307 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1308 if (mPendingInstalls.size() > 0) { 1309 if (mBound) { 1310 disconnectService(); 1311 } 1312 if (!connectToService()) { 1313 Slog.e(TAG, "Failed to bind to media container service"); 1314 for (HandlerParams params : mPendingInstalls) { 1315 // Indicate service bind error 1316 params.serviceError(); 1317 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1318 System.identityHashCode(params)); 1319 } 1320 mPendingInstalls.clear(); 1321 } 1322 } 1323 break; 1324 } 1325 case MCS_UNBIND: { 1326 // If there is no actual work left, then time to unbind. 1327 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1328 1329 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1330 if (mBound) { 1331 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1332 1333 disconnectService(); 1334 } 1335 } else if (mPendingInstalls.size() > 0) { 1336 // There are more pending requests in queue. 1337 // Just post MCS_BOUND message to trigger processing 1338 // of next pending install. 1339 mHandler.sendEmptyMessage(MCS_BOUND); 1340 } 1341 1342 break; 1343 } 1344 case MCS_GIVE_UP: { 1345 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1346 HandlerParams params = mPendingInstalls.remove(0); 1347 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1348 System.identityHashCode(params)); 1349 break; 1350 } 1351 case SEND_PENDING_BROADCAST: { 1352 String packages[]; 1353 ArrayList<String> components[]; 1354 int size = 0; 1355 int uids[]; 1356 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1357 synchronized (mPackages) { 1358 if (mPendingBroadcasts == null) { 1359 return; 1360 } 1361 size = mPendingBroadcasts.size(); 1362 if (size <= 0) { 1363 // Nothing to be done. Just return 1364 return; 1365 } 1366 packages = new String[size]; 1367 components = new ArrayList[size]; 1368 uids = new int[size]; 1369 int i = 0; // filling out the above arrays 1370 1371 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1372 int packageUserId = mPendingBroadcasts.userIdAt(n); 1373 Iterator<Map.Entry<String, ArrayList<String>>> it 1374 = mPendingBroadcasts.packagesForUserId(packageUserId) 1375 .entrySet().iterator(); 1376 while (it.hasNext() && i < size) { 1377 Map.Entry<String, ArrayList<String>> ent = it.next(); 1378 packages[i] = ent.getKey(); 1379 components[i] = ent.getValue(); 1380 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1381 uids[i] = (ps != null) 1382 ? UserHandle.getUid(packageUserId, ps.appId) 1383 : -1; 1384 i++; 1385 } 1386 } 1387 size = i; 1388 mPendingBroadcasts.clear(); 1389 } 1390 // Send broadcasts 1391 for (int i = 0; i < size; i++) { 1392 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1393 } 1394 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1395 break; 1396 } 1397 case START_CLEANING_PACKAGE: { 1398 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1399 final String packageName = (String)msg.obj; 1400 final int userId = msg.arg1; 1401 final boolean andCode = msg.arg2 != 0; 1402 synchronized (mPackages) { 1403 if (userId == UserHandle.USER_ALL) { 1404 int[] users = sUserManager.getUserIds(); 1405 for (int user : users) { 1406 mSettings.addPackageToCleanLPw( 1407 new PackageCleanItem(user, packageName, andCode)); 1408 } 1409 } else { 1410 mSettings.addPackageToCleanLPw( 1411 new PackageCleanItem(userId, packageName, andCode)); 1412 } 1413 } 1414 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1415 startCleaningPackages(); 1416 } break; 1417 case POST_INSTALL: { 1418 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1419 1420 PostInstallData data = mRunningInstalls.get(msg.arg1); 1421 mRunningInstalls.delete(msg.arg1); 1422 boolean deleteOld = false; 1423 1424 if (data != null) { 1425 InstallArgs args = data.args; 1426 PackageInstalledInfo res = data.res; 1427 1428 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1429 final String packageName = res.pkg.applicationInfo.packageName; 1430 res.removedInfo.sendBroadcast(false, true, false); 1431 Bundle extras = new Bundle(1); 1432 extras.putInt(Intent.EXTRA_UID, res.uid); 1433 1434 // Now that we successfully installed the package, grant runtime 1435 // permissions if requested before broadcasting the install. 1436 if ((args.installFlags 1437 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 1438 && res.pkg.applicationInfo.targetSdkVersion 1439 >= Build.VERSION_CODES.M) { 1440 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1441 args.installGrantPermissions); 1442 } 1443 1444 synchronized (mPackages) { 1445 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1446 } 1447 1448 // Determine the set of users who are adding this 1449 // package for the first time vs. those who are seeing 1450 // an update. 1451 int[] firstUsers; 1452 int[] updateUsers = new int[0]; 1453 if (res.origUsers == null || res.origUsers.length == 0) { 1454 firstUsers = res.newUsers; 1455 } else { 1456 firstUsers = new int[0]; 1457 for (int i=0; i<res.newUsers.length; i++) { 1458 int user = res.newUsers[i]; 1459 boolean isNew = true; 1460 for (int j=0; j<res.origUsers.length; j++) { 1461 if (res.origUsers[j] == user) { 1462 isNew = false; 1463 break; 1464 } 1465 } 1466 if (isNew) { 1467 int[] newFirst = new int[firstUsers.length+1]; 1468 System.arraycopy(firstUsers, 0, newFirst, 0, 1469 firstUsers.length); 1470 newFirst[firstUsers.length] = user; 1471 firstUsers = newFirst; 1472 } else { 1473 int[] newUpdate = new int[updateUsers.length+1]; 1474 System.arraycopy(updateUsers, 0, newUpdate, 0, 1475 updateUsers.length); 1476 newUpdate[updateUsers.length] = user; 1477 updateUsers = newUpdate; 1478 } 1479 } 1480 } 1481 // don't broadcast for ephemeral installs/updates 1482 final boolean isEphemeral = isEphemeral(res.pkg); 1483 if (!isEphemeral) { 1484 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1485 extras, 0 /*flags*/, null /*targetPackage*/, 1486 null /*finishedReceiver*/, firstUsers); 1487 } 1488 final boolean update = res.removedInfo.removedPackage != null; 1489 if (update) { 1490 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1491 } 1492 if (!isEphemeral) { 1493 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1494 extras, 0 /*flags*/, null /*targetPackage*/, 1495 null /*finishedReceiver*/, updateUsers); 1496 } 1497 if (update) { 1498 if (!isEphemeral) { 1499 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1500 packageName, extras, 0 /*flags*/, 1501 null /*targetPackage*/, null /*finishedReceiver*/, 1502 updateUsers); 1503 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1504 null /*package*/, null /*extras*/, 0 /*flags*/, 1505 packageName /*targetPackage*/, 1506 null /*finishedReceiver*/, updateUsers); 1507 } 1508 1509 // treat asec-hosted packages like removable media on upgrade 1510 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1511 if (DEBUG_INSTALL) { 1512 Slog.i(TAG, "upgrading pkg " + res.pkg 1513 + " is ASEC-hosted -> AVAILABLE"); 1514 } 1515 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1516 ArrayList<String> pkgList = new ArrayList<String>(1); 1517 pkgList.add(packageName); 1518 sendResourcesChangedBroadcast(true, true, 1519 pkgList,uidArray, null); 1520 } 1521 } 1522 if (res.removedInfo.args != null) { 1523 // Remove the replaced package's older resources safely now 1524 deleteOld = true; 1525 } 1526 1527 1528 // Work that needs to happen on first install within each user 1529 if (firstUsers.length > 0) { 1530 for (int userId : firstUsers) { 1531 synchronized (mPackages) { 1532 // If this app is a browser and it's newly-installed for 1533 // some users, clear any default-browser state in those 1534 // users. The app's nature doesn't depend on the user, 1535 // so we can just check its browser nature in any user 1536 // and generalize. 1537 if (packageIsBrowser(packageName, firstUsers[0])) { 1538 mSettings.setDefaultBrowserPackageNameLPw( 1539 null, userId); 1540 } 1541 1542 // We may also need to apply pending (restored) runtime 1543 // permission grants within these users. 1544 mSettings.applyPendingPermissionGrantsLPw( 1545 packageName, userId); 1546 } 1547 } 1548 } 1549 // Log current value of "unknown sources" setting 1550 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1551 getUnknownSourcesSettings()); 1552 } 1553 // Force a gc to clear up things 1554 Runtime.getRuntime().gc(); 1555 // We delete after a gc for applications on sdcard. 1556 if (deleteOld) { 1557 synchronized (mInstallLock) { 1558 res.removedInfo.args.doPostDeleteLI(true); 1559 } 1560 } 1561 if (args.observer != null) { 1562 try { 1563 Bundle extras = extrasForInstallResult(res); 1564 args.observer.onPackageInstalled(res.name, res.returnCode, 1565 res.returnMsg, extras); 1566 } catch (RemoteException e) { 1567 Slog.i(TAG, "Observer no longer exists."); 1568 } 1569 } 1570 if (args.traceMethod != null) { 1571 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1572 args.traceCookie); 1573 } 1574 return; 1575 } else { 1576 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1577 } 1578 1579 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1580 } break; 1581 case UPDATED_MEDIA_STATUS: { 1582 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1583 boolean reportStatus = msg.arg1 == 1; 1584 boolean doGc = msg.arg2 == 1; 1585 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1586 if (doGc) { 1587 // Force a gc to clear up stale containers. 1588 Runtime.getRuntime().gc(); 1589 } 1590 if (msg.obj != null) { 1591 @SuppressWarnings("unchecked") 1592 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1593 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1594 // Unload containers 1595 unloadAllContainers(args); 1596 } 1597 if (reportStatus) { 1598 try { 1599 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1600 PackageHelper.getMountService().finishMediaUpdate(); 1601 } catch (RemoteException e) { 1602 Log.e(TAG, "MountService not running?"); 1603 } 1604 } 1605 } break; 1606 case WRITE_SETTINGS: { 1607 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1608 synchronized (mPackages) { 1609 removeMessages(WRITE_SETTINGS); 1610 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1611 mSettings.writeLPr(); 1612 mDirtyUsers.clear(); 1613 } 1614 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1615 } break; 1616 case WRITE_PACKAGE_RESTRICTIONS: { 1617 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1618 synchronized (mPackages) { 1619 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1620 for (int userId : mDirtyUsers) { 1621 mSettings.writePackageRestrictionsLPr(userId); 1622 } 1623 mDirtyUsers.clear(); 1624 } 1625 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1626 } break; 1627 case CHECK_PENDING_VERIFICATION: { 1628 final int verificationId = msg.arg1; 1629 final PackageVerificationState state = mPendingVerification.get(verificationId); 1630 1631 if ((state != null) && !state.timeoutExtended()) { 1632 final InstallArgs args = state.getInstallArgs(); 1633 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1634 1635 Slog.i(TAG, "Verification timed out for " + originUri); 1636 mPendingVerification.remove(verificationId); 1637 1638 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1639 1640 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1641 Slog.i(TAG, "Continuing with installation of " + originUri); 1642 state.setVerifierResponse(Binder.getCallingUid(), 1643 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1644 broadcastPackageVerified(verificationId, originUri, 1645 PackageManager.VERIFICATION_ALLOW, 1646 state.getInstallArgs().getUser()); 1647 try { 1648 ret = args.copyApk(mContainerService, true); 1649 } catch (RemoteException e) { 1650 Slog.e(TAG, "Could not contact the ContainerService"); 1651 } 1652 } else { 1653 broadcastPackageVerified(verificationId, originUri, 1654 PackageManager.VERIFICATION_REJECT, 1655 state.getInstallArgs().getUser()); 1656 } 1657 1658 Trace.asyncTraceEnd( 1659 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1660 1661 processPendingInstall(args, ret); 1662 mHandler.sendEmptyMessage(MCS_UNBIND); 1663 } 1664 break; 1665 } 1666 case PACKAGE_VERIFIED: { 1667 final int verificationId = msg.arg1; 1668 1669 final PackageVerificationState state = mPendingVerification.get(verificationId); 1670 if (state == null) { 1671 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1672 break; 1673 } 1674 1675 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1676 1677 state.setVerifierResponse(response.callerUid, response.code); 1678 1679 if (state.isVerificationComplete()) { 1680 mPendingVerification.remove(verificationId); 1681 1682 final InstallArgs args = state.getInstallArgs(); 1683 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1684 1685 int ret; 1686 if (state.isInstallAllowed()) { 1687 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1688 broadcastPackageVerified(verificationId, originUri, 1689 response.code, state.getInstallArgs().getUser()); 1690 try { 1691 ret = args.copyApk(mContainerService, true); 1692 } catch (RemoteException e) { 1693 Slog.e(TAG, "Could not contact the ContainerService"); 1694 } 1695 } else { 1696 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1697 } 1698 1699 Trace.asyncTraceEnd( 1700 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1701 1702 processPendingInstall(args, ret); 1703 mHandler.sendEmptyMessage(MCS_UNBIND); 1704 } 1705 1706 break; 1707 } 1708 case START_INTENT_FILTER_VERIFICATIONS: { 1709 IFVerificationParams params = (IFVerificationParams) msg.obj; 1710 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1711 params.replacing, params.pkg); 1712 break; 1713 } 1714 case INTENT_FILTER_VERIFIED: { 1715 final int verificationId = msg.arg1; 1716 1717 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1718 verificationId); 1719 if (state == null) { 1720 Slog.w(TAG, "Invalid IntentFilter verification token " 1721 + verificationId + " received"); 1722 break; 1723 } 1724 1725 final int userId = state.getUserId(); 1726 1727 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1728 "Processing IntentFilter verification with token:" 1729 + verificationId + " and userId:" + userId); 1730 1731 final IntentFilterVerificationResponse response = 1732 (IntentFilterVerificationResponse) msg.obj; 1733 1734 state.setVerifierResponse(response.callerUid, response.code); 1735 1736 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1737 "IntentFilter verification with token:" + verificationId 1738 + " and userId:" + userId 1739 + " is settings verifier response with response code:" 1740 + response.code); 1741 1742 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1743 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1744 + response.getFailedDomainsString()); 1745 } 1746 1747 if (state.isVerificationComplete()) { 1748 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1749 } else { 1750 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1751 "IntentFilter verification with token:" + verificationId 1752 + " was not said to be complete"); 1753 } 1754 1755 break; 1756 } 1757 } 1758 } 1759 } 1760 1761 private StorageEventListener mStorageListener = new StorageEventListener() { 1762 @Override 1763 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1764 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1765 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1766 final String volumeUuid = vol.getFsUuid(); 1767 1768 // Clean up any users or apps that were removed or recreated 1769 // while this volume was missing 1770 reconcileUsers(volumeUuid); 1771 reconcileApps(volumeUuid); 1772 1773 // Clean up any install sessions that expired or were 1774 // cancelled while this volume was missing 1775 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1776 1777 loadPrivatePackages(vol); 1778 1779 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1780 unloadPrivatePackages(vol); 1781 } 1782 } 1783 1784 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1785 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1786 updateExternalMediaStatus(true, false); 1787 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1788 updateExternalMediaStatus(false, false); 1789 } 1790 } 1791 } 1792 1793 @Override 1794 public void onVolumeForgotten(String fsUuid) { 1795 if (TextUtils.isEmpty(fsUuid)) { 1796 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1797 return; 1798 } 1799 1800 // Remove any apps installed on the forgotten volume 1801 synchronized (mPackages) { 1802 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1803 for (PackageSetting ps : packages) { 1804 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1805 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1806 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1807 } 1808 1809 mSettings.onVolumeForgotten(fsUuid); 1810 mSettings.writeLPr(); 1811 } 1812 } 1813 }; 1814 1815 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1816 String[] grantedPermissions) { 1817 if (userId >= UserHandle.USER_SYSTEM) { 1818 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1819 } else if (userId == UserHandle.USER_ALL) { 1820 final int[] userIds; 1821 synchronized (mPackages) { 1822 userIds = UserManagerService.getInstance().getUserIds(); 1823 } 1824 for (int someUserId : userIds) { 1825 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1826 } 1827 } 1828 1829 // We could have touched GID membership, so flush out packages.list 1830 synchronized (mPackages) { 1831 mSettings.writePackageListLPr(); 1832 } 1833 } 1834 1835 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1836 String[] grantedPermissions) { 1837 SettingBase sb = (SettingBase) pkg.mExtras; 1838 if (sb == null) { 1839 return; 1840 } 1841 1842 PermissionsState permissionsState = sb.getPermissionsState(); 1843 1844 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1845 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1846 1847 synchronized (mPackages) { 1848 for (String permission : pkg.requestedPermissions) { 1849 BasePermission bp = mSettings.mPermissions.get(permission); 1850 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1851 && (grantedPermissions == null 1852 || ArrayUtils.contains(grantedPermissions, permission))) { 1853 final int flags = permissionsState.getPermissionFlags(permission, userId); 1854 // Installer cannot change immutable permissions. 1855 if ((flags & immutableFlags) == 0) { 1856 grantRuntimePermission(pkg.packageName, permission, userId); 1857 } 1858 } 1859 } 1860 } 1861 } 1862 1863 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1864 Bundle extras = null; 1865 switch (res.returnCode) { 1866 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1867 extras = new Bundle(); 1868 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1869 res.origPermission); 1870 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1871 res.origPackage); 1872 break; 1873 } 1874 case PackageManager.INSTALL_SUCCEEDED: { 1875 extras = new Bundle(); 1876 extras.putBoolean(Intent.EXTRA_REPLACING, 1877 res.removedInfo != null && res.removedInfo.removedPackage != null); 1878 break; 1879 } 1880 } 1881 return extras; 1882 } 1883 1884 void scheduleWriteSettingsLocked() { 1885 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1886 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1887 } 1888 } 1889 1890 void scheduleWritePackageRestrictionsLocked(int userId) { 1891 if (!sUserManager.exists(userId)) return; 1892 mDirtyUsers.add(userId); 1893 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1894 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1895 } 1896 } 1897 1898 public static PackageManagerService main(Context context, Installer installer, 1899 boolean factoryTest, boolean onlyCore) { 1900 PackageManagerService m = new PackageManagerService(context, installer, 1901 factoryTest, onlyCore); 1902 m.enableSystemUserPackages(); 1903 ServiceManager.addService("package", m); 1904 return m; 1905 } 1906 1907 private void enableSystemUserPackages() { 1908 if (!UserManager.isSplitSystemUser()) { 1909 return; 1910 } 1911 // For system user, enable apps based on the following conditions: 1912 // - app is whitelisted or belong to one of these groups: 1913 // -- system app which has no launcher icons 1914 // -- system app which has INTERACT_ACROSS_USERS permission 1915 // -- system IME app 1916 // - app is not in the blacklist 1917 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1918 Set<String> enableApps = new ArraySet<>(); 1919 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1920 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1921 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1922 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1923 enableApps.addAll(wlApps); 1924 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1925 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1926 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1927 enableApps.removeAll(blApps); 1928 Log.i(TAG, "Applications installed for system user: " + enableApps); 1929 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1930 UserHandle.SYSTEM); 1931 final int allAppsSize = allAps.size(); 1932 synchronized (mPackages) { 1933 for (int i = 0; i < allAppsSize; i++) { 1934 String pName = allAps.get(i); 1935 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1936 // Should not happen, but we shouldn't be failing if it does 1937 if (pkgSetting == null) { 1938 continue; 1939 } 1940 boolean install = enableApps.contains(pName); 1941 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 1942 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 1943 + " for system user"); 1944 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 1945 } 1946 } 1947 } 1948 } 1949 1950 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1951 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1952 Context.DISPLAY_SERVICE); 1953 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1954 } 1955 1956 public PackageManagerService(Context context, Installer installer, 1957 boolean factoryTest, boolean onlyCore) { 1958 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1959 SystemClock.uptimeMillis()); 1960 1961 if (mSdkVersion <= 0) { 1962 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1963 } 1964 1965 mContext = context; 1966 mFactoryTest = factoryTest; 1967 mOnlyCore = onlyCore; 1968 mMetrics = new DisplayMetrics(); 1969 mSettings = new Settings(mPackages); 1970 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1971 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1972 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1973 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1974 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1975 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1976 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1977 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1978 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1979 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1980 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1981 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1982 1983 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1984 if (separateProcesses != null && separateProcesses.length() > 0) { 1985 if ("*".equals(separateProcesses)) { 1986 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1987 mSeparateProcesses = null; 1988 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1989 } else { 1990 mDefParseFlags = 0; 1991 mSeparateProcesses = separateProcesses.split(","); 1992 Slog.w(TAG, "Running with debug.separate_processes: " 1993 + separateProcesses); 1994 } 1995 } else { 1996 mDefParseFlags = 0; 1997 mSeparateProcesses = null; 1998 } 1999 2000 mInstaller = installer; 2001 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2002 "*dexopt*"); 2003 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2004 2005 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2006 FgThread.get().getLooper()); 2007 2008 getDefaultDisplayMetrics(context, mMetrics); 2009 2010 SystemConfig systemConfig = SystemConfig.getInstance(); 2011 mGlobalGids = systemConfig.getGlobalGids(); 2012 mSystemPermissions = systemConfig.getSystemPermissions(); 2013 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2014 2015 synchronized (mInstallLock) { 2016 // writer 2017 synchronized (mPackages) { 2018 mHandlerThread = new ServiceThread(TAG, 2019 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2020 mHandlerThread.start(); 2021 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2022 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2023 2024 File dataDir = Environment.getDataDirectory(); 2025 mAppInstallDir = new File(dataDir, "app"); 2026 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2027 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2028 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2029 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2030 2031 sUserManager = new UserManagerService(context, this, mPackages); 2032 2033 // Propagate permission configuration in to package manager. 2034 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2035 = systemConfig.getPermissions(); 2036 for (int i=0; i<permConfig.size(); i++) { 2037 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2038 BasePermission bp = mSettings.mPermissions.get(perm.name); 2039 if (bp == null) { 2040 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2041 mSettings.mPermissions.put(perm.name, bp); 2042 } 2043 if (perm.gids != null) { 2044 bp.setGids(perm.gids, perm.perUser); 2045 } 2046 } 2047 2048 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2049 for (int i=0; i<libConfig.size(); i++) { 2050 mSharedLibraries.put(libConfig.keyAt(i), 2051 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2052 } 2053 2054 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2055 2056 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2057 2058 String customResolverActivity = Resources.getSystem().getString( 2059 R.string.config_customResolverActivity); 2060 if (TextUtils.isEmpty(customResolverActivity)) { 2061 customResolverActivity = null; 2062 } else { 2063 mCustomResolverComponentName = ComponentName.unflattenFromString( 2064 customResolverActivity); 2065 } 2066 2067 long startTime = SystemClock.uptimeMillis(); 2068 2069 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2070 startTime); 2071 2072 // Set flag to monitor and not change apk file paths when 2073 // scanning install directories. 2074 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2075 2076 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2077 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2078 2079 if (bootClassPath == null) { 2080 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2081 } 2082 2083 if (systemServerClassPath == null) { 2084 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2085 } 2086 2087 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2088 final String[] dexCodeInstructionSets = 2089 getDexCodeInstructionSets( 2090 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2091 2092 /** 2093 * Ensure all external libraries have had dexopt run on them. 2094 */ 2095 if (mSharedLibraries.size() > 0) { 2096 // NOTE: For now, we're compiling these system "shared libraries" 2097 // (and framework jars) into all available architectures. It's possible 2098 // to compile them only when we come across an app that uses them (there's 2099 // already logic for that in scanPackageLI) but that adds some complexity. 2100 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2101 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2102 final String lib = libEntry.path; 2103 if (lib == null) { 2104 continue; 2105 } 2106 2107 try { 2108 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2109 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2110 // Shared libraries do not have profiles so we perform a full 2111 // AOT compilation. 2112 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2113 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2114 StorageManager.UUID_PRIVATE_INTERNAL, 2115 false /*useProfiles*/); 2116 } 2117 } catch (FileNotFoundException e) { 2118 Slog.w(TAG, "Library not found: " + lib); 2119 } catch (IOException | InstallerException e) { 2120 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2121 + e.getMessage()); 2122 } 2123 } 2124 } 2125 } 2126 2127 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2128 2129 final VersionInfo ver = mSettings.getInternalVersion(); 2130 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2131 // when upgrading from pre-M, promote system app permissions from install to runtime 2132 mPromoteSystemApps = 2133 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2134 2135 // save off the names of pre-existing system packages prior to scanning; we don't 2136 // want to automatically grant runtime permissions for new system apps 2137 if (mPromoteSystemApps) { 2138 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2139 while (pkgSettingIter.hasNext()) { 2140 PackageSetting ps = pkgSettingIter.next(); 2141 if (isSystemApp(ps)) { 2142 mExistingSystemPackages.add(ps.name); 2143 } 2144 } 2145 } 2146 2147 // Collect vendor overlay packages. 2148 // (Do this before scanning any apps.) 2149 // For security and version matching reason, only consider 2150 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2151 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2152 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2153 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2154 2155 // Find base frameworks (resource packages without code). 2156 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2157 | PackageParser.PARSE_IS_SYSTEM_DIR 2158 | PackageParser.PARSE_IS_PRIVILEGED, 2159 scanFlags | SCAN_NO_DEX, 0); 2160 2161 // Collected privileged system packages. 2162 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2163 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2164 | PackageParser.PARSE_IS_SYSTEM_DIR 2165 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2166 2167 // Collect ordinary system packages. 2168 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2169 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2170 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2171 2172 // Collect all vendor packages. 2173 File vendorAppDir = new File("/vendor/app"); 2174 try { 2175 vendorAppDir = vendorAppDir.getCanonicalFile(); 2176 } catch (IOException e) { 2177 // failed to look up canonical path, continue with original one 2178 } 2179 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2180 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2181 2182 // Collect all OEM packages. 2183 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2184 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2185 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2186 2187 // Prune any system packages that no longer exist. 2188 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2189 if (!mOnlyCore) { 2190 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2191 while (psit.hasNext()) { 2192 PackageSetting ps = psit.next(); 2193 2194 /* 2195 * If this is not a system app, it can't be a 2196 * disable system app. 2197 */ 2198 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2199 continue; 2200 } 2201 2202 /* 2203 * If the package is scanned, it's not erased. 2204 */ 2205 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2206 if (scannedPkg != null) { 2207 /* 2208 * If the system app is both scanned and in the 2209 * disabled packages list, then it must have been 2210 * added via OTA. Remove it from the currently 2211 * scanned package so the previously user-installed 2212 * application can be scanned. 2213 */ 2214 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2215 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2216 + ps.name + "; removing system app. Last known codePath=" 2217 + ps.codePathString + ", installStatus=" + ps.installStatus 2218 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2219 + scannedPkg.mVersionCode); 2220 removePackageLI(ps, true); 2221 mExpectingBetter.put(ps.name, ps.codePath); 2222 } 2223 2224 continue; 2225 } 2226 2227 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2228 psit.remove(); 2229 logCriticalInfo(Log.WARN, "System package " + ps.name 2230 + " no longer exists; wiping its data"); 2231 removeDataDirsLI(null, ps.name); 2232 } else { 2233 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2234 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2235 possiblyDeletedUpdatedSystemApps.add(ps.name); 2236 } 2237 } 2238 } 2239 } 2240 2241 //look for any incomplete package installations 2242 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2243 //clean up list 2244 for(int i = 0; i < deletePkgsList.size(); i++) { 2245 //clean up here 2246 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2247 } 2248 //delete tmp files 2249 deleteTempPackageFiles(); 2250 2251 // Remove any shared userIDs that have no associated packages 2252 mSettings.pruneSharedUsersLPw(); 2253 2254 if (!mOnlyCore) { 2255 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2256 SystemClock.uptimeMillis()); 2257 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2258 2259 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2260 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2261 2262 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2263 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2264 2265 /** 2266 * Remove disable package settings for any updated system 2267 * apps that were removed via an OTA. If they're not a 2268 * previously-updated app, remove them completely. 2269 * Otherwise, just revoke their system-level permissions. 2270 */ 2271 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2272 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2273 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2274 2275 String msg; 2276 if (deletedPkg == null) { 2277 msg = "Updated system package " + deletedAppName 2278 + " no longer exists; wiping its data"; 2279 removeDataDirsLI(null, deletedAppName); 2280 } else { 2281 msg = "Updated system app + " + deletedAppName 2282 + " no longer present; removing system privileges for " 2283 + deletedAppName; 2284 2285 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2286 2287 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2288 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2289 } 2290 logCriticalInfo(Log.WARN, msg); 2291 } 2292 2293 /** 2294 * Make sure all system apps that we expected to appear on 2295 * the userdata partition actually showed up. If they never 2296 * appeared, crawl back and revive the system version. 2297 */ 2298 for (int i = 0; i < mExpectingBetter.size(); i++) { 2299 final String packageName = mExpectingBetter.keyAt(i); 2300 if (!mPackages.containsKey(packageName)) { 2301 final File scanFile = mExpectingBetter.valueAt(i); 2302 2303 logCriticalInfo(Log.WARN, "Expected better " + packageName 2304 + " but never showed up; reverting to system"); 2305 2306 final int reparseFlags; 2307 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2308 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2309 | PackageParser.PARSE_IS_SYSTEM_DIR 2310 | PackageParser.PARSE_IS_PRIVILEGED; 2311 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2312 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2313 | PackageParser.PARSE_IS_SYSTEM_DIR; 2314 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2315 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2316 | PackageParser.PARSE_IS_SYSTEM_DIR; 2317 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2318 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2319 | PackageParser.PARSE_IS_SYSTEM_DIR; 2320 } else { 2321 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2322 continue; 2323 } 2324 2325 mSettings.enableSystemPackageLPw(packageName); 2326 2327 try { 2328 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2329 } catch (PackageManagerException e) { 2330 Slog.e(TAG, "Failed to parse original system package: " 2331 + e.getMessage()); 2332 } 2333 } 2334 } 2335 } 2336 mExpectingBetter.clear(); 2337 2338 // Now that we know all of the shared libraries, update all clients to have 2339 // the correct library paths. 2340 updateAllSharedLibrariesLPw(); 2341 2342 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2343 // NOTE: We ignore potential failures here during a system scan (like 2344 // the rest of the commands above) because there's precious little we 2345 // can do about it. A settings error is reported, though. 2346 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2347 false /* boot complete */); 2348 } 2349 2350 // Now that we know all the packages we are keeping, 2351 // read and update their last usage times. 2352 mPackageUsage.readLP(); 2353 2354 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2355 SystemClock.uptimeMillis()); 2356 Slog.i(TAG, "Time to scan packages: " 2357 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2358 + " seconds"); 2359 2360 // If the platform SDK has changed since the last time we booted, 2361 // we need to re-grant app permission to catch any new ones that 2362 // appear. This is really a hack, and means that apps can in some 2363 // cases get permissions that the user didn't initially explicitly 2364 // allow... it would be nice to have some better way to handle 2365 // this situation. 2366 int updateFlags = UPDATE_PERMISSIONS_ALL; 2367 if (ver.sdkVersion != mSdkVersion) { 2368 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2369 + mSdkVersion + "; regranting permissions for internal storage"); 2370 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2371 } 2372 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2373 ver.sdkVersion = mSdkVersion; 2374 2375 // If this is the first boot or an update from pre-M, and it is a normal 2376 // boot, then we need to initialize the default preferred apps across 2377 // all defined users. 2378 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2379 for (UserInfo user : sUserManager.getUsers(true)) { 2380 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2381 applyFactoryDefaultBrowserLPw(user.id); 2382 primeDomainVerificationsLPw(user.id); 2383 } 2384 } 2385 2386 // Prepare storage for system user really early during boot, 2387 // since core system apps like SettingsProvider and SystemUI 2388 // can't wait for user to start 2389 final int flags; 2390 if (StorageManager.isFileBasedEncryptionEnabled()) { 2391 flags = Installer.FLAG_DE_STORAGE; 2392 } else { 2393 flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE; 2394 } 2395 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, flags); 2396 2397 // If this is first boot after an OTA, and a normal boot, then 2398 // we need to clear code cache directories. 2399 if (mIsUpgrade && !onlyCore) { 2400 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2401 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2402 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2403 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2404 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2405 } 2406 } 2407 ver.fingerprint = Build.FINGERPRINT; 2408 } 2409 2410 checkDefaultBrowser(); 2411 2412 // clear only after permissions and other defaults have been updated 2413 mExistingSystemPackages.clear(); 2414 mPromoteSystemApps = false; 2415 2416 // All the changes are done during package scanning. 2417 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2418 2419 // can downgrade to reader 2420 mSettings.writeLPr(); 2421 2422 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2423 SystemClock.uptimeMillis()); 2424 2425 if (!mOnlyCore) { 2426 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2427 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2428 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2429 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2430 mIntentFilterVerifierComponent); 2431 } else { 2432 mRequiredVerifierPackage = null; 2433 mRequiredInstallerPackage = null; 2434 mIntentFilterVerifierComponent = null; 2435 mIntentFilterVerifier = null; 2436 } 2437 2438 mInstallerService = new PackageInstallerService(context, this); 2439 2440 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2441 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2442 // both the installer and resolver must be present to enable ephemeral 2443 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2444 if (DEBUG_EPHEMERAL) { 2445 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2446 + " installer:" + ephemeralInstallerComponent); 2447 } 2448 mEphemeralResolverComponent = ephemeralResolverComponent; 2449 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2450 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2451 mEphemeralResolverConnection = 2452 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2453 } else { 2454 if (DEBUG_EPHEMERAL) { 2455 final String missingComponent = 2456 (ephemeralResolverComponent == null) 2457 ? (ephemeralInstallerComponent == null) 2458 ? "resolver and installer" 2459 : "resolver" 2460 : "installer"; 2461 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2462 } 2463 mEphemeralResolverComponent = null; 2464 mEphemeralInstallerComponent = null; 2465 mEphemeralResolverConnection = null; 2466 } 2467 2468 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2469 } // synchronized (mPackages) 2470 } // synchronized (mInstallLock) 2471 2472 // Now after opening every single application zip, make sure they 2473 // are all flushed. Not really needed, but keeps things nice and 2474 // tidy. 2475 Runtime.getRuntime().gc(); 2476 2477 // The initial scanning above does many calls into installd while 2478 // holding the mPackages lock, but we're mostly interested in yelling 2479 // once we have a booted system. 2480 mInstaller.setWarnIfHeld(mPackages); 2481 2482 // Expose private service for system components to use. 2483 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2484 } 2485 2486 @Override 2487 public boolean isFirstBoot() { 2488 return !mRestoredSettings; 2489 } 2490 2491 @Override 2492 public boolean isOnlyCoreApps() { 2493 return mOnlyCore; 2494 } 2495 2496 @Override 2497 public boolean isUpgrade() { 2498 return mIsUpgrade; 2499 } 2500 2501 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2502 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2503 2504 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2505 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2506 if (matches.size() == 1) { 2507 return matches.get(0).getComponentInfo().packageName; 2508 } else { 2509 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2510 return null; 2511 } 2512 } 2513 2514 private @NonNull String getRequiredInstallerLPr() { 2515 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2516 intent.addCategory(Intent.CATEGORY_DEFAULT); 2517 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2518 2519 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2520 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2521 if (matches.size() == 1) { 2522 return matches.get(0).getComponentInfo().packageName; 2523 } else { 2524 throw new RuntimeException("There must be exactly one installer; found " + matches); 2525 } 2526 } 2527 2528 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2529 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2530 2531 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2532 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2533 ResolveInfo best = null; 2534 final int N = matches.size(); 2535 for (int i = 0; i < N; i++) { 2536 final ResolveInfo cur = matches.get(i); 2537 final String packageName = cur.getComponentInfo().packageName; 2538 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2539 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2540 continue; 2541 } 2542 2543 if (best == null || cur.priority > best.priority) { 2544 best = cur; 2545 } 2546 } 2547 2548 if (best != null) { 2549 return best.getComponentInfo().getComponentName(); 2550 } else { 2551 throw new RuntimeException("There must be at least one intent filter verifier"); 2552 } 2553 } 2554 2555 private @Nullable ComponentName getEphemeralResolverLPr() { 2556 final String[] packageArray = 2557 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2558 if (packageArray.length == 0) { 2559 if (DEBUG_EPHEMERAL) { 2560 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2561 } 2562 return null; 2563 } 2564 2565 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2566 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null, 2567 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2568 2569 final int N = resolvers.size(); 2570 if (N == 0) { 2571 if (DEBUG_EPHEMERAL) { 2572 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2573 } 2574 return null; 2575 } 2576 2577 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2578 for (int i = 0; i < N; i++) { 2579 final ResolveInfo info = resolvers.get(i); 2580 2581 if (info.serviceInfo == null) { 2582 continue; 2583 } 2584 2585 final String packageName = info.serviceInfo.packageName; 2586 if (!possiblePackages.contains(packageName)) { 2587 if (DEBUG_EPHEMERAL) { 2588 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2589 + " pkg: " + packageName + ", info:" + info); 2590 } 2591 continue; 2592 } 2593 2594 if (DEBUG_EPHEMERAL) { 2595 Slog.v(TAG, "Ephemeral resolver found;" 2596 + " pkg: " + packageName + ", info:" + info); 2597 } 2598 return new ComponentName(packageName, info.serviceInfo.name); 2599 } 2600 if (DEBUG_EPHEMERAL) { 2601 Slog.v(TAG, "Ephemeral resolver NOT found"); 2602 } 2603 return null; 2604 } 2605 2606 private @Nullable ComponentName getEphemeralInstallerLPr() { 2607 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2608 intent.addCategory(Intent.CATEGORY_DEFAULT); 2609 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2610 2611 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2612 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2613 if (matches.size() == 0) { 2614 return null; 2615 } else if (matches.size() == 1) { 2616 return matches.get(0).getComponentInfo().getComponentName(); 2617 } else { 2618 throw new RuntimeException( 2619 "There must be at most one ephemeral installer; found " + matches); 2620 } 2621 } 2622 2623 private void primeDomainVerificationsLPw(int userId) { 2624 if (DEBUG_DOMAIN_VERIFICATION) { 2625 Slog.d(TAG, "Priming domain verifications in user " + userId); 2626 } 2627 2628 SystemConfig systemConfig = SystemConfig.getInstance(); 2629 ArraySet<String> packages = systemConfig.getLinkedApps(); 2630 ArraySet<String> domains = new ArraySet<String>(); 2631 2632 for (String packageName : packages) { 2633 PackageParser.Package pkg = mPackages.get(packageName); 2634 if (pkg != null) { 2635 if (!pkg.isSystemApp()) { 2636 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2637 continue; 2638 } 2639 2640 domains.clear(); 2641 for (PackageParser.Activity a : pkg.activities) { 2642 for (ActivityIntentInfo filter : a.intents) { 2643 if (hasValidDomains(filter)) { 2644 domains.addAll(filter.getHostsList()); 2645 } 2646 } 2647 } 2648 2649 if (domains.size() > 0) { 2650 if (DEBUG_DOMAIN_VERIFICATION) { 2651 Slog.v(TAG, " + " + packageName); 2652 } 2653 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2654 // state w.r.t. the formal app-linkage "no verification attempted" state; 2655 // and then 'always' in the per-user state actually used for intent resolution. 2656 final IntentFilterVerificationInfo ivi; 2657 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2658 new ArrayList<String>(domains)); 2659 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2660 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2661 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2662 } else { 2663 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2664 + "' does not handle web links"); 2665 } 2666 } else { 2667 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2668 } 2669 } 2670 2671 scheduleWritePackageRestrictionsLocked(userId); 2672 scheduleWriteSettingsLocked(); 2673 } 2674 2675 private void applyFactoryDefaultBrowserLPw(int userId) { 2676 // The default browser app's package name is stored in a string resource, 2677 // with a product-specific overlay used for vendor customization. 2678 String browserPkg = mContext.getResources().getString( 2679 com.android.internal.R.string.default_browser); 2680 if (!TextUtils.isEmpty(browserPkg)) { 2681 // non-empty string => required to be a known package 2682 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2683 if (ps == null) { 2684 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2685 browserPkg = null; 2686 } else { 2687 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2688 } 2689 } 2690 2691 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2692 // default. If there's more than one, just leave everything alone. 2693 if (browserPkg == null) { 2694 calculateDefaultBrowserLPw(userId); 2695 } 2696 } 2697 2698 private void calculateDefaultBrowserLPw(int userId) { 2699 List<String> allBrowsers = resolveAllBrowserApps(userId); 2700 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2701 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2702 } 2703 2704 private List<String> resolveAllBrowserApps(int userId) { 2705 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2706 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2707 PackageManager.MATCH_ALL, userId); 2708 2709 final int count = list.size(); 2710 List<String> result = new ArrayList<String>(count); 2711 for (int i=0; i<count; i++) { 2712 ResolveInfo info = list.get(i); 2713 if (info.activityInfo == null 2714 || !info.handleAllWebDataURI 2715 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2716 || result.contains(info.activityInfo.packageName)) { 2717 continue; 2718 } 2719 result.add(info.activityInfo.packageName); 2720 } 2721 2722 return result; 2723 } 2724 2725 private boolean packageIsBrowser(String packageName, int userId) { 2726 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2727 PackageManager.MATCH_ALL, userId); 2728 final int N = list.size(); 2729 for (int i = 0; i < N; i++) { 2730 ResolveInfo info = list.get(i); 2731 if (packageName.equals(info.activityInfo.packageName)) { 2732 return true; 2733 } 2734 } 2735 return false; 2736 } 2737 2738 private void checkDefaultBrowser() { 2739 final int myUserId = UserHandle.myUserId(); 2740 final String packageName = getDefaultBrowserPackageName(myUserId); 2741 if (packageName != null) { 2742 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2743 if (info == null) { 2744 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2745 synchronized (mPackages) { 2746 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2747 } 2748 } 2749 } 2750 } 2751 2752 @Override 2753 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2754 throws RemoteException { 2755 try { 2756 return super.onTransact(code, data, reply, flags); 2757 } catch (RuntimeException e) { 2758 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2759 Slog.wtf(TAG, "Package Manager Crash", e); 2760 } 2761 throw e; 2762 } 2763 } 2764 2765 void cleanupInstallFailedPackage(PackageSetting ps) { 2766 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2767 2768 removeDataDirsLI(ps.volumeUuid, ps.name); 2769 if (ps.codePath != null) { 2770 removeCodePathLI(ps.codePath); 2771 } 2772 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2773 if (ps.resourcePath.isDirectory()) { 2774 FileUtils.deleteContents(ps.resourcePath); 2775 } 2776 ps.resourcePath.delete(); 2777 } 2778 mSettings.removePackageLPw(ps.name); 2779 } 2780 2781 static int[] appendInts(int[] cur, int[] add) { 2782 if (add == null) return cur; 2783 if (cur == null) return add; 2784 final int N = add.length; 2785 for (int i=0; i<N; i++) { 2786 cur = appendInt(cur, add[i]); 2787 } 2788 return cur; 2789 } 2790 2791 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2792 if (!sUserManager.exists(userId)) return null; 2793 final PackageSetting ps = (PackageSetting) p.mExtras; 2794 if (ps == null) { 2795 return null; 2796 } 2797 2798 final PermissionsState permissionsState = ps.getPermissionsState(); 2799 2800 final int[] gids = permissionsState.computeGids(userId); 2801 final Set<String> permissions = permissionsState.getPermissions(userId); 2802 final PackageUserState state = ps.readUserState(userId); 2803 2804 return PackageParser.generatePackageInfo(p, gids, flags, 2805 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2806 } 2807 2808 @Override 2809 public void checkPackageStartable(String packageName, int userId) { 2810 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2811 2812 synchronized (mPackages) { 2813 final PackageSetting ps = mSettings.mPackages.get(packageName); 2814 if (ps == null) { 2815 throw new SecurityException("Package " + packageName + " was not found!"); 2816 } 2817 2818 if (ps.frozen) { 2819 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2820 } 2821 2822 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2823 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2824 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2825 } 2826 } 2827 } 2828 2829 @Override 2830 public boolean isPackageAvailable(String packageName, int userId) { 2831 if (!sUserManager.exists(userId)) return false; 2832 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2833 synchronized (mPackages) { 2834 PackageParser.Package p = mPackages.get(packageName); 2835 if (p != null) { 2836 final PackageSetting ps = (PackageSetting) p.mExtras; 2837 if (ps != null) { 2838 final PackageUserState state = ps.readUserState(userId); 2839 if (state != null) { 2840 return PackageParser.isAvailable(state); 2841 } 2842 } 2843 } 2844 } 2845 return false; 2846 } 2847 2848 @Override 2849 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2850 if (!sUserManager.exists(userId)) return null; 2851 flags = updateFlagsForPackage(flags, userId, packageName); 2852 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2853 // reader 2854 synchronized (mPackages) { 2855 PackageParser.Package p = mPackages.get(packageName); 2856 if (DEBUG_PACKAGE_INFO) 2857 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2858 if (p != null) { 2859 return generatePackageInfo(p, flags, userId); 2860 } 2861 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2862 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2863 } 2864 } 2865 return null; 2866 } 2867 2868 @Override 2869 public String[] currentToCanonicalPackageNames(String[] names) { 2870 String[] out = new String[names.length]; 2871 // reader 2872 synchronized (mPackages) { 2873 for (int i=names.length-1; i>=0; i--) { 2874 PackageSetting ps = mSettings.mPackages.get(names[i]); 2875 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2876 } 2877 } 2878 return out; 2879 } 2880 2881 @Override 2882 public String[] canonicalToCurrentPackageNames(String[] names) { 2883 String[] out = new String[names.length]; 2884 // reader 2885 synchronized (mPackages) { 2886 for (int i=names.length-1; i>=0; i--) { 2887 String cur = mSettings.mRenamedPackages.get(names[i]); 2888 out[i] = cur != null ? cur : names[i]; 2889 } 2890 } 2891 return out; 2892 } 2893 2894 @Override 2895 public int getPackageUid(String packageName, int flags, int userId) { 2896 if (!sUserManager.exists(userId)) return -1; 2897 flags = updateFlagsForPackage(flags, userId, packageName); 2898 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2899 2900 // reader 2901 synchronized (mPackages) { 2902 final PackageParser.Package p = mPackages.get(packageName); 2903 if (p != null && p.isMatch(flags)) { 2904 return UserHandle.getUid(userId, p.applicationInfo.uid); 2905 } 2906 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2907 final PackageSetting ps = mSettings.mPackages.get(packageName); 2908 if (ps != null && ps.isMatch(flags)) { 2909 return UserHandle.getUid(userId, ps.appId); 2910 } 2911 } 2912 } 2913 2914 return -1; 2915 } 2916 2917 @Override 2918 public int[] getPackageGids(String packageName, int flags, int userId) { 2919 if (!sUserManager.exists(userId)) return null; 2920 flags = updateFlagsForPackage(flags, userId, packageName); 2921 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2922 "getPackageGids"); 2923 2924 // reader 2925 synchronized (mPackages) { 2926 final PackageParser.Package p = mPackages.get(packageName); 2927 if (p != null && p.isMatch(flags)) { 2928 PackageSetting ps = (PackageSetting) p.mExtras; 2929 return ps.getPermissionsState().computeGids(userId); 2930 } 2931 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2932 final PackageSetting ps = mSettings.mPackages.get(packageName); 2933 if (ps != null && ps.isMatch(flags)) { 2934 return ps.getPermissionsState().computeGids(userId); 2935 } 2936 } 2937 } 2938 2939 return null; 2940 } 2941 2942 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 2943 if (bp.perm != null) { 2944 return PackageParser.generatePermissionInfo(bp.perm, flags); 2945 } 2946 PermissionInfo pi = new PermissionInfo(); 2947 pi.name = bp.name; 2948 pi.packageName = bp.sourcePackage; 2949 pi.nonLocalizedLabel = bp.name; 2950 pi.protectionLevel = bp.protectionLevel; 2951 return pi; 2952 } 2953 2954 @Override 2955 public PermissionInfo getPermissionInfo(String name, int flags) { 2956 // reader 2957 synchronized (mPackages) { 2958 final BasePermission p = mSettings.mPermissions.get(name); 2959 if (p != null) { 2960 return generatePermissionInfo(p, flags); 2961 } 2962 return null; 2963 } 2964 } 2965 2966 @Override 2967 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2968 // reader 2969 synchronized (mPackages) { 2970 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2971 for (BasePermission p : mSettings.mPermissions.values()) { 2972 if (group == null) { 2973 if (p.perm == null || p.perm.info.group == null) { 2974 out.add(generatePermissionInfo(p, flags)); 2975 } 2976 } else { 2977 if (p.perm != null && group.equals(p.perm.info.group)) { 2978 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2979 } 2980 } 2981 } 2982 2983 if (out.size() > 0) { 2984 return out; 2985 } 2986 return mPermissionGroups.containsKey(group) ? out : null; 2987 } 2988 } 2989 2990 @Override 2991 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2992 // reader 2993 synchronized (mPackages) { 2994 return PackageParser.generatePermissionGroupInfo( 2995 mPermissionGroups.get(name), flags); 2996 } 2997 } 2998 2999 @Override 3000 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3001 // reader 3002 synchronized (mPackages) { 3003 final int N = mPermissionGroups.size(); 3004 ArrayList<PermissionGroupInfo> out 3005 = new ArrayList<PermissionGroupInfo>(N); 3006 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3007 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3008 } 3009 return out; 3010 } 3011 } 3012 3013 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3014 int userId) { 3015 if (!sUserManager.exists(userId)) return null; 3016 PackageSetting ps = mSettings.mPackages.get(packageName); 3017 if (ps != null) { 3018 if (ps.pkg == null) { 3019 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3020 flags, userId); 3021 if (pInfo != null) { 3022 return pInfo.applicationInfo; 3023 } 3024 return null; 3025 } 3026 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3027 ps.readUserState(userId), userId); 3028 } 3029 return null; 3030 } 3031 3032 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3033 int userId) { 3034 if (!sUserManager.exists(userId)) return null; 3035 PackageSetting ps = mSettings.mPackages.get(packageName); 3036 if (ps != null) { 3037 PackageParser.Package pkg = ps.pkg; 3038 if (pkg == null) { 3039 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3040 return null; 3041 } 3042 // Only data remains, so we aren't worried about code paths 3043 pkg = new PackageParser.Package(packageName); 3044 pkg.applicationInfo.packageName = packageName; 3045 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3046 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3047 pkg.applicationInfo.uid = ps.appId; 3048 pkg.applicationInfo.initForUser(userId); 3049 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3050 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3051 } 3052 return generatePackageInfo(pkg, flags, userId); 3053 } 3054 return null; 3055 } 3056 3057 @Override 3058 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3059 if (!sUserManager.exists(userId)) return null; 3060 flags = updateFlagsForApplication(flags, userId, packageName); 3061 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3062 // writer 3063 synchronized (mPackages) { 3064 PackageParser.Package p = mPackages.get(packageName); 3065 if (DEBUG_PACKAGE_INFO) Log.v( 3066 TAG, "getApplicationInfo " + packageName 3067 + ": " + p); 3068 if (p != null) { 3069 PackageSetting ps = mSettings.mPackages.get(packageName); 3070 if (ps == null) return null; 3071 // Note: isEnabledLP() does not apply here - always return info 3072 return PackageParser.generateApplicationInfo( 3073 p, flags, ps.readUserState(userId), userId); 3074 } 3075 if ("android".equals(packageName)||"system".equals(packageName)) { 3076 return mAndroidApplication; 3077 } 3078 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3079 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3080 } 3081 } 3082 return null; 3083 } 3084 3085 @Override 3086 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3087 final IPackageDataObserver observer) { 3088 mContext.enforceCallingOrSelfPermission( 3089 android.Manifest.permission.CLEAR_APP_CACHE, null); 3090 // Queue up an async operation since clearing cache may take a little while. 3091 mHandler.post(new Runnable() { 3092 public void run() { 3093 mHandler.removeCallbacks(this); 3094 boolean success = true; 3095 synchronized (mInstallLock) { 3096 try { 3097 mInstaller.freeCache(volumeUuid, freeStorageSize); 3098 } catch (InstallerException e) { 3099 Slog.w(TAG, "Couldn't clear application caches: " + e); 3100 success = false; 3101 } 3102 } 3103 if (observer != null) { 3104 try { 3105 observer.onRemoveCompleted(null, success); 3106 } catch (RemoteException e) { 3107 Slog.w(TAG, "RemoveException when invoking call back"); 3108 } 3109 } 3110 } 3111 }); 3112 } 3113 3114 @Override 3115 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3116 final IntentSender pi) { 3117 mContext.enforceCallingOrSelfPermission( 3118 android.Manifest.permission.CLEAR_APP_CACHE, null); 3119 // Queue up an async operation since clearing cache may take a little while. 3120 mHandler.post(new Runnable() { 3121 public void run() { 3122 mHandler.removeCallbacks(this); 3123 boolean success = true; 3124 synchronized (mInstallLock) { 3125 try { 3126 mInstaller.freeCache(volumeUuid, freeStorageSize); 3127 } catch (InstallerException e) { 3128 Slog.w(TAG, "Couldn't clear application caches: " + e); 3129 success = false; 3130 } 3131 } 3132 if(pi != null) { 3133 try { 3134 // Callback via pending intent 3135 int code = success ? 1 : 0; 3136 pi.sendIntent(null, code, null, 3137 null, null); 3138 } catch (SendIntentException e1) { 3139 Slog.i(TAG, "Failed to send pending intent"); 3140 } 3141 } 3142 } 3143 }); 3144 } 3145 3146 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3147 synchronized (mInstallLock) { 3148 try { 3149 mInstaller.freeCache(volumeUuid, freeStorageSize); 3150 } catch (InstallerException e) { 3151 throw new IOException("Failed to free enough space", e); 3152 } 3153 } 3154 } 3155 3156 /** 3157 * Return if the user key is currently unlocked. 3158 */ 3159 private boolean isUserKeyUnlocked(int userId) { 3160 if (StorageManager.isFileBasedEncryptionEnabled()) { 3161 final IMountService mount = IMountService.Stub 3162 .asInterface(ServiceManager.getService("mount")); 3163 if (mount == null) { 3164 Slog.w(TAG, "Early during boot, assuming locked"); 3165 return false; 3166 } 3167 final long token = Binder.clearCallingIdentity(); 3168 try { 3169 return mount.isUserKeyUnlocked(userId); 3170 } catch (RemoteException e) { 3171 throw e.rethrowAsRuntimeException(); 3172 } finally { 3173 Binder.restoreCallingIdentity(token); 3174 } 3175 } else { 3176 return true; 3177 } 3178 } 3179 3180 /** 3181 * Update given flags based on encryption status of current user. 3182 */ 3183 private int updateFlags(int flags, int userId) { 3184 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3185 | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) { 3186 // Caller expressed an explicit opinion about what encryption 3187 // aware/unaware components they want to see, so fall through and 3188 // give them what they want 3189 } else { 3190 // Caller expressed no opinion, so match based on user state 3191 if (isUserKeyUnlocked(userId)) { 3192 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 3193 } else { 3194 flags |= PackageManager.MATCH_ENCRYPTION_AWARE; 3195 } 3196 } 3197 3198 // Safe mode means we should ignore any third-party apps 3199 if (mSafeMode) { 3200 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3201 } 3202 3203 return flags; 3204 } 3205 3206 /** 3207 * Update given flags when being used to request {@link PackageInfo}. 3208 */ 3209 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3210 boolean triaged = true; 3211 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3212 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3213 // Caller is asking for component details, so they'd better be 3214 // asking for specific encryption matching behavior, or be triaged 3215 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3216 | PackageManager.MATCH_ENCRYPTION_AWARE 3217 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3218 triaged = false; 3219 } 3220 } 3221 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3222 | PackageManager.MATCH_SYSTEM_ONLY 3223 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3224 triaged = false; 3225 } 3226 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3227 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3228 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3229 } 3230 return updateFlags(flags, userId); 3231 } 3232 3233 /** 3234 * Update given flags when being used to request {@link ApplicationInfo}. 3235 */ 3236 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3237 return updateFlagsForPackage(flags, userId, cookie); 3238 } 3239 3240 /** 3241 * Update given flags when being used to request {@link ComponentInfo}. 3242 */ 3243 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3244 if (cookie instanceof Intent) { 3245 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3246 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3247 } 3248 } 3249 3250 boolean triaged = true; 3251 // Caller is asking for component details, so they'd better be 3252 // asking for specific encryption matching behavior, or be triaged 3253 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3254 | PackageManager.MATCH_ENCRYPTION_AWARE 3255 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3256 triaged = false; 3257 } 3258 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3259 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3260 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3261 } 3262 return updateFlags(flags, userId); 3263 } 3264 3265 /** 3266 * Update given flags when being used to request {@link ResolveInfo}. 3267 */ 3268 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3269 return updateFlagsForComponent(flags, userId, cookie); 3270 } 3271 3272 @Override 3273 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3274 if (!sUserManager.exists(userId)) return null; 3275 flags = updateFlagsForComponent(flags, userId, component); 3276 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3277 synchronized (mPackages) { 3278 PackageParser.Activity a = mActivities.mActivities.get(component); 3279 3280 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3281 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3282 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3283 if (ps == null) return null; 3284 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3285 userId); 3286 } 3287 if (mResolveComponentName.equals(component)) { 3288 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3289 new PackageUserState(), userId); 3290 } 3291 } 3292 return null; 3293 } 3294 3295 @Override 3296 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3297 String resolvedType) { 3298 synchronized (mPackages) { 3299 if (component.equals(mResolveComponentName)) { 3300 // The resolver supports EVERYTHING! 3301 return true; 3302 } 3303 PackageParser.Activity a = mActivities.mActivities.get(component); 3304 if (a == null) { 3305 return false; 3306 } 3307 for (int i=0; i<a.intents.size(); i++) { 3308 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3309 intent.getData(), intent.getCategories(), TAG) >= 0) { 3310 return true; 3311 } 3312 } 3313 return false; 3314 } 3315 } 3316 3317 @Override 3318 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3319 if (!sUserManager.exists(userId)) return null; 3320 flags = updateFlagsForComponent(flags, userId, component); 3321 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3322 synchronized (mPackages) { 3323 PackageParser.Activity a = mReceivers.mActivities.get(component); 3324 if (DEBUG_PACKAGE_INFO) Log.v( 3325 TAG, "getReceiverInfo " + component + ": " + a); 3326 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3327 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3328 if (ps == null) return null; 3329 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3330 userId); 3331 } 3332 } 3333 return null; 3334 } 3335 3336 @Override 3337 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3338 if (!sUserManager.exists(userId)) return null; 3339 flags = updateFlagsForComponent(flags, userId, component); 3340 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3341 synchronized (mPackages) { 3342 PackageParser.Service s = mServices.mServices.get(component); 3343 if (DEBUG_PACKAGE_INFO) Log.v( 3344 TAG, "getServiceInfo " + component + ": " + s); 3345 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3346 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3347 if (ps == null) return null; 3348 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3349 userId); 3350 } 3351 } 3352 return null; 3353 } 3354 3355 @Override 3356 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3357 if (!sUserManager.exists(userId)) return null; 3358 flags = updateFlagsForComponent(flags, userId, component); 3359 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3360 synchronized (mPackages) { 3361 PackageParser.Provider p = mProviders.mProviders.get(component); 3362 if (DEBUG_PACKAGE_INFO) Log.v( 3363 TAG, "getProviderInfo " + component + ": " + p); 3364 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3365 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3366 if (ps == null) return null; 3367 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3368 userId); 3369 } 3370 } 3371 return null; 3372 } 3373 3374 @Override 3375 public String[] getSystemSharedLibraryNames() { 3376 Set<String> libSet; 3377 synchronized (mPackages) { 3378 libSet = mSharedLibraries.keySet(); 3379 int size = libSet.size(); 3380 if (size > 0) { 3381 String[] libs = new String[size]; 3382 libSet.toArray(libs); 3383 return libs; 3384 } 3385 } 3386 return null; 3387 } 3388 3389 @Override 3390 public FeatureInfo[] getSystemAvailableFeatures() { 3391 Collection<FeatureInfo> featSet; 3392 synchronized (mPackages) { 3393 featSet = mAvailableFeatures.values(); 3394 int size = featSet.size(); 3395 if (size > 0) { 3396 FeatureInfo[] features = new FeatureInfo[size+1]; 3397 featSet.toArray(features); 3398 FeatureInfo fi = new FeatureInfo(); 3399 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3400 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3401 features[size] = fi; 3402 return features; 3403 } 3404 } 3405 return null; 3406 } 3407 3408 @Override 3409 public boolean hasSystemFeature(String name) { 3410 synchronized (mPackages) { 3411 return mAvailableFeatures.containsKey(name); 3412 } 3413 } 3414 3415 @Override 3416 public int checkPermission(String permName, String pkgName, int userId) { 3417 if (!sUserManager.exists(userId)) { 3418 return PackageManager.PERMISSION_DENIED; 3419 } 3420 3421 synchronized (mPackages) { 3422 final PackageParser.Package p = mPackages.get(pkgName); 3423 if (p != null && p.mExtras != null) { 3424 final PackageSetting ps = (PackageSetting) p.mExtras; 3425 final PermissionsState permissionsState = ps.getPermissionsState(); 3426 if (permissionsState.hasPermission(permName, userId)) { 3427 return PackageManager.PERMISSION_GRANTED; 3428 } 3429 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3430 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3431 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3432 return PackageManager.PERMISSION_GRANTED; 3433 } 3434 } 3435 } 3436 3437 return PackageManager.PERMISSION_DENIED; 3438 } 3439 3440 @Override 3441 public int checkUidPermission(String permName, int uid) { 3442 final int userId = UserHandle.getUserId(uid); 3443 3444 if (!sUserManager.exists(userId)) { 3445 return PackageManager.PERMISSION_DENIED; 3446 } 3447 3448 synchronized (mPackages) { 3449 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3450 if (obj != null) { 3451 final SettingBase ps = (SettingBase) obj; 3452 final PermissionsState permissionsState = ps.getPermissionsState(); 3453 if (permissionsState.hasPermission(permName, userId)) { 3454 return PackageManager.PERMISSION_GRANTED; 3455 } 3456 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3457 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3458 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3459 return PackageManager.PERMISSION_GRANTED; 3460 } 3461 } else { 3462 ArraySet<String> perms = mSystemPermissions.get(uid); 3463 if (perms != null) { 3464 if (perms.contains(permName)) { 3465 return PackageManager.PERMISSION_GRANTED; 3466 } 3467 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3468 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3469 return PackageManager.PERMISSION_GRANTED; 3470 } 3471 } 3472 } 3473 } 3474 3475 return PackageManager.PERMISSION_DENIED; 3476 } 3477 3478 @Override 3479 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3480 if (UserHandle.getCallingUserId() != userId) { 3481 mContext.enforceCallingPermission( 3482 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3483 "isPermissionRevokedByPolicy for user " + userId); 3484 } 3485 3486 if (checkPermission(permission, packageName, userId) 3487 == PackageManager.PERMISSION_GRANTED) { 3488 return false; 3489 } 3490 3491 final long identity = Binder.clearCallingIdentity(); 3492 try { 3493 final int flags = getPermissionFlags(permission, packageName, userId); 3494 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3495 } finally { 3496 Binder.restoreCallingIdentity(identity); 3497 } 3498 } 3499 3500 @Override 3501 public String getPermissionControllerPackageName() { 3502 synchronized (mPackages) { 3503 return mRequiredInstallerPackage; 3504 } 3505 } 3506 3507 /** 3508 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3509 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3510 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3511 * @param message the message to log on security exception 3512 */ 3513 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3514 boolean checkShell, String message) { 3515 if (userId < 0) { 3516 throw new IllegalArgumentException("Invalid userId " + userId); 3517 } 3518 if (checkShell) { 3519 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3520 } 3521 if (userId == UserHandle.getUserId(callingUid)) return; 3522 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3523 if (requireFullPermission) { 3524 mContext.enforceCallingOrSelfPermission( 3525 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3526 } else { 3527 try { 3528 mContext.enforceCallingOrSelfPermission( 3529 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3530 } catch (SecurityException se) { 3531 mContext.enforceCallingOrSelfPermission( 3532 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3533 } 3534 } 3535 } 3536 } 3537 3538 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3539 if (callingUid == Process.SHELL_UID) { 3540 if (userHandle >= 0 3541 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3542 throw new SecurityException("Shell does not have permission to access user " 3543 + userHandle); 3544 } else if (userHandle < 0) { 3545 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3546 + Debug.getCallers(3)); 3547 } 3548 } 3549 } 3550 3551 private BasePermission findPermissionTreeLP(String permName) { 3552 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3553 if (permName.startsWith(bp.name) && 3554 permName.length() > bp.name.length() && 3555 permName.charAt(bp.name.length()) == '.') { 3556 return bp; 3557 } 3558 } 3559 return null; 3560 } 3561 3562 private BasePermission checkPermissionTreeLP(String permName) { 3563 if (permName != null) { 3564 BasePermission bp = findPermissionTreeLP(permName); 3565 if (bp != null) { 3566 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3567 return bp; 3568 } 3569 throw new SecurityException("Calling uid " 3570 + Binder.getCallingUid() 3571 + " is not allowed to add to permission tree " 3572 + bp.name + " owned by uid " + bp.uid); 3573 } 3574 } 3575 throw new SecurityException("No permission tree found for " + permName); 3576 } 3577 3578 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3579 if (s1 == null) { 3580 return s2 == null; 3581 } 3582 if (s2 == null) { 3583 return false; 3584 } 3585 if (s1.getClass() != s2.getClass()) { 3586 return false; 3587 } 3588 return s1.equals(s2); 3589 } 3590 3591 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3592 if (pi1.icon != pi2.icon) return false; 3593 if (pi1.logo != pi2.logo) return false; 3594 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3595 if (!compareStrings(pi1.name, pi2.name)) return false; 3596 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3597 // We'll take care of setting this one. 3598 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3599 // These are not currently stored in settings. 3600 //if (!compareStrings(pi1.group, pi2.group)) return false; 3601 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3602 //if (pi1.labelRes != pi2.labelRes) return false; 3603 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3604 return true; 3605 } 3606 3607 int permissionInfoFootprint(PermissionInfo info) { 3608 int size = info.name.length(); 3609 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3610 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3611 return size; 3612 } 3613 3614 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3615 int size = 0; 3616 for (BasePermission perm : mSettings.mPermissions.values()) { 3617 if (perm.uid == tree.uid) { 3618 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3619 } 3620 } 3621 return size; 3622 } 3623 3624 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3625 // We calculate the max size of permissions defined by this uid and throw 3626 // if that plus the size of 'info' would exceed our stated maximum. 3627 if (tree.uid != Process.SYSTEM_UID) { 3628 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3629 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3630 throw new SecurityException("Permission tree size cap exceeded"); 3631 } 3632 } 3633 } 3634 3635 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3636 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3637 throw new SecurityException("Label must be specified in permission"); 3638 } 3639 BasePermission tree = checkPermissionTreeLP(info.name); 3640 BasePermission bp = mSettings.mPermissions.get(info.name); 3641 boolean added = bp == null; 3642 boolean changed = true; 3643 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3644 if (added) { 3645 enforcePermissionCapLocked(info, tree); 3646 bp = new BasePermission(info.name, tree.sourcePackage, 3647 BasePermission.TYPE_DYNAMIC); 3648 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3649 throw new SecurityException( 3650 "Not allowed to modify non-dynamic permission " 3651 + info.name); 3652 } else { 3653 if (bp.protectionLevel == fixedLevel 3654 && bp.perm.owner.equals(tree.perm.owner) 3655 && bp.uid == tree.uid 3656 && comparePermissionInfos(bp.perm.info, info)) { 3657 changed = false; 3658 } 3659 } 3660 bp.protectionLevel = fixedLevel; 3661 info = new PermissionInfo(info); 3662 info.protectionLevel = fixedLevel; 3663 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3664 bp.perm.info.packageName = tree.perm.info.packageName; 3665 bp.uid = tree.uid; 3666 if (added) { 3667 mSettings.mPermissions.put(info.name, bp); 3668 } 3669 if (changed) { 3670 if (!async) { 3671 mSettings.writeLPr(); 3672 } else { 3673 scheduleWriteSettingsLocked(); 3674 } 3675 } 3676 return added; 3677 } 3678 3679 @Override 3680 public boolean addPermission(PermissionInfo info) { 3681 synchronized (mPackages) { 3682 return addPermissionLocked(info, false); 3683 } 3684 } 3685 3686 @Override 3687 public boolean addPermissionAsync(PermissionInfo info) { 3688 synchronized (mPackages) { 3689 return addPermissionLocked(info, true); 3690 } 3691 } 3692 3693 @Override 3694 public void removePermission(String name) { 3695 synchronized (mPackages) { 3696 checkPermissionTreeLP(name); 3697 BasePermission bp = mSettings.mPermissions.get(name); 3698 if (bp != null) { 3699 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3700 throw new SecurityException( 3701 "Not allowed to modify non-dynamic permission " 3702 + name); 3703 } 3704 mSettings.mPermissions.remove(name); 3705 mSettings.writeLPr(); 3706 } 3707 } 3708 } 3709 3710 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3711 BasePermission bp) { 3712 int index = pkg.requestedPermissions.indexOf(bp.name); 3713 if (index == -1) { 3714 throw new SecurityException("Package " + pkg.packageName 3715 + " has not requested permission " + bp.name); 3716 } 3717 if (!bp.isRuntime() && !bp.isDevelopment()) { 3718 throw new SecurityException("Permission " + bp.name 3719 + " is not a changeable permission type"); 3720 } 3721 } 3722 3723 @Override 3724 public void grantRuntimePermission(String packageName, String name, final int userId) { 3725 if (!sUserManager.exists(userId)) { 3726 Log.e(TAG, "No such user:" + userId); 3727 return; 3728 } 3729 3730 mContext.enforceCallingOrSelfPermission( 3731 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3732 "grantRuntimePermission"); 3733 3734 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3735 "grantRuntimePermission"); 3736 3737 final int uid; 3738 final SettingBase sb; 3739 3740 synchronized (mPackages) { 3741 final PackageParser.Package pkg = mPackages.get(packageName); 3742 if (pkg == null) { 3743 throw new IllegalArgumentException("Unknown package: " + packageName); 3744 } 3745 3746 final BasePermission bp = mSettings.mPermissions.get(name); 3747 if (bp == null) { 3748 throw new IllegalArgumentException("Unknown permission: " + name); 3749 } 3750 3751 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3752 3753 // If a permission review is required for legacy apps we represent 3754 // their permissions as always granted runtime ones since we need 3755 // to keep the review required permission flag per user while an 3756 // install permission's state is shared across all users. 3757 if (Build.PERMISSIONS_REVIEW_REQUIRED 3758 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3759 && bp.isRuntime()) { 3760 return; 3761 } 3762 3763 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3764 sb = (SettingBase) pkg.mExtras; 3765 if (sb == null) { 3766 throw new IllegalArgumentException("Unknown package: " + packageName); 3767 } 3768 3769 final PermissionsState permissionsState = sb.getPermissionsState(); 3770 3771 final int flags = permissionsState.getPermissionFlags(name, userId); 3772 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3773 throw new SecurityException("Cannot grant system fixed permission " 3774 + name + " for package " + packageName); 3775 } 3776 3777 if (bp.isDevelopment()) { 3778 // Development permissions must be handled specially, since they are not 3779 // normal runtime permissions. For now they apply to all users. 3780 if (permissionsState.grantInstallPermission(bp) != 3781 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3782 scheduleWriteSettingsLocked(); 3783 } 3784 return; 3785 } 3786 3787 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3788 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3789 return; 3790 } 3791 3792 final int result = permissionsState.grantRuntimePermission(bp, userId); 3793 switch (result) { 3794 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3795 return; 3796 } 3797 3798 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3799 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3800 mHandler.post(new Runnable() { 3801 @Override 3802 public void run() { 3803 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3804 } 3805 }); 3806 } 3807 break; 3808 } 3809 3810 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3811 3812 // Not critical if that is lost - app has to request again. 3813 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3814 } 3815 3816 // Only need to do this if user is initialized. Otherwise it's a new user 3817 // and there are no processes running as the user yet and there's no need 3818 // to make an expensive call to remount processes for the changed permissions. 3819 if (READ_EXTERNAL_STORAGE.equals(name) 3820 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3821 final long token = Binder.clearCallingIdentity(); 3822 try { 3823 if (sUserManager.isInitialized(userId)) { 3824 MountServiceInternal mountServiceInternal = LocalServices.getService( 3825 MountServiceInternal.class); 3826 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3827 } 3828 } finally { 3829 Binder.restoreCallingIdentity(token); 3830 } 3831 } 3832 } 3833 3834 @Override 3835 public void revokeRuntimePermission(String packageName, String name, int userId) { 3836 if (!sUserManager.exists(userId)) { 3837 Log.e(TAG, "No such user:" + userId); 3838 return; 3839 } 3840 3841 mContext.enforceCallingOrSelfPermission( 3842 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3843 "revokeRuntimePermission"); 3844 3845 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3846 "revokeRuntimePermission"); 3847 3848 final int appId; 3849 3850 synchronized (mPackages) { 3851 final PackageParser.Package pkg = mPackages.get(packageName); 3852 if (pkg == null) { 3853 throw new IllegalArgumentException("Unknown package: " + packageName); 3854 } 3855 3856 final BasePermission bp = mSettings.mPermissions.get(name); 3857 if (bp == null) { 3858 throw new IllegalArgumentException("Unknown permission: " + name); 3859 } 3860 3861 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3862 3863 // If a permission review is required for legacy apps we represent 3864 // their permissions as always granted runtime ones since we need 3865 // to keep the review required permission flag per user while an 3866 // install permission's state is shared across all users. 3867 if (Build.PERMISSIONS_REVIEW_REQUIRED 3868 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3869 && bp.isRuntime()) { 3870 return; 3871 } 3872 3873 SettingBase sb = (SettingBase) pkg.mExtras; 3874 if (sb == null) { 3875 throw new IllegalArgumentException("Unknown package: " + packageName); 3876 } 3877 3878 final PermissionsState permissionsState = sb.getPermissionsState(); 3879 3880 final int flags = permissionsState.getPermissionFlags(name, userId); 3881 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3882 throw new SecurityException("Cannot revoke system fixed permission " 3883 + name + " for package " + packageName); 3884 } 3885 3886 if (bp.isDevelopment()) { 3887 // Development permissions must be handled specially, since they are not 3888 // normal runtime permissions. For now they apply to all users. 3889 if (permissionsState.revokeInstallPermission(bp) != 3890 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3891 scheduleWriteSettingsLocked(); 3892 } 3893 return; 3894 } 3895 3896 if (permissionsState.revokeRuntimePermission(bp, userId) == 3897 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3898 return; 3899 } 3900 3901 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3902 3903 // Critical, after this call app should never have the permission. 3904 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3905 3906 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3907 } 3908 3909 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3910 } 3911 3912 @Override 3913 public void resetRuntimePermissions() { 3914 mContext.enforceCallingOrSelfPermission( 3915 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3916 "revokeRuntimePermission"); 3917 3918 int callingUid = Binder.getCallingUid(); 3919 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3920 mContext.enforceCallingOrSelfPermission( 3921 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3922 "resetRuntimePermissions"); 3923 } 3924 3925 synchronized (mPackages) { 3926 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3927 for (int userId : UserManagerService.getInstance().getUserIds()) { 3928 final int packageCount = mPackages.size(); 3929 for (int i = 0; i < packageCount; i++) { 3930 PackageParser.Package pkg = mPackages.valueAt(i); 3931 if (!(pkg.mExtras instanceof PackageSetting)) { 3932 continue; 3933 } 3934 PackageSetting ps = (PackageSetting) pkg.mExtras; 3935 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3936 } 3937 } 3938 } 3939 } 3940 3941 @Override 3942 public int getPermissionFlags(String name, String packageName, int userId) { 3943 if (!sUserManager.exists(userId)) { 3944 return 0; 3945 } 3946 3947 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3948 3949 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3950 "getPermissionFlags"); 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 SettingBase sb = (SettingBase) pkg.mExtras; 3964 if (sb == null) { 3965 throw new IllegalArgumentException("Unknown package: " + packageName); 3966 } 3967 3968 PermissionsState permissionsState = sb.getPermissionsState(); 3969 return permissionsState.getPermissionFlags(name, userId); 3970 } 3971 } 3972 3973 @Override 3974 public void updatePermissionFlags(String name, String packageName, int flagMask, 3975 int flagValues, int userId) { 3976 if (!sUserManager.exists(userId)) { 3977 return; 3978 } 3979 3980 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3981 3982 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3983 "updatePermissionFlags"); 3984 3985 // Only the system can change these flags and nothing else. 3986 if (getCallingUid() != Process.SYSTEM_UID) { 3987 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3988 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3989 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3990 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3991 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 3992 } 3993 3994 synchronized (mPackages) { 3995 final PackageParser.Package pkg = mPackages.get(packageName); 3996 if (pkg == null) { 3997 throw new IllegalArgumentException("Unknown package: " + packageName); 3998 } 3999 4000 final BasePermission bp = mSettings.mPermissions.get(name); 4001 if (bp == null) { 4002 throw new IllegalArgumentException("Unknown permission: " + name); 4003 } 4004 4005 SettingBase sb = (SettingBase) pkg.mExtras; 4006 if (sb == null) { 4007 throw new IllegalArgumentException("Unknown package: " + packageName); 4008 } 4009 4010 PermissionsState permissionsState = sb.getPermissionsState(); 4011 4012 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4013 4014 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4015 // Install and runtime permissions are stored in different places, 4016 // so figure out what permission changed and persist the change. 4017 if (permissionsState.getInstallPermissionState(name) != null) { 4018 scheduleWriteSettingsLocked(); 4019 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4020 || hadState) { 4021 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4022 } 4023 } 4024 } 4025 } 4026 4027 /** 4028 * Update the permission flags for all packages and runtime permissions of a user in order 4029 * to allow device or profile owner to remove POLICY_FIXED. 4030 */ 4031 @Override 4032 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4033 if (!sUserManager.exists(userId)) { 4034 return; 4035 } 4036 4037 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4038 4039 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4040 "updatePermissionFlagsForAllApps"); 4041 4042 // Only the system can change system fixed flags. 4043 if (getCallingUid() != Process.SYSTEM_UID) { 4044 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4045 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4046 } 4047 4048 synchronized (mPackages) { 4049 boolean changed = false; 4050 final int packageCount = mPackages.size(); 4051 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4052 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4053 SettingBase sb = (SettingBase) pkg.mExtras; 4054 if (sb == null) { 4055 continue; 4056 } 4057 PermissionsState permissionsState = sb.getPermissionsState(); 4058 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4059 userId, flagMask, flagValues); 4060 } 4061 if (changed) { 4062 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4063 } 4064 } 4065 } 4066 4067 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4068 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4069 != PackageManager.PERMISSION_GRANTED 4070 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4071 != PackageManager.PERMISSION_GRANTED) { 4072 throw new SecurityException(message + " requires " 4073 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4074 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4075 } 4076 } 4077 4078 @Override 4079 public boolean shouldShowRequestPermissionRationale(String permissionName, 4080 String packageName, int userId) { 4081 if (UserHandle.getCallingUserId() != userId) { 4082 mContext.enforceCallingPermission( 4083 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4084 "canShowRequestPermissionRationale for user " + userId); 4085 } 4086 4087 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4088 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4089 return false; 4090 } 4091 4092 if (checkPermission(permissionName, packageName, userId) 4093 == PackageManager.PERMISSION_GRANTED) { 4094 return false; 4095 } 4096 4097 final int flags; 4098 4099 final long identity = Binder.clearCallingIdentity(); 4100 try { 4101 flags = getPermissionFlags(permissionName, 4102 packageName, userId); 4103 } finally { 4104 Binder.restoreCallingIdentity(identity); 4105 } 4106 4107 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4108 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4109 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4110 4111 if ((flags & fixedFlags) != 0) { 4112 return false; 4113 } 4114 4115 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4116 } 4117 4118 @Override 4119 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4120 mContext.enforceCallingOrSelfPermission( 4121 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4122 "addOnPermissionsChangeListener"); 4123 4124 synchronized (mPackages) { 4125 mOnPermissionChangeListeners.addListenerLocked(listener); 4126 } 4127 } 4128 4129 @Override 4130 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4131 synchronized (mPackages) { 4132 mOnPermissionChangeListeners.removeListenerLocked(listener); 4133 } 4134 } 4135 4136 @Override 4137 public boolean isProtectedBroadcast(String actionName) { 4138 synchronized (mPackages) { 4139 if (mProtectedBroadcasts.contains(actionName)) { 4140 return true; 4141 } else if (actionName != null) { 4142 // TODO: remove these terrible hacks 4143 if (actionName.startsWith("android.net.netmon.lingerExpired") 4144 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) { 4145 return true; 4146 } 4147 } 4148 } 4149 return false; 4150 } 4151 4152 @Override 4153 public int checkSignatures(String pkg1, String pkg2) { 4154 synchronized (mPackages) { 4155 final PackageParser.Package p1 = mPackages.get(pkg1); 4156 final PackageParser.Package p2 = mPackages.get(pkg2); 4157 if (p1 == null || p1.mExtras == null 4158 || p2 == null || p2.mExtras == null) { 4159 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4160 } 4161 return compareSignatures(p1.mSignatures, p2.mSignatures); 4162 } 4163 } 4164 4165 @Override 4166 public int checkUidSignatures(int uid1, int uid2) { 4167 // Map to base uids. 4168 uid1 = UserHandle.getAppId(uid1); 4169 uid2 = UserHandle.getAppId(uid2); 4170 // reader 4171 synchronized (mPackages) { 4172 Signature[] s1; 4173 Signature[] s2; 4174 Object obj = mSettings.getUserIdLPr(uid1); 4175 if (obj != null) { 4176 if (obj instanceof SharedUserSetting) { 4177 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4178 } else if (obj instanceof PackageSetting) { 4179 s1 = ((PackageSetting)obj).signatures.mSignatures; 4180 } else { 4181 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4182 } 4183 } else { 4184 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4185 } 4186 obj = mSettings.getUserIdLPr(uid2); 4187 if (obj != null) { 4188 if (obj instanceof SharedUserSetting) { 4189 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4190 } else if (obj instanceof PackageSetting) { 4191 s2 = ((PackageSetting)obj).signatures.mSignatures; 4192 } else { 4193 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4194 } 4195 } else { 4196 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4197 } 4198 return compareSignatures(s1, s2); 4199 } 4200 } 4201 4202 private void killUid(int appId, int userId, String reason) { 4203 final long identity = Binder.clearCallingIdentity(); 4204 try { 4205 IActivityManager am = ActivityManagerNative.getDefault(); 4206 if (am != null) { 4207 try { 4208 am.killUid(appId, userId, reason); 4209 } catch (RemoteException e) { 4210 /* ignore - same process */ 4211 } 4212 } 4213 } finally { 4214 Binder.restoreCallingIdentity(identity); 4215 } 4216 } 4217 4218 /** 4219 * Compares two sets of signatures. Returns: 4220 * <br /> 4221 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4222 * <br /> 4223 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4224 * <br /> 4225 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4226 * <br /> 4227 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4228 * <br /> 4229 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4230 */ 4231 static int compareSignatures(Signature[] s1, Signature[] s2) { 4232 if (s1 == null) { 4233 return s2 == null 4234 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4235 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4236 } 4237 4238 if (s2 == null) { 4239 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4240 } 4241 4242 if (s1.length != s2.length) { 4243 return PackageManager.SIGNATURE_NO_MATCH; 4244 } 4245 4246 // Since both signature sets are of size 1, we can compare without HashSets. 4247 if (s1.length == 1) { 4248 return s1[0].equals(s2[0]) ? 4249 PackageManager.SIGNATURE_MATCH : 4250 PackageManager.SIGNATURE_NO_MATCH; 4251 } 4252 4253 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4254 for (Signature sig : s1) { 4255 set1.add(sig); 4256 } 4257 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4258 for (Signature sig : s2) { 4259 set2.add(sig); 4260 } 4261 // Make sure s2 contains all signatures in s1. 4262 if (set1.equals(set2)) { 4263 return PackageManager.SIGNATURE_MATCH; 4264 } 4265 return PackageManager.SIGNATURE_NO_MATCH; 4266 } 4267 4268 /** 4269 * If the database version for this type of package (internal storage or 4270 * external storage) is less than the version where package signatures 4271 * were updated, return true. 4272 */ 4273 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4274 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4275 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4276 } 4277 4278 /** 4279 * Used for backward compatibility to make sure any packages with 4280 * certificate chains get upgraded to the new style. {@code existingSigs} 4281 * will be in the old format (since they were stored on disk from before the 4282 * system upgrade) and {@code scannedSigs} will be in the newer format. 4283 */ 4284 private int compareSignaturesCompat(PackageSignatures existingSigs, 4285 PackageParser.Package scannedPkg) { 4286 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4287 return PackageManager.SIGNATURE_NO_MATCH; 4288 } 4289 4290 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4291 for (Signature sig : existingSigs.mSignatures) { 4292 existingSet.add(sig); 4293 } 4294 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4295 for (Signature sig : scannedPkg.mSignatures) { 4296 try { 4297 Signature[] chainSignatures = sig.getChainSignatures(); 4298 for (Signature chainSig : chainSignatures) { 4299 scannedCompatSet.add(chainSig); 4300 } 4301 } catch (CertificateEncodingException e) { 4302 scannedCompatSet.add(sig); 4303 } 4304 } 4305 /* 4306 * Make sure the expanded scanned set contains all signatures in the 4307 * existing one. 4308 */ 4309 if (scannedCompatSet.equals(existingSet)) { 4310 // Migrate the old signatures to the new scheme. 4311 existingSigs.assignSignatures(scannedPkg.mSignatures); 4312 // The new KeySets will be re-added later in the scanning process. 4313 synchronized (mPackages) { 4314 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4315 } 4316 return PackageManager.SIGNATURE_MATCH; 4317 } 4318 return PackageManager.SIGNATURE_NO_MATCH; 4319 } 4320 4321 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4322 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4323 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4324 } 4325 4326 private int compareSignaturesRecover(PackageSignatures existingSigs, 4327 PackageParser.Package scannedPkg) { 4328 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4329 return PackageManager.SIGNATURE_NO_MATCH; 4330 } 4331 4332 String msg = null; 4333 try { 4334 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4335 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4336 + scannedPkg.packageName); 4337 return PackageManager.SIGNATURE_MATCH; 4338 } 4339 } catch (CertificateException e) { 4340 msg = e.getMessage(); 4341 } 4342 4343 logCriticalInfo(Log.INFO, 4344 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4345 return PackageManager.SIGNATURE_NO_MATCH; 4346 } 4347 4348 @Override 4349 public String[] getPackagesForUid(int uid) { 4350 uid = UserHandle.getAppId(uid); 4351 // reader 4352 synchronized (mPackages) { 4353 Object obj = mSettings.getUserIdLPr(uid); 4354 if (obj instanceof SharedUserSetting) { 4355 final SharedUserSetting sus = (SharedUserSetting) obj; 4356 final int N = sus.packages.size(); 4357 final String[] res = new String[N]; 4358 final Iterator<PackageSetting> it = sus.packages.iterator(); 4359 int i = 0; 4360 while (it.hasNext()) { 4361 res[i++] = it.next().name; 4362 } 4363 return res; 4364 } else if (obj instanceof PackageSetting) { 4365 final PackageSetting ps = (PackageSetting) obj; 4366 return new String[] { ps.name }; 4367 } 4368 } 4369 return null; 4370 } 4371 4372 @Override 4373 public String getNameForUid(int uid) { 4374 // reader 4375 synchronized (mPackages) { 4376 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4377 if (obj instanceof SharedUserSetting) { 4378 final SharedUserSetting sus = (SharedUserSetting) obj; 4379 return sus.name + ":" + sus.userId; 4380 } else if (obj instanceof PackageSetting) { 4381 final PackageSetting ps = (PackageSetting) obj; 4382 return ps.name; 4383 } 4384 } 4385 return null; 4386 } 4387 4388 @Override 4389 public int getUidForSharedUser(String sharedUserName) { 4390 if(sharedUserName == null) { 4391 return -1; 4392 } 4393 // reader 4394 synchronized (mPackages) { 4395 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4396 if (suid == null) { 4397 return -1; 4398 } 4399 return suid.userId; 4400 } 4401 } 4402 4403 @Override 4404 public int getFlagsForUid(int uid) { 4405 synchronized (mPackages) { 4406 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4407 if (obj instanceof SharedUserSetting) { 4408 final SharedUserSetting sus = (SharedUserSetting) obj; 4409 return sus.pkgFlags; 4410 } else if (obj instanceof PackageSetting) { 4411 final PackageSetting ps = (PackageSetting) obj; 4412 return ps.pkgFlags; 4413 } 4414 } 4415 return 0; 4416 } 4417 4418 @Override 4419 public int getPrivateFlagsForUid(int uid) { 4420 synchronized (mPackages) { 4421 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4422 if (obj instanceof SharedUserSetting) { 4423 final SharedUserSetting sus = (SharedUserSetting) obj; 4424 return sus.pkgPrivateFlags; 4425 } else if (obj instanceof PackageSetting) { 4426 final PackageSetting ps = (PackageSetting) obj; 4427 return ps.pkgPrivateFlags; 4428 } 4429 } 4430 return 0; 4431 } 4432 4433 @Override 4434 public boolean isUidPrivileged(int uid) { 4435 uid = UserHandle.getAppId(uid); 4436 // reader 4437 synchronized (mPackages) { 4438 Object obj = mSettings.getUserIdLPr(uid); 4439 if (obj instanceof SharedUserSetting) { 4440 final SharedUserSetting sus = (SharedUserSetting) obj; 4441 final Iterator<PackageSetting> it = sus.packages.iterator(); 4442 while (it.hasNext()) { 4443 if (it.next().isPrivileged()) { 4444 return true; 4445 } 4446 } 4447 } else if (obj instanceof PackageSetting) { 4448 final PackageSetting ps = (PackageSetting) obj; 4449 return ps.isPrivileged(); 4450 } 4451 } 4452 return false; 4453 } 4454 4455 @Override 4456 public String[] getAppOpPermissionPackages(String permissionName) { 4457 synchronized (mPackages) { 4458 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4459 if (pkgs == null) { 4460 return null; 4461 } 4462 return pkgs.toArray(new String[pkgs.size()]); 4463 } 4464 } 4465 4466 @Override 4467 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4468 int flags, int userId) { 4469 if (!sUserManager.exists(userId)) return null; 4470 flags = updateFlagsForResolve(flags, userId, intent); 4471 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4472 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4473 final ResolveInfo bestChoice = 4474 chooseBestActivity(intent, resolvedType, flags, query, userId); 4475 4476 if (isEphemeralAllowed(intent, query, userId)) { 4477 final EphemeralResolveInfo ai = 4478 getEphemeralResolveInfo(intent, resolvedType, userId); 4479 if (ai != null) { 4480 if (DEBUG_EPHEMERAL) { 4481 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4482 } 4483 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4484 bestChoice.ephemeralResolveInfo = ai; 4485 } 4486 } 4487 return bestChoice; 4488 } 4489 4490 @Override 4491 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4492 IntentFilter filter, int match, ComponentName activity) { 4493 final int userId = UserHandle.getCallingUserId(); 4494 if (DEBUG_PREFERRED) { 4495 Log.v(TAG, "setLastChosenActivity intent=" + intent 4496 + " resolvedType=" + resolvedType 4497 + " flags=" + flags 4498 + " filter=" + filter 4499 + " match=" + match 4500 + " activity=" + activity); 4501 filter.dump(new PrintStreamPrinter(System.out), " "); 4502 } 4503 intent.setComponent(null); 4504 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4505 // Find any earlier preferred or last chosen entries and nuke them 4506 findPreferredActivity(intent, resolvedType, 4507 flags, query, 0, false, true, false, userId); 4508 // Add the new activity as the last chosen for this filter 4509 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4510 "Setting last chosen"); 4511 } 4512 4513 @Override 4514 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4515 final int userId = UserHandle.getCallingUserId(); 4516 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4517 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4518 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4519 false, false, false, userId); 4520 } 4521 4522 4523 private boolean isEphemeralAllowed( 4524 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4525 // Short circuit and return early if possible. 4526 if (DISABLE_EPHEMERAL_APPS) { 4527 return false; 4528 } 4529 final int callingUser = UserHandle.getCallingUserId(); 4530 if (callingUser != UserHandle.USER_SYSTEM) { 4531 return false; 4532 } 4533 if (mEphemeralResolverConnection == null) { 4534 return false; 4535 } 4536 if (intent.getComponent() != null) { 4537 return false; 4538 } 4539 if (intent.getPackage() != null) { 4540 return false; 4541 } 4542 final boolean isWebUri = hasWebURI(intent); 4543 if (!isWebUri) { 4544 return false; 4545 } 4546 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4547 synchronized (mPackages) { 4548 final int count = resolvedActivites.size(); 4549 for (int n = 0; n < count; n++) { 4550 ResolveInfo info = resolvedActivites.get(n); 4551 String packageName = info.activityInfo.packageName; 4552 PackageSetting ps = mSettings.mPackages.get(packageName); 4553 if (ps != null) { 4554 // Try to get the status from User settings first 4555 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4556 int status = (int) (packedStatus >> 32); 4557 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4558 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4559 if (DEBUG_EPHEMERAL) { 4560 Slog.v(TAG, "DENY ephemeral apps;" 4561 + " pkg: " + packageName + ", status: " + status); 4562 } 4563 return false; 4564 } 4565 } 4566 } 4567 } 4568 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4569 return true; 4570 } 4571 4572 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4573 int userId) { 4574 MessageDigest digest = null; 4575 try { 4576 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4577 } catch (NoSuchAlgorithmException e) { 4578 // If we can't create a digest, ignore ephemeral apps. 4579 return null; 4580 } 4581 4582 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4583 final byte[] digestBytes = digest.digest(hostBytes); 4584 int shaPrefix = 4585 digestBytes[0] << 24 4586 | digestBytes[1] << 16 4587 | digestBytes[2] << 8 4588 | digestBytes[3] << 0; 4589 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4590 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4591 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4592 // No hash prefix match; there are no ephemeral apps for this domain. 4593 return null; 4594 } 4595 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4596 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4597 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4598 continue; 4599 } 4600 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4601 // No filters; this should never happen. 4602 if (filters.isEmpty()) { 4603 continue; 4604 } 4605 // We have a domain match; resolve the filters to see if anything matches. 4606 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4607 for (int j = filters.size() - 1; j >= 0; --j) { 4608 final EphemeralResolveIntentInfo intentInfo = 4609 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4610 ephemeralResolver.addFilter(intentInfo); 4611 } 4612 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4613 intent, resolvedType, false /*defaultOnly*/, userId); 4614 if (!matchedResolveInfoList.isEmpty()) { 4615 return matchedResolveInfoList.get(0); 4616 } 4617 } 4618 // Hash or filter mis-match; no ephemeral apps for this domain. 4619 return null; 4620 } 4621 4622 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4623 int flags, List<ResolveInfo> query, int userId) { 4624 if (query != null) { 4625 final int N = query.size(); 4626 if (N == 1) { 4627 return query.get(0); 4628 } else if (N > 1) { 4629 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4630 // If there is more than one activity with the same priority, 4631 // then let the user decide between them. 4632 ResolveInfo r0 = query.get(0); 4633 ResolveInfo r1 = query.get(1); 4634 if (DEBUG_INTENT_MATCHING || debug) { 4635 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4636 + r1.activityInfo.name + "=" + r1.priority); 4637 } 4638 // If the first activity has a higher priority, or a different 4639 // default, then it is always desirable to pick it. 4640 if (r0.priority != r1.priority 4641 || r0.preferredOrder != r1.preferredOrder 4642 || r0.isDefault != r1.isDefault) { 4643 return query.get(0); 4644 } 4645 // If we have saved a preference for a preferred activity for 4646 // this Intent, use that. 4647 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4648 flags, query, r0.priority, true, false, debug, userId); 4649 if (ri != null) { 4650 return ri; 4651 } 4652 ri = new ResolveInfo(mResolveInfo); 4653 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4654 ri.activityInfo.applicationInfo = new ApplicationInfo( 4655 ri.activityInfo.applicationInfo); 4656 if (userId != 0) { 4657 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4658 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4659 } 4660 // Make sure that the resolver is displayable in car mode 4661 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4662 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4663 return ri; 4664 } 4665 } 4666 return null; 4667 } 4668 4669 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4670 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4671 final int N = query.size(); 4672 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4673 .get(userId); 4674 // Get the list of persistent preferred activities that handle the intent 4675 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4676 List<PersistentPreferredActivity> pprefs = ppir != null 4677 ? ppir.queryIntent(intent, resolvedType, 4678 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4679 : null; 4680 if (pprefs != null && pprefs.size() > 0) { 4681 final int M = pprefs.size(); 4682 for (int i=0; i<M; i++) { 4683 final PersistentPreferredActivity ppa = pprefs.get(i); 4684 if (DEBUG_PREFERRED || debug) { 4685 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4686 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4687 + "\n component=" + ppa.mComponent); 4688 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4689 } 4690 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4691 flags | MATCH_DISABLED_COMPONENTS, userId); 4692 if (DEBUG_PREFERRED || debug) { 4693 Slog.v(TAG, "Found persistent preferred activity:"); 4694 if (ai != null) { 4695 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4696 } else { 4697 Slog.v(TAG, " null"); 4698 } 4699 } 4700 if (ai == null) { 4701 // This previously registered persistent preferred activity 4702 // component is no longer known. Ignore it and do NOT remove it. 4703 continue; 4704 } 4705 for (int j=0; j<N; j++) { 4706 final ResolveInfo ri = query.get(j); 4707 if (!ri.activityInfo.applicationInfo.packageName 4708 .equals(ai.applicationInfo.packageName)) { 4709 continue; 4710 } 4711 if (!ri.activityInfo.name.equals(ai.name)) { 4712 continue; 4713 } 4714 // Found a persistent preference that can handle the intent. 4715 if (DEBUG_PREFERRED || debug) { 4716 Slog.v(TAG, "Returning persistent preferred activity: " + 4717 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4718 } 4719 return ri; 4720 } 4721 } 4722 } 4723 return null; 4724 } 4725 4726 // TODO: handle preferred activities missing while user has amnesia 4727 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4728 List<ResolveInfo> query, int priority, boolean always, 4729 boolean removeMatches, boolean debug, int userId) { 4730 if (!sUserManager.exists(userId)) return null; 4731 flags = updateFlagsForResolve(flags, userId, intent); 4732 // writer 4733 synchronized (mPackages) { 4734 if (intent.getSelector() != null) { 4735 intent = intent.getSelector(); 4736 } 4737 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4738 4739 // Try to find a matching persistent preferred activity. 4740 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4741 debug, userId); 4742 4743 // If a persistent preferred activity matched, use it. 4744 if (pri != null) { 4745 return pri; 4746 } 4747 4748 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4749 // Get the list of preferred activities that handle the intent 4750 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4751 List<PreferredActivity> prefs = pir != null 4752 ? pir.queryIntent(intent, resolvedType, 4753 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4754 : null; 4755 if (prefs != null && prefs.size() > 0) { 4756 boolean changed = false; 4757 try { 4758 // First figure out how good the original match set is. 4759 // We will only allow preferred activities that came 4760 // from the same match quality. 4761 int match = 0; 4762 4763 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4764 4765 final int N = query.size(); 4766 for (int j=0; j<N; j++) { 4767 final ResolveInfo ri = query.get(j); 4768 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4769 + ": 0x" + Integer.toHexString(match)); 4770 if (ri.match > match) { 4771 match = ri.match; 4772 } 4773 } 4774 4775 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4776 + Integer.toHexString(match)); 4777 4778 match &= IntentFilter.MATCH_CATEGORY_MASK; 4779 final int M = prefs.size(); 4780 for (int i=0; i<M; i++) { 4781 final PreferredActivity pa = prefs.get(i); 4782 if (DEBUG_PREFERRED || debug) { 4783 Slog.v(TAG, "Checking PreferredActivity ds=" 4784 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4785 + "\n component=" + pa.mPref.mComponent); 4786 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4787 } 4788 if (pa.mPref.mMatch != match) { 4789 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4790 + Integer.toHexString(pa.mPref.mMatch)); 4791 continue; 4792 } 4793 // If it's not an "always" type preferred activity and that's what we're 4794 // looking for, skip it. 4795 if (always && !pa.mPref.mAlways) { 4796 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4797 continue; 4798 } 4799 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4800 flags | MATCH_DISABLED_COMPONENTS, userId); 4801 if (DEBUG_PREFERRED || debug) { 4802 Slog.v(TAG, "Found preferred activity:"); 4803 if (ai != null) { 4804 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4805 } else { 4806 Slog.v(TAG, " null"); 4807 } 4808 } 4809 if (ai == null) { 4810 // This previously registered preferred activity 4811 // component is no longer known. Most likely an update 4812 // to the app was installed and in the new version this 4813 // component no longer exists. Clean it up by removing 4814 // it from the preferred activities list, and skip it. 4815 Slog.w(TAG, "Removing dangling preferred activity: " 4816 + pa.mPref.mComponent); 4817 pir.removeFilter(pa); 4818 changed = true; 4819 continue; 4820 } 4821 for (int j=0; j<N; j++) { 4822 final ResolveInfo ri = query.get(j); 4823 if (!ri.activityInfo.applicationInfo.packageName 4824 .equals(ai.applicationInfo.packageName)) { 4825 continue; 4826 } 4827 if (!ri.activityInfo.name.equals(ai.name)) { 4828 continue; 4829 } 4830 4831 if (removeMatches) { 4832 pir.removeFilter(pa); 4833 changed = true; 4834 if (DEBUG_PREFERRED) { 4835 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4836 } 4837 break; 4838 } 4839 4840 // Okay we found a previously set preferred or last chosen app. 4841 // If the result set is different from when this 4842 // was created, we need to clear it and re-ask the 4843 // user their preference, if we're looking for an "always" type entry. 4844 if (always && !pa.mPref.sameSet(query)) { 4845 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4846 + intent + " type " + resolvedType); 4847 if (DEBUG_PREFERRED) { 4848 Slog.v(TAG, "Removing preferred activity since set changed " 4849 + pa.mPref.mComponent); 4850 } 4851 pir.removeFilter(pa); 4852 // Re-add the filter as a "last chosen" entry (!always) 4853 PreferredActivity lastChosen = new PreferredActivity( 4854 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4855 pir.addFilter(lastChosen); 4856 changed = true; 4857 return null; 4858 } 4859 4860 // Yay! Either the set matched or we're looking for the last chosen 4861 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4862 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4863 return ri; 4864 } 4865 } 4866 } finally { 4867 if (changed) { 4868 if (DEBUG_PREFERRED) { 4869 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4870 } 4871 scheduleWritePackageRestrictionsLocked(userId); 4872 } 4873 } 4874 } 4875 } 4876 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4877 return null; 4878 } 4879 4880 /* 4881 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4882 */ 4883 @Override 4884 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4885 int targetUserId) { 4886 mContext.enforceCallingOrSelfPermission( 4887 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4888 List<CrossProfileIntentFilter> matches = 4889 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4890 if (matches != null) { 4891 int size = matches.size(); 4892 for (int i = 0; i < size; i++) { 4893 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4894 } 4895 } 4896 if (hasWebURI(intent)) { 4897 // cross-profile app linking works only towards the parent. 4898 final UserInfo parent = getProfileParent(sourceUserId); 4899 synchronized(mPackages) { 4900 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4901 intent, resolvedType, 0, sourceUserId, parent.id); 4902 return xpDomainInfo != null; 4903 } 4904 } 4905 return false; 4906 } 4907 4908 private UserInfo getProfileParent(int userId) { 4909 final long identity = Binder.clearCallingIdentity(); 4910 try { 4911 return sUserManager.getProfileParent(userId); 4912 } finally { 4913 Binder.restoreCallingIdentity(identity); 4914 } 4915 } 4916 4917 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4918 String resolvedType, int userId) { 4919 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4920 if (resolver != null) { 4921 return resolver.queryIntent(intent, resolvedType, false, userId); 4922 } 4923 return null; 4924 } 4925 4926 @Override 4927 public List<ResolveInfo> queryIntentActivities(Intent intent, 4928 String resolvedType, int flags, int userId) { 4929 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4930 flags = updateFlagsForResolve(flags, userId, intent); 4931 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4932 ComponentName comp = intent.getComponent(); 4933 if (comp == null) { 4934 if (intent.getSelector() != null) { 4935 intent = intent.getSelector(); 4936 comp = intent.getComponent(); 4937 } 4938 } 4939 4940 if (comp != null) { 4941 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4942 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4943 if (ai != null) { 4944 final ResolveInfo ri = new ResolveInfo(); 4945 ri.activityInfo = ai; 4946 list.add(ri); 4947 } 4948 return list; 4949 } 4950 4951 // reader 4952 synchronized (mPackages) { 4953 final String pkgName = intent.getPackage(); 4954 if (pkgName == null) { 4955 List<CrossProfileIntentFilter> matchingFilters = 4956 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4957 // Check for results that need to skip the current profile. 4958 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4959 resolvedType, flags, userId); 4960 if (xpResolveInfo != null) { 4961 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4962 result.add(xpResolveInfo); 4963 return filterIfNotSystemUser(result, userId); 4964 } 4965 4966 // Check for results in the current profile. 4967 List<ResolveInfo> result = mActivities.queryIntent( 4968 intent, resolvedType, flags, userId); 4969 result = filterIfNotSystemUser(result, userId); 4970 4971 // Check for cross profile results. 4972 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 4973 xpResolveInfo = queryCrossProfileIntents( 4974 matchingFilters, intent, resolvedType, flags, userId, 4975 hasNonNegativePriorityResult); 4976 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4977 boolean isVisibleToUser = filterIfNotSystemUser( 4978 Collections.singletonList(xpResolveInfo), userId).size() > 0; 4979 if (isVisibleToUser) { 4980 result.add(xpResolveInfo); 4981 Collections.sort(result, mResolvePrioritySorter); 4982 } 4983 } 4984 if (hasWebURI(intent)) { 4985 CrossProfileDomainInfo xpDomainInfo = null; 4986 final UserInfo parent = getProfileParent(userId); 4987 if (parent != null) { 4988 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4989 flags, userId, parent.id); 4990 } 4991 if (xpDomainInfo != null) { 4992 if (xpResolveInfo != null) { 4993 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4994 // in the result. 4995 result.remove(xpResolveInfo); 4996 } 4997 if (result.size() == 0) { 4998 result.add(xpDomainInfo.resolveInfo); 4999 return result; 5000 } 5001 } else if (result.size() <= 1) { 5002 return result; 5003 } 5004 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5005 xpDomainInfo, userId); 5006 Collections.sort(result, mResolvePrioritySorter); 5007 } 5008 return result; 5009 } 5010 final PackageParser.Package pkg = mPackages.get(pkgName); 5011 if (pkg != null) { 5012 return filterIfNotSystemUser( 5013 mActivities.queryIntentForPackage( 5014 intent, resolvedType, flags, pkg.activities, userId), 5015 userId); 5016 } 5017 return new ArrayList<ResolveInfo>(); 5018 } 5019 } 5020 5021 private static class CrossProfileDomainInfo { 5022 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5023 ResolveInfo resolveInfo; 5024 /* Best domain verification status of the activities found in the other profile */ 5025 int bestDomainVerificationStatus; 5026 } 5027 5028 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5029 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5030 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5031 sourceUserId)) { 5032 return null; 5033 } 5034 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5035 resolvedType, flags, parentUserId); 5036 5037 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5038 return null; 5039 } 5040 CrossProfileDomainInfo result = null; 5041 int size = resultTargetUser.size(); 5042 for (int i = 0; i < size; i++) { 5043 ResolveInfo riTargetUser = resultTargetUser.get(i); 5044 // Intent filter verification is only for filters that specify a host. So don't return 5045 // those that handle all web uris. 5046 if (riTargetUser.handleAllWebDataURI) { 5047 continue; 5048 } 5049 String packageName = riTargetUser.activityInfo.packageName; 5050 PackageSetting ps = mSettings.mPackages.get(packageName); 5051 if (ps == null) { 5052 continue; 5053 } 5054 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5055 int status = (int)(verificationState >> 32); 5056 if (result == null) { 5057 result = new CrossProfileDomainInfo(); 5058 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5059 sourceUserId, parentUserId); 5060 result.bestDomainVerificationStatus = status; 5061 } else { 5062 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5063 result.bestDomainVerificationStatus); 5064 } 5065 } 5066 // Don't consider matches with status NEVER across profiles. 5067 if (result != null && result.bestDomainVerificationStatus 5068 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5069 return null; 5070 } 5071 return result; 5072 } 5073 5074 /** 5075 * Verification statuses are ordered from the worse to the best, except for 5076 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5077 */ 5078 private int bestDomainVerificationStatus(int status1, int status2) { 5079 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5080 return status2; 5081 } 5082 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5083 return status1; 5084 } 5085 return (int) MathUtils.max(status1, status2); 5086 } 5087 5088 private boolean isUserEnabled(int userId) { 5089 long callingId = Binder.clearCallingIdentity(); 5090 try { 5091 UserInfo userInfo = sUserManager.getUserInfo(userId); 5092 return userInfo != null && userInfo.isEnabled(); 5093 } finally { 5094 Binder.restoreCallingIdentity(callingId); 5095 } 5096 } 5097 5098 /** 5099 * Filter out activities with systemUserOnly flag set, when current user is not System. 5100 * 5101 * @return filtered list 5102 */ 5103 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5104 if (userId == UserHandle.USER_SYSTEM) { 5105 return resolveInfos; 5106 } 5107 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5108 ResolveInfo info = resolveInfos.get(i); 5109 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5110 resolveInfos.remove(i); 5111 } 5112 } 5113 return resolveInfos; 5114 } 5115 5116 /** 5117 * @param resolveInfos list of resolve infos in descending priority order 5118 * @return if the list contains a resolve info with non-negative priority 5119 */ 5120 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5121 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5122 } 5123 5124 private static boolean hasWebURI(Intent intent) { 5125 if (intent.getData() == null) { 5126 return false; 5127 } 5128 final String scheme = intent.getScheme(); 5129 if (TextUtils.isEmpty(scheme)) { 5130 return false; 5131 } 5132 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5133 } 5134 5135 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5136 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5137 int userId) { 5138 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5139 5140 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5141 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5142 candidates.size()); 5143 } 5144 5145 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5146 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5147 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5148 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5149 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5150 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5151 5152 synchronized (mPackages) { 5153 final int count = candidates.size(); 5154 // First, try to use linked apps. Partition the candidates into four lists: 5155 // one for the final results, one for the "do not use ever", one for "undefined status" 5156 // and finally one for "browser app type". 5157 for (int n=0; n<count; n++) { 5158 ResolveInfo info = candidates.get(n); 5159 String packageName = info.activityInfo.packageName; 5160 PackageSetting ps = mSettings.mPackages.get(packageName); 5161 if (ps != null) { 5162 // Add to the special match all list (Browser use case) 5163 if (info.handleAllWebDataURI) { 5164 matchAllList.add(info); 5165 continue; 5166 } 5167 // Try to get the status from User settings first 5168 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5169 int status = (int)(packedStatus >> 32); 5170 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5171 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5172 if (DEBUG_DOMAIN_VERIFICATION) { 5173 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5174 + " : linkgen=" + linkGeneration); 5175 } 5176 // Use link-enabled generation as preferredOrder, i.e. 5177 // prefer newly-enabled over earlier-enabled. 5178 info.preferredOrder = linkGeneration; 5179 alwaysList.add(info); 5180 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5181 if (DEBUG_DOMAIN_VERIFICATION) { 5182 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5183 } 5184 neverList.add(info); 5185 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5186 if (DEBUG_DOMAIN_VERIFICATION) { 5187 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5188 } 5189 alwaysAskList.add(info); 5190 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5191 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5192 if (DEBUG_DOMAIN_VERIFICATION) { 5193 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5194 } 5195 undefinedList.add(info); 5196 } 5197 } 5198 } 5199 5200 // We'll want to include browser possibilities in a few cases 5201 boolean includeBrowser = false; 5202 5203 // First try to add the "always" resolution(s) for the current user, if any 5204 if (alwaysList.size() > 0) { 5205 result.addAll(alwaysList); 5206 } else { 5207 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5208 result.addAll(undefinedList); 5209 // Maybe add one for the other profile. 5210 if (xpDomainInfo != null && ( 5211 xpDomainInfo.bestDomainVerificationStatus 5212 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5213 result.add(xpDomainInfo.resolveInfo); 5214 } 5215 includeBrowser = true; 5216 } 5217 5218 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5219 // If there were 'always' entries their preferred order has been set, so we also 5220 // back that off to make the alternatives equivalent 5221 if (alwaysAskList.size() > 0) { 5222 for (ResolveInfo i : result) { 5223 i.preferredOrder = 0; 5224 } 5225 result.addAll(alwaysAskList); 5226 includeBrowser = true; 5227 } 5228 5229 if (includeBrowser) { 5230 // Also add browsers (all of them or only the default one) 5231 if (DEBUG_DOMAIN_VERIFICATION) { 5232 Slog.v(TAG, " ...including browsers in candidate set"); 5233 } 5234 if ((matchFlags & MATCH_ALL) != 0) { 5235 result.addAll(matchAllList); 5236 } else { 5237 // Browser/generic handling case. If there's a default browser, go straight 5238 // to that (but only if there is no other higher-priority match). 5239 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5240 int maxMatchPrio = 0; 5241 ResolveInfo defaultBrowserMatch = null; 5242 final int numCandidates = matchAllList.size(); 5243 for (int n = 0; n < numCandidates; n++) { 5244 ResolveInfo info = matchAllList.get(n); 5245 // track the highest overall match priority... 5246 if (info.priority > maxMatchPrio) { 5247 maxMatchPrio = info.priority; 5248 } 5249 // ...and the highest-priority default browser match 5250 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5251 if (defaultBrowserMatch == null 5252 || (defaultBrowserMatch.priority < info.priority)) { 5253 if (debug) { 5254 Slog.v(TAG, "Considering default browser match " + info); 5255 } 5256 defaultBrowserMatch = info; 5257 } 5258 } 5259 } 5260 if (defaultBrowserMatch != null 5261 && defaultBrowserMatch.priority >= maxMatchPrio 5262 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5263 { 5264 if (debug) { 5265 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5266 } 5267 result.add(defaultBrowserMatch); 5268 } else { 5269 result.addAll(matchAllList); 5270 } 5271 } 5272 5273 // If there is nothing selected, add all candidates and remove the ones that the user 5274 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5275 if (result.size() == 0) { 5276 result.addAll(candidates); 5277 result.removeAll(neverList); 5278 } 5279 } 5280 } 5281 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5282 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5283 result.size()); 5284 for (ResolveInfo info : result) { 5285 Slog.v(TAG, " + " + info.activityInfo); 5286 } 5287 } 5288 return result; 5289 } 5290 5291 // Returns a packed value as a long: 5292 // 5293 // high 'int'-sized word: link status: undefined/ask/never/always. 5294 // low 'int'-sized word: relative priority among 'always' results. 5295 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5296 long result = ps.getDomainVerificationStatusForUser(userId); 5297 // if none available, get the master status 5298 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5299 if (ps.getIntentFilterVerificationInfo() != null) { 5300 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5301 } 5302 } 5303 return result; 5304 } 5305 5306 private ResolveInfo querySkipCurrentProfileIntents( 5307 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5308 int flags, int sourceUserId) { 5309 if (matchingFilters != null) { 5310 int size = matchingFilters.size(); 5311 for (int i = 0; i < size; i ++) { 5312 CrossProfileIntentFilter filter = matchingFilters.get(i); 5313 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5314 // Checking if there are activities in the target user that can handle the 5315 // intent. 5316 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5317 resolvedType, flags, sourceUserId); 5318 if (resolveInfo != null) { 5319 return resolveInfo; 5320 } 5321 } 5322 } 5323 } 5324 return null; 5325 } 5326 5327 // Return matching ResolveInfo in target user if any. 5328 private ResolveInfo queryCrossProfileIntents( 5329 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5330 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5331 if (matchingFilters != null) { 5332 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5333 // match the same intent. For performance reasons, it is better not to 5334 // run queryIntent twice for the same userId 5335 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5336 int size = matchingFilters.size(); 5337 for (int i = 0; i < size; i++) { 5338 CrossProfileIntentFilter filter = matchingFilters.get(i); 5339 int targetUserId = filter.getTargetUserId(); 5340 boolean skipCurrentProfile = 5341 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5342 boolean skipCurrentProfileIfNoMatchFound = 5343 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5344 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5345 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5346 // Checking if there are activities in the target user that can handle the 5347 // intent. 5348 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5349 resolvedType, flags, sourceUserId); 5350 if (resolveInfo != null) return resolveInfo; 5351 alreadyTriedUserIds.put(targetUserId, true); 5352 } 5353 } 5354 } 5355 return null; 5356 } 5357 5358 /** 5359 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5360 * will forward the intent to the filter's target user. 5361 * Otherwise, returns null. 5362 */ 5363 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5364 String resolvedType, int flags, int sourceUserId) { 5365 int targetUserId = filter.getTargetUserId(); 5366 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5367 resolvedType, flags, targetUserId); 5368 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5369 // If all the matches in the target profile are suspended, return null. 5370 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5371 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5372 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5373 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5374 targetUserId); 5375 } 5376 } 5377 } 5378 return null; 5379 } 5380 5381 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5382 int sourceUserId, int targetUserId) { 5383 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5384 long ident = Binder.clearCallingIdentity(); 5385 boolean targetIsProfile; 5386 try { 5387 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5388 } finally { 5389 Binder.restoreCallingIdentity(ident); 5390 } 5391 String className; 5392 if (targetIsProfile) { 5393 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5394 } else { 5395 className = FORWARD_INTENT_TO_PARENT; 5396 } 5397 ComponentName forwardingActivityComponentName = new ComponentName( 5398 mAndroidApplication.packageName, className); 5399 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5400 sourceUserId); 5401 if (!targetIsProfile) { 5402 forwardingActivityInfo.showUserIcon = targetUserId; 5403 forwardingResolveInfo.noResourceId = true; 5404 } 5405 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5406 forwardingResolveInfo.priority = 0; 5407 forwardingResolveInfo.preferredOrder = 0; 5408 forwardingResolveInfo.match = 0; 5409 forwardingResolveInfo.isDefault = true; 5410 forwardingResolveInfo.filter = filter; 5411 forwardingResolveInfo.targetUserId = targetUserId; 5412 return forwardingResolveInfo; 5413 } 5414 5415 @Override 5416 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5417 Intent[] specifics, String[] specificTypes, Intent intent, 5418 String resolvedType, int flags, int userId) { 5419 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5420 flags = updateFlagsForResolve(flags, userId, intent); 5421 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5422 false, "query intent activity options"); 5423 final String resultsAction = intent.getAction(); 5424 5425 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5426 | PackageManager.GET_RESOLVED_FILTER, userId); 5427 5428 if (DEBUG_INTENT_MATCHING) { 5429 Log.v(TAG, "Query " + intent + ": " + results); 5430 } 5431 5432 int specificsPos = 0; 5433 int N; 5434 5435 // todo: note that the algorithm used here is O(N^2). This 5436 // isn't a problem in our current environment, but if we start running 5437 // into situations where we have more than 5 or 10 matches then this 5438 // should probably be changed to something smarter... 5439 5440 // First we go through and resolve each of the specific items 5441 // that were supplied, taking care of removing any corresponding 5442 // duplicate items in the generic resolve list. 5443 if (specifics != null) { 5444 for (int i=0; i<specifics.length; i++) { 5445 final Intent sintent = specifics[i]; 5446 if (sintent == null) { 5447 continue; 5448 } 5449 5450 if (DEBUG_INTENT_MATCHING) { 5451 Log.v(TAG, "Specific #" + i + ": " + sintent); 5452 } 5453 5454 String action = sintent.getAction(); 5455 if (resultsAction != null && resultsAction.equals(action)) { 5456 // If this action was explicitly requested, then don't 5457 // remove things that have it. 5458 action = null; 5459 } 5460 5461 ResolveInfo ri = null; 5462 ActivityInfo ai = null; 5463 5464 ComponentName comp = sintent.getComponent(); 5465 if (comp == null) { 5466 ri = resolveIntent( 5467 sintent, 5468 specificTypes != null ? specificTypes[i] : null, 5469 flags, userId); 5470 if (ri == null) { 5471 continue; 5472 } 5473 if (ri == mResolveInfo) { 5474 // ACK! Must do something better with this. 5475 } 5476 ai = ri.activityInfo; 5477 comp = new ComponentName(ai.applicationInfo.packageName, 5478 ai.name); 5479 } else { 5480 ai = getActivityInfo(comp, flags, userId); 5481 if (ai == null) { 5482 continue; 5483 } 5484 } 5485 5486 // Look for any generic query activities that are duplicates 5487 // of this specific one, and remove them from the results. 5488 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5489 N = results.size(); 5490 int j; 5491 for (j=specificsPos; j<N; j++) { 5492 ResolveInfo sri = results.get(j); 5493 if ((sri.activityInfo.name.equals(comp.getClassName()) 5494 && sri.activityInfo.applicationInfo.packageName.equals( 5495 comp.getPackageName())) 5496 || (action != null && sri.filter.matchAction(action))) { 5497 results.remove(j); 5498 if (DEBUG_INTENT_MATCHING) Log.v( 5499 TAG, "Removing duplicate item from " + j 5500 + " due to specific " + specificsPos); 5501 if (ri == null) { 5502 ri = sri; 5503 } 5504 j--; 5505 N--; 5506 } 5507 } 5508 5509 // Add this specific item to its proper place. 5510 if (ri == null) { 5511 ri = new ResolveInfo(); 5512 ri.activityInfo = ai; 5513 } 5514 results.add(specificsPos, ri); 5515 ri.specificIndex = i; 5516 specificsPos++; 5517 } 5518 } 5519 5520 // Now we go through the remaining generic results and remove any 5521 // duplicate actions that are found here. 5522 N = results.size(); 5523 for (int i=specificsPos; i<N-1; i++) { 5524 final ResolveInfo rii = results.get(i); 5525 if (rii.filter == null) { 5526 continue; 5527 } 5528 5529 // Iterate over all of the actions of this result's intent 5530 // filter... typically this should be just one. 5531 final Iterator<String> it = rii.filter.actionsIterator(); 5532 if (it == null) { 5533 continue; 5534 } 5535 while (it.hasNext()) { 5536 final String action = it.next(); 5537 if (resultsAction != null && resultsAction.equals(action)) { 5538 // If this action was explicitly requested, then don't 5539 // remove things that have it. 5540 continue; 5541 } 5542 for (int j=i+1; j<N; j++) { 5543 final ResolveInfo rij = results.get(j); 5544 if (rij.filter != null && rij.filter.hasAction(action)) { 5545 results.remove(j); 5546 if (DEBUG_INTENT_MATCHING) Log.v( 5547 TAG, "Removing duplicate item from " + j 5548 + " due to action " + action + " at " + i); 5549 j--; 5550 N--; 5551 } 5552 } 5553 } 5554 5555 // If the caller didn't request filter information, drop it now 5556 // so we don't have to marshall/unmarshall it. 5557 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5558 rii.filter = null; 5559 } 5560 } 5561 5562 // Filter out the caller activity if so requested. 5563 if (caller != null) { 5564 N = results.size(); 5565 for (int i=0; i<N; i++) { 5566 ActivityInfo ainfo = results.get(i).activityInfo; 5567 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5568 && caller.getClassName().equals(ainfo.name)) { 5569 results.remove(i); 5570 break; 5571 } 5572 } 5573 } 5574 5575 // If the caller didn't request filter information, 5576 // drop them now so we don't have to 5577 // marshall/unmarshall it. 5578 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5579 N = results.size(); 5580 for (int i=0; i<N; i++) { 5581 results.get(i).filter = null; 5582 } 5583 } 5584 5585 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5586 return results; 5587 } 5588 5589 @Override 5590 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5591 int userId) { 5592 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5593 flags = updateFlagsForResolve(flags, userId, intent); 5594 ComponentName comp = intent.getComponent(); 5595 if (comp == null) { 5596 if (intent.getSelector() != null) { 5597 intent = intent.getSelector(); 5598 comp = intent.getComponent(); 5599 } 5600 } 5601 if (comp != null) { 5602 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5603 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5604 if (ai != null) { 5605 ResolveInfo ri = new ResolveInfo(); 5606 ri.activityInfo = ai; 5607 list.add(ri); 5608 } 5609 return list; 5610 } 5611 5612 // reader 5613 synchronized (mPackages) { 5614 String pkgName = intent.getPackage(); 5615 if (pkgName == null) { 5616 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5617 } 5618 final PackageParser.Package pkg = mPackages.get(pkgName); 5619 if (pkg != null) { 5620 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5621 userId); 5622 } 5623 return null; 5624 } 5625 } 5626 5627 @Override 5628 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5629 if (!sUserManager.exists(userId)) return null; 5630 flags = updateFlagsForResolve(flags, userId, intent); 5631 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5632 if (query != null) { 5633 if (query.size() >= 1) { 5634 // If there is more than one service with the same priority, 5635 // just arbitrarily pick the first one. 5636 return query.get(0); 5637 } 5638 } 5639 return null; 5640 } 5641 5642 @Override 5643 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5644 int userId) { 5645 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5646 flags = updateFlagsForResolve(flags, userId, intent); 5647 ComponentName comp = intent.getComponent(); 5648 if (comp == null) { 5649 if (intent.getSelector() != null) { 5650 intent = intent.getSelector(); 5651 comp = intent.getComponent(); 5652 } 5653 } 5654 if (comp != null) { 5655 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5656 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5657 if (si != null) { 5658 final ResolveInfo ri = new ResolveInfo(); 5659 ri.serviceInfo = si; 5660 list.add(ri); 5661 } 5662 return list; 5663 } 5664 5665 // reader 5666 synchronized (mPackages) { 5667 String pkgName = intent.getPackage(); 5668 if (pkgName == null) { 5669 return mServices.queryIntent(intent, resolvedType, flags, userId); 5670 } 5671 final PackageParser.Package pkg = mPackages.get(pkgName); 5672 if (pkg != null) { 5673 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5674 userId); 5675 } 5676 return null; 5677 } 5678 } 5679 5680 @Override 5681 public List<ResolveInfo> queryIntentContentProviders( 5682 Intent intent, String resolvedType, int flags, int userId) { 5683 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5684 flags = updateFlagsForResolve(flags, userId, intent); 5685 ComponentName comp = intent.getComponent(); 5686 if (comp == null) { 5687 if (intent.getSelector() != null) { 5688 intent = intent.getSelector(); 5689 comp = intent.getComponent(); 5690 } 5691 } 5692 if (comp != null) { 5693 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5694 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5695 if (pi != null) { 5696 final ResolveInfo ri = new ResolveInfo(); 5697 ri.providerInfo = pi; 5698 list.add(ri); 5699 } 5700 return list; 5701 } 5702 5703 // reader 5704 synchronized (mPackages) { 5705 String pkgName = intent.getPackage(); 5706 if (pkgName == null) { 5707 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5708 } 5709 final PackageParser.Package pkg = mPackages.get(pkgName); 5710 if (pkg != null) { 5711 return mProviders.queryIntentForPackage( 5712 intent, resolvedType, flags, pkg.providers, userId); 5713 } 5714 return null; 5715 } 5716 } 5717 5718 @Override 5719 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5720 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5721 flags = updateFlagsForPackage(flags, userId, null); 5722 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5723 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5724 5725 // writer 5726 synchronized (mPackages) { 5727 ArrayList<PackageInfo> list; 5728 if (listUninstalled) { 5729 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5730 for (PackageSetting ps : mSettings.mPackages.values()) { 5731 PackageInfo pi; 5732 if (ps.pkg != null) { 5733 pi = generatePackageInfo(ps.pkg, flags, userId); 5734 } else { 5735 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5736 } 5737 if (pi != null) { 5738 list.add(pi); 5739 } 5740 } 5741 } else { 5742 list = new ArrayList<PackageInfo>(mPackages.size()); 5743 for (PackageParser.Package p : mPackages.values()) { 5744 PackageInfo pi = generatePackageInfo(p, flags, userId); 5745 if (pi != null) { 5746 list.add(pi); 5747 } 5748 } 5749 } 5750 5751 return new ParceledListSlice<PackageInfo>(list); 5752 } 5753 } 5754 5755 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5756 String[] permissions, boolean[] tmp, int flags, int userId) { 5757 int numMatch = 0; 5758 final PermissionsState permissionsState = ps.getPermissionsState(); 5759 for (int i=0; i<permissions.length; i++) { 5760 final String permission = permissions[i]; 5761 if (permissionsState.hasPermission(permission, userId)) { 5762 tmp[i] = true; 5763 numMatch++; 5764 } else { 5765 tmp[i] = false; 5766 } 5767 } 5768 if (numMatch == 0) { 5769 return; 5770 } 5771 PackageInfo pi; 5772 if (ps.pkg != null) { 5773 pi = generatePackageInfo(ps.pkg, flags, userId); 5774 } else { 5775 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5776 } 5777 // The above might return null in cases of uninstalled apps or install-state 5778 // skew across users/profiles. 5779 if (pi != null) { 5780 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5781 if (numMatch == permissions.length) { 5782 pi.requestedPermissions = permissions; 5783 } else { 5784 pi.requestedPermissions = new String[numMatch]; 5785 numMatch = 0; 5786 for (int i=0; i<permissions.length; i++) { 5787 if (tmp[i]) { 5788 pi.requestedPermissions[numMatch] = permissions[i]; 5789 numMatch++; 5790 } 5791 } 5792 } 5793 } 5794 list.add(pi); 5795 } 5796 } 5797 5798 @Override 5799 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5800 String[] permissions, int flags, int userId) { 5801 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5802 flags = updateFlagsForPackage(flags, userId, permissions); 5803 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5804 5805 // writer 5806 synchronized (mPackages) { 5807 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5808 boolean[] tmpBools = new boolean[permissions.length]; 5809 if (listUninstalled) { 5810 for (PackageSetting ps : mSettings.mPackages.values()) { 5811 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5812 } 5813 } else { 5814 for (PackageParser.Package pkg : mPackages.values()) { 5815 PackageSetting ps = (PackageSetting)pkg.mExtras; 5816 if (ps != null) { 5817 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5818 userId); 5819 } 5820 } 5821 } 5822 5823 return new ParceledListSlice<PackageInfo>(list); 5824 } 5825 } 5826 5827 @Override 5828 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5829 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5830 flags = updateFlagsForApplication(flags, userId, null); 5831 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5832 5833 // writer 5834 synchronized (mPackages) { 5835 ArrayList<ApplicationInfo> list; 5836 if (listUninstalled) { 5837 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5838 for (PackageSetting ps : mSettings.mPackages.values()) { 5839 ApplicationInfo ai; 5840 if (ps.pkg != null) { 5841 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5842 ps.readUserState(userId), userId); 5843 } else { 5844 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5845 } 5846 if (ai != null) { 5847 list.add(ai); 5848 } 5849 } 5850 } else { 5851 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5852 for (PackageParser.Package p : mPackages.values()) { 5853 if (p.mExtras != null) { 5854 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5855 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5856 if (ai != null) { 5857 list.add(ai); 5858 } 5859 } 5860 } 5861 } 5862 5863 return new ParceledListSlice<ApplicationInfo>(list); 5864 } 5865 } 5866 5867 @Override 5868 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5869 if (DISABLE_EPHEMERAL_APPS) { 5870 return null; 5871 } 5872 5873 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5874 "getEphemeralApplications"); 5875 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5876 "getEphemeralApplications"); 5877 synchronized (mPackages) { 5878 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5879 .getEphemeralApplicationsLPw(userId); 5880 if (ephemeralApps != null) { 5881 return new ParceledListSlice<>(ephemeralApps); 5882 } 5883 } 5884 return null; 5885 } 5886 5887 @Override 5888 public boolean isEphemeralApplication(String packageName, int userId) { 5889 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5890 "isEphemeral"); 5891 if (DISABLE_EPHEMERAL_APPS) { 5892 return false; 5893 } 5894 5895 if (!isCallerSameApp(packageName)) { 5896 return false; 5897 } 5898 synchronized (mPackages) { 5899 PackageParser.Package pkg = mPackages.get(packageName); 5900 if (pkg != null) { 5901 return pkg.applicationInfo.isEphemeralApp(); 5902 } 5903 } 5904 return false; 5905 } 5906 5907 @Override 5908 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 5909 if (DISABLE_EPHEMERAL_APPS) { 5910 return null; 5911 } 5912 5913 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5914 "getCookie"); 5915 if (!isCallerSameApp(packageName)) { 5916 return null; 5917 } 5918 synchronized (mPackages) { 5919 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 5920 packageName, userId); 5921 } 5922 } 5923 5924 @Override 5925 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 5926 if (DISABLE_EPHEMERAL_APPS) { 5927 return true; 5928 } 5929 5930 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5931 "setCookie"); 5932 if (!isCallerSameApp(packageName)) { 5933 return false; 5934 } 5935 synchronized (mPackages) { 5936 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 5937 packageName, cookie, userId); 5938 } 5939 } 5940 5941 @Override 5942 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 5943 if (DISABLE_EPHEMERAL_APPS) { 5944 return null; 5945 } 5946 5947 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5948 "getEphemeralApplicationIcon"); 5949 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5950 "getEphemeralApplicationIcon"); 5951 synchronized (mPackages) { 5952 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 5953 packageName, userId); 5954 } 5955 } 5956 5957 private boolean isCallerSameApp(String packageName) { 5958 PackageParser.Package pkg = mPackages.get(packageName); 5959 return pkg != null 5960 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 5961 } 5962 5963 public List<ApplicationInfo> getPersistentApplications(int flags) { 5964 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5965 5966 // reader 5967 synchronized (mPackages) { 5968 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5969 final int userId = UserHandle.getCallingUserId(); 5970 while (i.hasNext()) { 5971 final PackageParser.Package p = i.next(); 5972 if (p.applicationInfo != null 5973 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5974 && (!mSafeMode || isSystemApp(p))) { 5975 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5976 if (ps != null) { 5977 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5978 ps.readUserState(userId), userId); 5979 if (ai != null) { 5980 finalList.add(ai); 5981 } 5982 } 5983 } 5984 } 5985 } 5986 5987 return finalList; 5988 } 5989 5990 @Override 5991 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5992 if (!sUserManager.exists(userId)) return null; 5993 flags = updateFlagsForComponent(flags, userId, name); 5994 // reader 5995 synchronized (mPackages) { 5996 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5997 PackageSetting ps = provider != null 5998 ? mSettings.mPackages.get(provider.owner.packageName) 5999 : null; 6000 return ps != null 6001 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6002 ? PackageParser.generateProviderInfo(provider, flags, 6003 ps.readUserState(userId), userId) 6004 : null; 6005 } 6006 } 6007 6008 /** 6009 * @deprecated 6010 */ 6011 @Deprecated 6012 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6013 // reader 6014 synchronized (mPackages) { 6015 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6016 .entrySet().iterator(); 6017 final int userId = UserHandle.getCallingUserId(); 6018 while (i.hasNext()) { 6019 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6020 PackageParser.Provider p = entry.getValue(); 6021 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6022 6023 if (ps != null && p.syncable 6024 && (!mSafeMode || (p.info.applicationInfo.flags 6025 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6026 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6027 ps.readUserState(userId), userId); 6028 if (info != null) { 6029 outNames.add(entry.getKey()); 6030 outInfo.add(info); 6031 } 6032 } 6033 } 6034 } 6035 } 6036 6037 @Override 6038 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6039 int uid, int flags) { 6040 final int userId = processName != null ? UserHandle.getUserId(uid) 6041 : UserHandle.getCallingUserId(); 6042 if (!sUserManager.exists(userId)) return null; 6043 flags = updateFlagsForComponent(flags, userId, processName); 6044 6045 ArrayList<ProviderInfo> finalList = null; 6046 // reader 6047 synchronized (mPackages) { 6048 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6049 while (i.hasNext()) { 6050 final PackageParser.Provider p = i.next(); 6051 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6052 if (ps != null && p.info.authority != null 6053 && (processName == null 6054 || (p.info.processName.equals(processName) 6055 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6056 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6057 if (finalList == null) { 6058 finalList = new ArrayList<ProviderInfo>(3); 6059 } 6060 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6061 ps.readUserState(userId), userId); 6062 if (info != null) { 6063 finalList.add(info); 6064 } 6065 } 6066 } 6067 } 6068 6069 if (finalList != null) { 6070 Collections.sort(finalList, mProviderInitOrderSorter); 6071 return new ParceledListSlice<ProviderInfo>(finalList); 6072 } 6073 6074 return null; 6075 } 6076 6077 @Override 6078 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6079 // reader 6080 synchronized (mPackages) { 6081 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6082 return PackageParser.generateInstrumentationInfo(i, flags); 6083 } 6084 } 6085 6086 @Override 6087 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6088 int flags) { 6089 ArrayList<InstrumentationInfo> finalList = 6090 new ArrayList<InstrumentationInfo>(); 6091 6092 // reader 6093 synchronized (mPackages) { 6094 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6095 while (i.hasNext()) { 6096 final PackageParser.Instrumentation p = i.next(); 6097 if (targetPackage == null 6098 || targetPackage.equals(p.info.targetPackage)) { 6099 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6100 flags); 6101 if (ii != null) { 6102 finalList.add(ii); 6103 } 6104 } 6105 } 6106 } 6107 6108 return finalList; 6109 } 6110 6111 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6112 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6113 if (overlays == null) { 6114 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6115 return; 6116 } 6117 for (PackageParser.Package opkg : overlays.values()) { 6118 // Not much to do if idmap fails: we already logged the error 6119 // and we certainly don't want to abort installation of pkg simply 6120 // because an overlay didn't fit properly. For these reasons, 6121 // ignore the return value of createIdmapForPackagePairLI. 6122 createIdmapForPackagePairLI(pkg, opkg); 6123 } 6124 } 6125 6126 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6127 PackageParser.Package opkg) { 6128 if (!opkg.mTrustedOverlay) { 6129 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6130 opkg.baseCodePath + ": overlay not trusted"); 6131 return false; 6132 } 6133 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6134 if (overlaySet == null) { 6135 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6136 opkg.baseCodePath + " but target package has no known overlays"); 6137 return false; 6138 } 6139 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6140 // TODO: generate idmap for split APKs 6141 try { 6142 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6143 } catch (InstallerException e) { 6144 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6145 + opkg.baseCodePath); 6146 return false; 6147 } 6148 PackageParser.Package[] overlayArray = 6149 overlaySet.values().toArray(new PackageParser.Package[0]); 6150 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6151 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6152 return p1.mOverlayPriority - p2.mOverlayPriority; 6153 } 6154 }; 6155 Arrays.sort(overlayArray, cmp); 6156 6157 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6158 int i = 0; 6159 for (PackageParser.Package p : overlayArray) { 6160 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6161 } 6162 return true; 6163 } 6164 6165 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6166 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6167 try { 6168 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6169 } finally { 6170 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6171 } 6172 } 6173 6174 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6175 final File[] files = dir.listFiles(); 6176 if (ArrayUtils.isEmpty(files)) { 6177 Log.d(TAG, "No files in app dir " + dir); 6178 return; 6179 } 6180 6181 if (DEBUG_PACKAGE_SCANNING) { 6182 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6183 + " flags=0x" + Integer.toHexString(parseFlags)); 6184 } 6185 6186 for (File file : files) { 6187 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6188 && !PackageInstallerService.isStageName(file.getName()); 6189 if (!isPackage) { 6190 // Ignore entries which are not packages 6191 continue; 6192 } 6193 try { 6194 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6195 scanFlags, currentTime, null); 6196 } catch (PackageManagerException e) { 6197 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6198 6199 // Delete invalid userdata apps 6200 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6201 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6202 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6203 removeCodePathLI(file); 6204 } 6205 } 6206 } 6207 } 6208 6209 private static File getSettingsProblemFile() { 6210 File dataDir = Environment.getDataDirectory(); 6211 File systemDir = new File(dataDir, "system"); 6212 File fname = new File(systemDir, "uiderrors.txt"); 6213 return fname; 6214 } 6215 6216 static void reportSettingsProblem(int priority, String msg) { 6217 logCriticalInfo(priority, msg); 6218 } 6219 6220 static void logCriticalInfo(int priority, String msg) { 6221 Slog.println(priority, TAG, msg); 6222 EventLogTags.writePmCriticalInfo(msg); 6223 try { 6224 File fname = getSettingsProblemFile(); 6225 FileOutputStream out = new FileOutputStream(fname, true); 6226 PrintWriter pw = new FastPrintWriter(out); 6227 SimpleDateFormat formatter = new SimpleDateFormat(); 6228 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6229 pw.println(dateString + ": " + msg); 6230 pw.close(); 6231 FileUtils.setPermissions( 6232 fname.toString(), 6233 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6234 -1, -1); 6235 } catch (java.io.IOException e) { 6236 } 6237 } 6238 6239 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 6240 PackageParser.Package pkg, File srcFile, int parseFlags) 6241 throws PackageManagerException { 6242 if (ps != null 6243 && ps.codePath.equals(srcFile) 6244 && ps.timeStamp == srcFile.lastModified() 6245 && !isCompatSignatureUpdateNeeded(pkg) 6246 && !isRecoverSignatureUpdateNeeded(pkg)) { 6247 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6248 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6249 ArraySet<PublicKey> signingKs; 6250 synchronized (mPackages) { 6251 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6252 } 6253 if (ps.signatures.mSignatures != null 6254 && ps.signatures.mSignatures.length != 0 6255 && signingKs != null) { 6256 // Optimization: reuse the existing cached certificates 6257 // if the package appears to be unchanged. 6258 pkg.mSignatures = ps.signatures.mSignatures; 6259 pkg.mSigningKeys = signingKs; 6260 return; 6261 } 6262 6263 Slog.w(TAG, "PackageSetting for " + ps.name 6264 + " is missing signatures. Collecting certs again to recover them."); 6265 } else { 6266 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6267 } 6268 6269 try { 6270 pp.collectCertificates(pkg, parseFlags); 6271 } catch (PackageParserException e) { 6272 throw PackageManagerException.from(e); 6273 } 6274 } 6275 6276 /** 6277 * Traces a package scan. 6278 * @see #scanPackageLI(File, int, int, long, UserHandle) 6279 */ 6280 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6281 long currentTime, UserHandle user) throws PackageManagerException { 6282 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6283 try { 6284 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6285 } finally { 6286 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6287 } 6288 } 6289 6290 /** 6291 * Scans a package and returns the newly parsed package. 6292 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6293 */ 6294 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6295 long currentTime, UserHandle user) throws PackageManagerException { 6296 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6297 parseFlags |= mDefParseFlags; 6298 PackageParser pp = new PackageParser(); 6299 pp.setSeparateProcesses(mSeparateProcesses); 6300 pp.setOnlyCoreApps(mOnlyCore); 6301 pp.setDisplayMetrics(mMetrics); 6302 6303 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6304 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6305 } 6306 6307 final PackageParser.Package pkg; 6308 try { 6309 pkg = pp.parsePackage(scanFile, parseFlags); 6310 } catch (PackageParserException e) { 6311 throw PackageManagerException.from(e); 6312 } 6313 6314 PackageSetting ps = null; 6315 PackageSetting updatedPkg; 6316 // reader 6317 synchronized (mPackages) { 6318 // Look to see if we already know about this package. 6319 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6320 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6321 // This package has been renamed to its original name. Let's 6322 // use that. 6323 ps = mSettings.peekPackageLPr(oldName); 6324 } 6325 // If there was no original package, see one for the real package name. 6326 if (ps == null) { 6327 ps = mSettings.peekPackageLPr(pkg.packageName); 6328 } 6329 // Check to see if this package could be hiding/updating a system 6330 // package. Must look for it either under the original or real 6331 // package name depending on our state. 6332 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6333 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6334 } 6335 boolean updatedPkgBetter = false; 6336 // First check if this is a system package that may involve an update 6337 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6338 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6339 // it needs to drop FLAG_PRIVILEGED. 6340 if (locationIsPrivileged(scanFile)) { 6341 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6342 } else { 6343 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6344 } 6345 6346 if (ps != null && !ps.codePath.equals(scanFile)) { 6347 // The path has changed from what was last scanned... check the 6348 // version of the new path against what we have stored to determine 6349 // what to do. 6350 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6351 if (pkg.mVersionCode <= ps.versionCode) { 6352 // The system package has been updated and the code path does not match 6353 // Ignore entry. Skip it. 6354 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6355 + " ignored: updated version " + ps.versionCode 6356 + " better than this " + pkg.mVersionCode); 6357 if (!updatedPkg.codePath.equals(scanFile)) { 6358 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6359 + ps.name + " changing from " + updatedPkg.codePathString 6360 + " to " + scanFile); 6361 updatedPkg.codePath = scanFile; 6362 updatedPkg.codePathString = scanFile.toString(); 6363 updatedPkg.resourcePath = scanFile; 6364 updatedPkg.resourcePathString = scanFile.toString(); 6365 } 6366 updatedPkg.pkg = pkg; 6367 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6368 "Package " + ps.name + " at " + scanFile 6369 + " ignored: updated version " + ps.versionCode 6370 + " better than this " + pkg.mVersionCode); 6371 } else { 6372 // The current app on the system partition is better than 6373 // what we have updated to on the data partition; switch 6374 // back to the system partition version. 6375 // At this point, its safely assumed that package installation for 6376 // apps in system partition will go through. If not there won't be a working 6377 // version of the app 6378 // writer 6379 synchronized (mPackages) { 6380 // Just remove the loaded entries from package lists. 6381 mPackages.remove(ps.name); 6382 } 6383 6384 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6385 + " reverting from " + ps.codePathString 6386 + ": new version " + pkg.mVersionCode 6387 + " better than installed " + ps.versionCode); 6388 6389 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6390 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6391 synchronized (mInstallLock) { 6392 args.cleanUpResourcesLI(); 6393 } 6394 synchronized (mPackages) { 6395 mSettings.enableSystemPackageLPw(ps.name); 6396 } 6397 updatedPkgBetter = true; 6398 } 6399 } 6400 } 6401 6402 if (updatedPkg != null) { 6403 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6404 // initially 6405 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6406 6407 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6408 // flag set initially 6409 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6410 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6411 } 6412 } 6413 6414 // Verify certificates against what was last scanned 6415 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 6416 6417 /* 6418 * A new system app appeared, but we already had a non-system one of the 6419 * same name installed earlier. 6420 */ 6421 boolean shouldHideSystemApp = false; 6422 if (updatedPkg == null && ps != null 6423 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6424 /* 6425 * Check to make sure the signatures match first. If they don't, 6426 * wipe the installed application and its data. 6427 */ 6428 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6429 != PackageManager.SIGNATURE_MATCH) { 6430 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6431 + " signatures don't match existing userdata copy; removing"); 6432 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 6433 ps = null; 6434 } else { 6435 /* 6436 * If the newly-added system app is an older version than the 6437 * already installed version, hide it. It will be scanned later 6438 * and re-added like an update. 6439 */ 6440 if (pkg.mVersionCode <= ps.versionCode) { 6441 shouldHideSystemApp = true; 6442 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6443 + " but new version " + pkg.mVersionCode + " better than installed " 6444 + ps.versionCode + "; hiding system"); 6445 } else { 6446 /* 6447 * The newly found system app is a newer version that the 6448 * one previously installed. Simply remove the 6449 * already-installed application and replace it with our own 6450 * while keeping the application data. 6451 */ 6452 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6453 + " reverting from " + ps.codePathString + ": new version " 6454 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6455 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6456 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6457 synchronized (mInstallLock) { 6458 args.cleanUpResourcesLI(); 6459 } 6460 } 6461 } 6462 } 6463 6464 // The apk is forward locked (not public) if its code and resources 6465 // are kept in different files. (except for app in either system or 6466 // vendor path). 6467 // TODO grab this value from PackageSettings 6468 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6469 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6470 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6471 } 6472 } 6473 6474 // TODO: extend to support forward-locked splits 6475 String resourcePath = null; 6476 String baseResourcePath = null; 6477 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6478 if (ps != null && ps.resourcePathString != null) { 6479 resourcePath = ps.resourcePathString; 6480 baseResourcePath = ps.resourcePathString; 6481 } else { 6482 // Should not happen at all. Just log an error. 6483 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6484 } 6485 } else { 6486 resourcePath = pkg.codePath; 6487 baseResourcePath = pkg.baseCodePath; 6488 } 6489 6490 // Set application objects path explicitly. 6491 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6492 pkg.applicationInfo.setCodePath(pkg.codePath); 6493 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6494 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6495 pkg.applicationInfo.setResourcePath(resourcePath); 6496 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6497 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6498 6499 // Note that we invoke the following method only if we are about to unpack an application 6500 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6501 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6502 6503 /* 6504 * If the system app should be overridden by a previously installed 6505 * data, hide the system app now and let the /data/app scan pick it up 6506 * again. 6507 */ 6508 if (shouldHideSystemApp) { 6509 synchronized (mPackages) { 6510 mSettings.disableSystemPackageLPw(pkg.packageName); 6511 } 6512 } 6513 6514 return scannedPkg; 6515 } 6516 6517 private static String fixProcessName(String defProcessName, 6518 String processName, int uid) { 6519 if (processName == null) { 6520 return defProcessName; 6521 } 6522 return processName; 6523 } 6524 6525 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6526 throws PackageManagerException { 6527 if (pkgSetting.signatures.mSignatures != null) { 6528 // Already existing package. Make sure signatures match 6529 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6530 == PackageManager.SIGNATURE_MATCH; 6531 if (!match) { 6532 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6533 == PackageManager.SIGNATURE_MATCH; 6534 } 6535 if (!match) { 6536 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6537 == PackageManager.SIGNATURE_MATCH; 6538 } 6539 if (!match) { 6540 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6541 + pkg.packageName + " signatures do not match the " 6542 + "previously installed version; ignoring!"); 6543 } 6544 } 6545 6546 // Check for shared user signatures 6547 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6548 // Already existing package. Make sure signatures match 6549 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6550 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6551 if (!match) { 6552 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6553 == PackageManager.SIGNATURE_MATCH; 6554 } 6555 if (!match) { 6556 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6557 == PackageManager.SIGNATURE_MATCH; 6558 } 6559 if (!match) { 6560 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6561 "Package " + pkg.packageName 6562 + " has no signatures that match those in shared user " 6563 + pkgSetting.sharedUser.name + "; ignoring!"); 6564 } 6565 } 6566 } 6567 6568 /** 6569 * Enforces that only the system UID or root's UID can call a method exposed 6570 * via Binder. 6571 * 6572 * @param message used as message if SecurityException is thrown 6573 * @throws SecurityException if the caller is not system or root 6574 */ 6575 private static final void enforceSystemOrRoot(String message) { 6576 final int uid = Binder.getCallingUid(); 6577 if (uid != Process.SYSTEM_UID && uid != 0) { 6578 throw new SecurityException(message); 6579 } 6580 } 6581 6582 @Override 6583 public void performFstrimIfNeeded() { 6584 enforceSystemOrRoot("Only the system can request fstrim"); 6585 6586 // Before everything else, see whether we need to fstrim. 6587 try { 6588 IMountService ms = PackageHelper.getMountService(); 6589 if (ms != null) { 6590 final boolean isUpgrade = isUpgrade(); 6591 boolean doTrim = isUpgrade; 6592 if (doTrim) { 6593 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6594 } else { 6595 final long interval = android.provider.Settings.Global.getLong( 6596 mContext.getContentResolver(), 6597 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6598 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6599 if (interval > 0) { 6600 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6601 if (timeSinceLast > interval) { 6602 doTrim = true; 6603 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6604 + "; running immediately"); 6605 } 6606 } 6607 } 6608 if (doTrim) { 6609 if (!isFirstBoot()) { 6610 try { 6611 ActivityManagerNative.getDefault().showBootMessage( 6612 mContext.getResources().getString( 6613 R.string.android_upgrading_fstrim), true); 6614 } catch (RemoteException e) { 6615 } 6616 } 6617 ms.runMaintenance(); 6618 } 6619 } else { 6620 Slog.e(TAG, "Mount service unavailable!"); 6621 } 6622 } catch (RemoteException e) { 6623 // Can't happen; MountService is local 6624 } 6625 } 6626 6627 @Override 6628 public void extractPackagesIfNeeded() { 6629 enforceSystemOrRoot("Only the system can request package extraction"); 6630 6631 // Extract pacakges only if profile-guided compilation is enabled because 6632 // otherwise BackgroundDexOptService will not dexopt them later. 6633 if (mUseJitProfiles) { 6634 ArraySet<String> pkgs = getOptimizablePackages(); 6635 if (pkgs != null) { 6636 for (String pkg : pkgs) { 6637 performDexOpt(pkg, null /* instructionSet */, false /* useProfiles */, 6638 true /* extractOnly */, false /* force */); 6639 } 6640 } 6641 } 6642 } 6643 6644 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6645 List<ResolveInfo> ris = null; 6646 try { 6647 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6648 intent, null, 0, userId); 6649 } catch (RemoteException e) { 6650 } 6651 ArraySet<String> pkgNames = new ArraySet<String>(); 6652 if (ris != null) { 6653 for (ResolveInfo ri : ris) { 6654 pkgNames.add(ri.activityInfo.packageName); 6655 } 6656 } 6657 return pkgNames; 6658 } 6659 6660 @Override 6661 public void notifyPackageUse(String packageName) { 6662 synchronized (mPackages) { 6663 PackageParser.Package p = mPackages.get(packageName); 6664 if (p == null) { 6665 return; 6666 } 6667 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6668 } 6669 } 6670 6671 // TODO: this is not used nor needed. Delete it. 6672 @Override 6673 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6674 return performDexOptTraced(packageName, instructionSet, false /* useProfiles */, 6675 false /* extractOnly */, false /* force */); 6676 } 6677 6678 @Override 6679 public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles, 6680 boolean extractOnly, boolean force) { 6681 return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force); 6682 } 6683 6684 private boolean performDexOptTraced(String packageName, String instructionSet, 6685 boolean useProfiles, boolean extractOnly, boolean force) { 6686 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6687 try { 6688 return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly, 6689 force); 6690 } finally { 6691 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6692 } 6693 } 6694 6695 private boolean performDexOptInternal(String packageName, String instructionSet, 6696 boolean useProfiles, boolean extractOnly, boolean force) { 6697 PackageParser.Package p; 6698 final String targetInstructionSet; 6699 synchronized (mPackages) { 6700 p = mPackages.get(packageName); 6701 if (p == null) { 6702 return false; 6703 } 6704 mPackageUsage.write(false); 6705 6706 targetInstructionSet = instructionSet != null ? instructionSet : 6707 getPrimaryInstructionSet(p.applicationInfo); 6708 if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) { 6709 // Skip only if we do not use profiles since they might trigger a recompilation. 6710 return false; 6711 } 6712 } 6713 long callingId = Binder.clearCallingIdentity(); 6714 try { 6715 synchronized (mInstallLock) { 6716 final String[] instructionSets = new String[] { targetInstructionSet }; 6717 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 6718 useProfiles, extractOnly, force); 6719 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6720 } 6721 } finally { 6722 Binder.restoreCallingIdentity(callingId); 6723 } 6724 } 6725 6726 public ArraySet<String> getOptimizablePackages() { 6727 ArraySet<String> pkgs = new ArraySet<String>(); 6728 synchronized (mPackages) { 6729 for (PackageParser.Package p : mPackages.values()) { 6730 if (PackageDexOptimizer.canOptimizePackage(p)) { 6731 pkgs.add(p.packageName); 6732 } 6733 } 6734 } 6735 return pkgs; 6736 } 6737 6738 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 6739 String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) { 6740 // Select the dex optimizer based on the force parameter. 6741 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 6742 // allocate an object here. 6743 PackageDexOptimizer pdo = force 6744 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 6745 : mPackageDexOptimizer; 6746 6747 // Optimize all dependencies first. Note: we ignore the return value and march on 6748 // on errors. 6749 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 6750 if (!deps.isEmpty()) { 6751 for (PackageParser.Package depPackage : deps) { 6752 // TODO: Analyze and investigate if we (should) profile libraries. 6753 // Currently this will do a full compilation of the library. 6754 pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */, 6755 false /* extractOnly */); 6756 } 6757 } 6758 6759 return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly); 6760 } 6761 6762 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 6763 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 6764 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 6765 Set<String> collectedNames = new HashSet<>(); 6766 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 6767 6768 retValue.remove(p); 6769 6770 return retValue; 6771 } else { 6772 return Collections.emptyList(); 6773 } 6774 } 6775 6776 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 6777 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 6778 if (!collectedNames.contains(p.packageName)) { 6779 collectedNames.add(p.packageName); 6780 collected.add(p); 6781 6782 if (p.usesLibraries != null) { 6783 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 6784 } 6785 if (p.usesOptionalLibraries != null) { 6786 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 6787 collectedNames); 6788 } 6789 } 6790 } 6791 6792 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 6793 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 6794 for (String libName : libs) { 6795 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 6796 if (libPkg != null) { 6797 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 6798 } 6799 } 6800 } 6801 6802 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 6803 synchronized (mPackages) { 6804 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 6805 if (lib != null && lib.apk != null) { 6806 return mPackages.get(lib.apk); 6807 } 6808 } 6809 return null; 6810 } 6811 6812 public void shutdown() { 6813 mPackageUsage.write(true); 6814 } 6815 6816 @Override 6817 public void forceDexOpt(String packageName) { 6818 enforceSystemOrRoot("forceDexOpt"); 6819 6820 PackageParser.Package pkg; 6821 synchronized (mPackages) { 6822 pkg = mPackages.get(packageName); 6823 if (pkg == null) { 6824 throw new IllegalArgumentException("Unknown package: " + packageName); 6825 } 6826 } 6827 6828 synchronized (mInstallLock) { 6829 final String[] instructionSets = new String[] { 6830 getPrimaryInstructionSet(pkg.applicationInfo) }; 6831 6832 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6833 6834 // Whoever is calling forceDexOpt wants a fully compiled package. 6835 // Don't use profiles since that may cause compilation to be skipped. 6836 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 6837 false /* useProfiles */, false /* extractOnly */, true /* force */); 6838 6839 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6840 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6841 throw new IllegalStateException("Failed to dexopt: " + res); 6842 } 6843 } 6844 } 6845 6846 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6847 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6848 Slog.w(TAG, "Unable to update from " + oldPkg.name 6849 + " to " + newPkg.packageName 6850 + ": old package not in system partition"); 6851 return false; 6852 } else if (mPackages.get(oldPkg.name) != null) { 6853 Slog.w(TAG, "Unable to update from " + oldPkg.name 6854 + " to " + newPkg.packageName 6855 + ": old package still exists"); 6856 return false; 6857 } 6858 return true; 6859 } 6860 6861 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 6862 // TODO: triage flags as part of 26466827 6863 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 6864 6865 boolean res = true; 6866 final int[] users = sUserManager.getUserIds(); 6867 for (int user : users) { 6868 try { 6869 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 6870 } catch (InstallerException e) { 6871 Slog.w(TAG, "Failed to delete data directory", e); 6872 res = false; 6873 } 6874 } 6875 return res; 6876 } 6877 6878 void removeCodePathLI(File codePath) { 6879 if (codePath.isDirectory()) { 6880 try { 6881 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 6882 } catch (InstallerException e) { 6883 Slog.w(TAG, "Failed to remove code path", e); 6884 } 6885 } else { 6886 codePath.delete(); 6887 } 6888 } 6889 6890 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 6891 try { 6892 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 6893 } catch (InstallerException e) { 6894 Slog.w(TAG, "Failed to destroy app data", e); 6895 } 6896 } 6897 6898 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 6899 int appId, String seinfo) { 6900 try { 6901 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 6902 } catch (InstallerException e) { 6903 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 6904 } 6905 } 6906 6907 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6908 // TODO: triage flags as part of 26466827 6909 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 6910 6911 final int[] users = sUserManager.getUserIds(); 6912 for (int user : users) { 6913 try { 6914 mInstaller.clearAppData(volumeUuid, packageName, user, 6915 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 6916 } catch (InstallerException e) { 6917 Slog.w(TAG, "Failed to delete code cache directory", e); 6918 } 6919 } 6920 } 6921 6922 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6923 PackageParser.Package changingLib) { 6924 if (file.path != null) { 6925 usesLibraryFiles.add(file.path); 6926 return; 6927 } 6928 PackageParser.Package p = mPackages.get(file.apk); 6929 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6930 // If we are doing this while in the middle of updating a library apk, 6931 // then we need to make sure to use that new apk for determining the 6932 // dependencies here. (We haven't yet finished committing the new apk 6933 // to the package manager state.) 6934 if (p == null || p.packageName.equals(changingLib.packageName)) { 6935 p = changingLib; 6936 } 6937 } 6938 if (p != null) { 6939 usesLibraryFiles.addAll(p.getAllCodePaths()); 6940 } 6941 } 6942 6943 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6944 PackageParser.Package changingLib) throws PackageManagerException { 6945 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6946 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6947 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6948 for (int i=0; i<N; i++) { 6949 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6950 if (file == null) { 6951 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6952 "Package " + pkg.packageName + " requires unavailable shared library " 6953 + pkg.usesLibraries.get(i) + "; failing!"); 6954 } 6955 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6956 } 6957 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6958 for (int i=0; i<N; i++) { 6959 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6960 if (file == null) { 6961 Slog.w(TAG, "Package " + pkg.packageName 6962 + " desires unavailable shared library " 6963 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6964 } else { 6965 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6966 } 6967 } 6968 N = usesLibraryFiles.size(); 6969 if (N > 0) { 6970 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6971 } else { 6972 pkg.usesLibraryFiles = null; 6973 } 6974 } 6975 } 6976 6977 private static boolean hasString(List<String> list, List<String> which) { 6978 if (list == null) { 6979 return false; 6980 } 6981 for (int i=list.size()-1; i>=0; i--) { 6982 for (int j=which.size()-1; j>=0; j--) { 6983 if (which.get(j).equals(list.get(i))) { 6984 return true; 6985 } 6986 } 6987 } 6988 return false; 6989 } 6990 6991 private void updateAllSharedLibrariesLPw() { 6992 for (PackageParser.Package pkg : mPackages.values()) { 6993 try { 6994 updateSharedLibrariesLPw(pkg, null); 6995 } catch (PackageManagerException e) { 6996 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6997 } 6998 } 6999 } 7000 7001 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7002 PackageParser.Package changingPkg) { 7003 ArrayList<PackageParser.Package> res = null; 7004 for (PackageParser.Package pkg : mPackages.values()) { 7005 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7006 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7007 if (res == null) { 7008 res = new ArrayList<PackageParser.Package>(); 7009 } 7010 res.add(pkg); 7011 try { 7012 updateSharedLibrariesLPw(pkg, changingPkg); 7013 } catch (PackageManagerException e) { 7014 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7015 } 7016 } 7017 } 7018 return res; 7019 } 7020 7021 /** 7022 * Derive the value of the {@code cpuAbiOverride} based on the provided 7023 * value and an optional stored value from the package settings. 7024 */ 7025 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7026 String cpuAbiOverride = null; 7027 7028 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7029 cpuAbiOverride = null; 7030 } else if (abiOverride != null) { 7031 cpuAbiOverride = abiOverride; 7032 } else if (settings != null) { 7033 cpuAbiOverride = settings.cpuAbiOverrideString; 7034 } 7035 7036 return cpuAbiOverride; 7037 } 7038 7039 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7040 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7041 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7042 try { 7043 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7044 } finally { 7045 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7046 } 7047 } 7048 7049 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7050 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7051 boolean success = false; 7052 try { 7053 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7054 currentTime, user); 7055 success = true; 7056 return res; 7057 } finally { 7058 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7059 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7060 } 7061 } 7062 } 7063 7064 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7065 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7066 final File scanFile = new File(pkg.codePath); 7067 if (pkg.applicationInfo.getCodePath() == null || 7068 pkg.applicationInfo.getResourcePath() == null) { 7069 // Bail out. The resource and code paths haven't been set. 7070 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7071 "Code and resource paths haven't been set correctly"); 7072 } 7073 7074 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7075 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7076 } else { 7077 // Only allow system apps to be flagged as core apps. 7078 pkg.coreApp = false; 7079 } 7080 7081 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7082 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7083 } 7084 7085 if (mCustomResolverComponentName != null && 7086 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7087 setUpCustomResolverActivity(pkg); 7088 } 7089 7090 if (pkg.packageName.equals("android")) { 7091 synchronized (mPackages) { 7092 if (mAndroidApplication != null) { 7093 Slog.w(TAG, "*************************************************"); 7094 Slog.w(TAG, "Core android package being redefined. Skipping."); 7095 Slog.w(TAG, " file=" + scanFile); 7096 Slog.w(TAG, "*************************************************"); 7097 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7098 "Core android package being redefined. Skipping."); 7099 } 7100 7101 // Set up information for our fall-back user intent resolution activity. 7102 mPlatformPackage = pkg; 7103 pkg.mVersionCode = mSdkVersion; 7104 mAndroidApplication = pkg.applicationInfo; 7105 7106 if (!mResolverReplaced) { 7107 mResolveActivity.applicationInfo = mAndroidApplication; 7108 mResolveActivity.name = ResolverActivity.class.getName(); 7109 mResolveActivity.packageName = mAndroidApplication.packageName; 7110 mResolveActivity.processName = "system:ui"; 7111 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7112 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7113 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7114 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7115 mResolveActivity.exported = true; 7116 mResolveActivity.enabled = true; 7117 mResolveInfo.activityInfo = mResolveActivity; 7118 mResolveInfo.priority = 0; 7119 mResolveInfo.preferredOrder = 0; 7120 mResolveInfo.match = 0; 7121 mResolveComponentName = new ComponentName( 7122 mAndroidApplication.packageName, mResolveActivity.name); 7123 } 7124 } 7125 } 7126 7127 if (DEBUG_PACKAGE_SCANNING) { 7128 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7129 Log.d(TAG, "Scanning package " + pkg.packageName); 7130 } 7131 7132 if (mPackages.containsKey(pkg.packageName) 7133 || mSharedLibraries.containsKey(pkg.packageName)) { 7134 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7135 "Application package " + pkg.packageName 7136 + " already installed. Skipping duplicate."); 7137 } 7138 7139 // If we're only installing presumed-existing packages, require that the 7140 // scanned APK is both already known and at the path previously established 7141 // for it. Previously unknown packages we pick up normally, but if we have an 7142 // a priori expectation about this package's install presence, enforce it. 7143 // With a singular exception for new system packages. When an OTA contains 7144 // a new system package, we allow the codepath to change from a system location 7145 // to the user-installed location. If we don't allow this change, any newer, 7146 // user-installed version of the application will be ignored. 7147 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7148 if (mExpectingBetter.containsKey(pkg.packageName)) { 7149 logCriticalInfo(Log.WARN, 7150 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7151 } else { 7152 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7153 if (known != null) { 7154 if (DEBUG_PACKAGE_SCANNING) { 7155 Log.d(TAG, "Examining " + pkg.codePath 7156 + " and requiring known paths " + known.codePathString 7157 + " & " + known.resourcePathString); 7158 } 7159 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7160 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 7161 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7162 "Application package " + pkg.packageName 7163 + " found at " + pkg.applicationInfo.getCodePath() 7164 + " but expected at " + known.codePathString + "; ignoring."); 7165 } 7166 } 7167 } 7168 } 7169 7170 // Initialize package source and resource directories 7171 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7172 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7173 7174 SharedUserSetting suid = null; 7175 PackageSetting pkgSetting = null; 7176 7177 if (!isSystemApp(pkg)) { 7178 // Only system apps can use these features. 7179 pkg.mOriginalPackages = null; 7180 pkg.mRealPackage = null; 7181 pkg.mAdoptPermissions = null; 7182 } 7183 7184 // writer 7185 synchronized (mPackages) { 7186 if (pkg.mSharedUserId != null) { 7187 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7188 if (suid == null) { 7189 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7190 "Creating application package " + pkg.packageName 7191 + " for shared user failed"); 7192 } 7193 if (DEBUG_PACKAGE_SCANNING) { 7194 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7195 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7196 + "): packages=" + suid.packages); 7197 } 7198 } 7199 7200 // Check if we are renaming from an original package name. 7201 PackageSetting origPackage = null; 7202 String realName = null; 7203 if (pkg.mOriginalPackages != null) { 7204 // This package may need to be renamed to a previously 7205 // installed name. Let's check on that... 7206 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7207 if (pkg.mOriginalPackages.contains(renamed)) { 7208 // This package had originally been installed as the 7209 // original name, and we have already taken care of 7210 // transitioning to the new one. Just update the new 7211 // one to continue using the old name. 7212 realName = pkg.mRealPackage; 7213 if (!pkg.packageName.equals(renamed)) { 7214 // Callers into this function may have already taken 7215 // care of renaming the package; only do it here if 7216 // it is not already done. 7217 pkg.setPackageName(renamed); 7218 } 7219 7220 } else { 7221 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7222 if ((origPackage = mSettings.peekPackageLPr( 7223 pkg.mOriginalPackages.get(i))) != null) { 7224 // We do have the package already installed under its 7225 // original name... should we use it? 7226 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7227 // New package is not compatible with original. 7228 origPackage = null; 7229 continue; 7230 } else if (origPackage.sharedUser != null) { 7231 // Make sure uid is compatible between packages. 7232 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7233 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7234 + " to " + pkg.packageName + ": old uid " 7235 + origPackage.sharedUser.name 7236 + " differs from " + pkg.mSharedUserId); 7237 origPackage = null; 7238 continue; 7239 } 7240 } else { 7241 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7242 + pkg.packageName + " to old name " + origPackage.name); 7243 } 7244 break; 7245 } 7246 } 7247 } 7248 } 7249 7250 if (mTransferedPackages.contains(pkg.packageName)) { 7251 Slog.w(TAG, "Package " + pkg.packageName 7252 + " was transferred to another, but its .apk remains"); 7253 } 7254 7255 // Just create the setting, don't add it yet. For already existing packages 7256 // the PkgSetting exists already and doesn't have to be created. 7257 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7258 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7259 pkg.applicationInfo.primaryCpuAbi, 7260 pkg.applicationInfo.secondaryCpuAbi, 7261 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7262 user, false); 7263 if (pkgSetting == null) { 7264 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7265 "Creating application package " + pkg.packageName + " failed"); 7266 } 7267 7268 if (pkgSetting.origPackage != null) { 7269 // If we are first transitioning from an original package, 7270 // fix up the new package's name now. We need to do this after 7271 // looking up the package under its new name, so getPackageLP 7272 // can take care of fiddling things correctly. 7273 pkg.setPackageName(origPackage.name); 7274 7275 // File a report about this. 7276 String msg = "New package " + pkgSetting.realName 7277 + " renamed to replace old package " + pkgSetting.name; 7278 reportSettingsProblem(Log.WARN, msg); 7279 7280 // Make a note of it. 7281 mTransferedPackages.add(origPackage.name); 7282 7283 // No longer need to retain this. 7284 pkgSetting.origPackage = null; 7285 } 7286 7287 if (realName != null) { 7288 // Make a note of it. 7289 mTransferedPackages.add(pkg.packageName); 7290 } 7291 7292 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7293 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7294 } 7295 7296 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7297 // Check all shared libraries and map to their actual file path. 7298 // We only do this here for apps not on a system dir, because those 7299 // are the only ones that can fail an install due to this. We 7300 // will take care of the system apps by updating all of their 7301 // library paths after the scan is done. 7302 updateSharedLibrariesLPw(pkg, null); 7303 } 7304 7305 if (mFoundPolicyFile) { 7306 SELinuxMMAC.assignSeinfoValue(pkg); 7307 } 7308 7309 pkg.applicationInfo.uid = pkgSetting.appId; 7310 pkg.mExtras = pkgSetting; 7311 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7312 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7313 // We just determined the app is signed correctly, so bring 7314 // over the latest parsed certs. 7315 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7316 } else { 7317 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7318 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7319 "Package " + pkg.packageName + " upgrade keys do not match the " 7320 + "previously installed version"); 7321 } else { 7322 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7323 String msg = "System package " + pkg.packageName 7324 + " signature changed; retaining data."; 7325 reportSettingsProblem(Log.WARN, msg); 7326 } 7327 } 7328 } else { 7329 try { 7330 verifySignaturesLP(pkgSetting, pkg); 7331 // We just determined the app is signed correctly, so bring 7332 // over the latest parsed certs. 7333 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7334 } catch (PackageManagerException e) { 7335 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7336 throw e; 7337 } 7338 // The signature has changed, but this package is in the system 7339 // image... let's recover! 7340 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7341 // However... if this package is part of a shared user, but it 7342 // doesn't match the signature of the shared user, let's fail. 7343 // What this means is that you can't change the signatures 7344 // associated with an overall shared user, which doesn't seem all 7345 // that unreasonable. 7346 if (pkgSetting.sharedUser != null) { 7347 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7348 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7349 throw new PackageManagerException( 7350 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7351 "Signature mismatch for shared user: " 7352 + pkgSetting.sharedUser); 7353 } 7354 } 7355 // File a report about this. 7356 String msg = "System package " + pkg.packageName 7357 + " signature changed; retaining data."; 7358 reportSettingsProblem(Log.WARN, msg); 7359 } 7360 } 7361 // Verify that this new package doesn't have any content providers 7362 // that conflict with existing packages. Only do this if the 7363 // package isn't already installed, since we don't want to break 7364 // things that are installed. 7365 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7366 final int N = pkg.providers.size(); 7367 int i; 7368 for (i=0; i<N; i++) { 7369 PackageParser.Provider p = pkg.providers.get(i); 7370 if (p.info.authority != null) { 7371 String names[] = p.info.authority.split(";"); 7372 for (int j = 0; j < names.length; j++) { 7373 if (mProvidersByAuthority.containsKey(names[j])) { 7374 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7375 final String otherPackageName = 7376 ((other != null && other.getComponentName() != null) ? 7377 other.getComponentName().getPackageName() : "?"); 7378 throw new PackageManagerException( 7379 INSTALL_FAILED_CONFLICTING_PROVIDER, 7380 "Can't install because provider name " + names[j] 7381 + " (in package " + pkg.applicationInfo.packageName 7382 + ") is already used by " + otherPackageName); 7383 } 7384 } 7385 } 7386 } 7387 } 7388 7389 if (pkg.mAdoptPermissions != null) { 7390 // This package wants to adopt ownership of permissions from 7391 // another package. 7392 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7393 final String origName = pkg.mAdoptPermissions.get(i); 7394 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7395 if (orig != null) { 7396 if (verifyPackageUpdateLPr(orig, pkg)) { 7397 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7398 + pkg.packageName); 7399 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7400 } 7401 } 7402 } 7403 } 7404 } 7405 7406 final String pkgName = pkg.packageName; 7407 7408 final long scanFileTime = scanFile.lastModified(); 7409 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7410 pkg.applicationInfo.processName = fixProcessName( 7411 pkg.applicationInfo.packageName, 7412 pkg.applicationInfo.processName, 7413 pkg.applicationInfo.uid); 7414 7415 if (pkg != mPlatformPackage) { 7416 // Get all of our default paths setup 7417 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7418 } 7419 7420 final String path = scanFile.getPath(); 7421 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7422 7423 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7424 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7425 7426 // Some system apps still use directory structure for native libraries 7427 // in which case we might end up not detecting abi solely based on apk 7428 // structure. Try to detect abi based on directory structure. 7429 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7430 pkg.applicationInfo.primaryCpuAbi == null) { 7431 setBundledAppAbisAndRoots(pkg, pkgSetting); 7432 setNativeLibraryPaths(pkg); 7433 } 7434 7435 } else { 7436 if ((scanFlags & SCAN_MOVE) != 0) { 7437 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7438 // but we already have this packages package info in the PackageSetting. We just 7439 // use that and derive the native library path based on the new codepath. 7440 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7441 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7442 } 7443 7444 // Set native library paths again. For moves, the path will be updated based on the 7445 // ABIs we've determined above. For non-moves, the path will be updated based on the 7446 // ABIs we determined during compilation, but the path will depend on the final 7447 // package path (after the rename away from the stage path). 7448 setNativeLibraryPaths(pkg); 7449 } 7450 7451 // This is a special case for the "system" package, where the ABI is 7452 // dictated by the zygote configuration (and init.rc). We should keep track 7453 // of this ABI so that we can deal with "normal" applications that run under 7454 // the same UID correctly. 7455 if (mPlatformPackage == pkg) { 7456 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7457 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7458 } 7459 7460 // If there's a mismatch between the abi-override in the package setting 7461 // and the abiOverride specified for the install. Warn about this because we 7462 // would've already compiled the app without taking the package setting into 7463 // account. 7464 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7465 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7466 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7467 " for package " + pkg.packageName); 7468 } 7469 } 7470 7471 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7472 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7473 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7474 7475 // Copy the derived override back to the parsed package, so that we can 7476 // update the package settings accordingly. 7477 pkg.cpuAbiOverride = cpuAbiOverride; 7478 7479 if (DEBUG_ABI_SELECTION) { 7480 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7481 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7482 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7483 } 7484 7485 // Push the derived path down into PackageSettings so we know what to 7486 // clean up at uninstall time. 7487 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7488 7489 if (DEBUG_ABI_SELECTION) { 7490 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7491 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7492 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7493 } 7494 7495 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7496 // We don't do this here during boot because we can do it all 7497 // at once after scanning all existing packages. 7498 // 7499 // We also do this *before* we perform dexopt on this package, so that 7500 // we can avoid redundant dexopts, and also to make sure we've got the 7501 // code and package path correct. 7502 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7503 pkg, true /* boot complete */); 7504 } 7505 7506 if (mFactoryTest && pkg.requestedPermissions.contains( 7507 android.Manifest.permission.FACTORY_TEST)) { 7508 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7509 } 7510 7511 ArrayList<PackageParser.Package> clientLibPkgs = null; 7512 7513 // writer 7514 synchronized (mPackages) { 7515 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7516 // Only system apps can add new shared libraries. 7517 if (pkg.libraryNames != null) { 7518 for (int i=0; i<pkg.libraryNames.size(); i++) { 7519 String name = pkg.libraryNames.get(i); 7520 boolean allowed = false; 7521 if (pkg.isUpdatedSystemApp()) { 7522 // New library entries can only be added through the 7523 // system image. This is important to get rid of a lot 7524 // of nasty edge cases: for example if we allowed a non- 7525 // system update of the app to add a library, then uninstalling 7526 // the update would make the library go away, and assumptions 7527 // we made such as through app install filtering would now 7528 // have allowed apps on the device which aren't compatible 7529 // with it. Better to just have the restriction here, be 7530 // conservative, and create many fewer cases that can negatively 7531 // impact the user experience. 7532 final PackageSetting sysPs = mSettings 7533 .getDisabledSystemPkgLPr(pkg.packageName); 7534 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7535 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7536 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7537 allowed = true; 7538 break; 7539 } 7540 } 7541 } 7542 } else { 7543 allowed = true; 7544 } 7545 if (allowed) { 7546 if (!mSharedLibraries.containsKey(name)) { 7547 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7548 } else if (!name.equals(pkg.packageName)) { 7549 Slog.w(TAG, "Package " + pkg.packageName + " library " 7550 + name + " already exists; skipping"); 7551 } 7552 } else { 7553 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7554 + name + " that is not declared on system image; skipping"); 7555 } 7556 } 7557 if ((scanFlags & SCAN_BOOTING) == 0) { 7558 // If we are not booting, we need to update any applications 7559 // that are clients of our shared library. If we are booting, 7560 // this will all be done once the scan is complete. 7561 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7562 } 7563 } 7564 } 7565 } 7566 7567 // Request the ActivityManager to kill the process(only for existing packages) 7568 // so that we do not end up in a confused state while the user is still using the older 7569 // version of the application while the new one gets installed. 7570 if ((scanFlags & SCAN_REPLACING) != 0) { 7571 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7572 7573 killApplication(pkg.applicationInfo.packageName, 7574 pkg.applicationInfo.uid, "replace pkg"); 7575 7576 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7577 } 7578 7579 // Also need to kill any apps that are dependent on the library. 7580 if (clientLibPkgs != null) { 7581 for (int i=0; i<clientLibPkgs.size(); i++) { 7582 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7583 killApplication(clientPkg.applicationInfo.packageName, 7584 clientPkg.applicationInfo.uid, "update lib"); 7585 } 7586 } 7587 7588 // Make sure we're not adding any bogus keyset info 7589 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7590 ksms.assertScannedPackageValid(pkg); 7591 7592 // writer 7593 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7594 7595 boolean createIdmapFailed = false; 7596 synchronized (mPackages) { 7597 // We don't expect installation to fail beyond this point 7598 7599 // Add the new setting to mSettings 7600 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7601 // Add the new setting to mPackages 7602 mPackages.put(pkg.applicationInfo.packageName, pkg); 7603 // Make sure we don't accidentally delete its data. 7604 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7605 while (iter.hasNext()) { 7606 PackageCleanItem item = iter.next(); 7607 if (pkgName.equals(item.packageName)) { 7608 iter.remove(); 7609 } 7610 } 7611 7612 // Take care of first install / last update times. 7613 if (currentTime != 0) { 7614 if (pkgSetting.firstInstallTime == 0) { 7615 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7616 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7617 pkgSetting.lastUpdateTime = currentTime; 7618 } 7619 } else if (pkgSetting.firstInstallTime == 0) { 7620 // We need *something*. Take time time stamp of the file. 7621 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7622 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7623 if (scanFileTime != pkgSetting.timeStamp) { 7624 // A package on the system image has changed; consider this 7625 // to be an update. 7626 pkgSetting.lastUpdateTime = scanFileTime; 7627 } 7628 } 7629 7630 // Add the package's KeySets to the global KeySetManagerService 7631 ksms.addScannedPackageLPw(pkg); 7632 7633 int N = pkg.providers.size(); 7634 StringBuilder r = null; 7635 int i; 7636 for (i=0; i<N; i++) { 7637 PackageParser.Provider p = pkg.providers.get(i); 7638 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7639 p.info.processName, pkg.applicationInfo.uid); 7640 mProviders.addProvider(p); 7641 p.syncable = p.info.isSyncable; 7642 if (p.info.authority != null) { 7643 String names[] = p.info.authority.split(";"); 7644 p.info.authority = null; 7645 for (int j = 0; j < names.length; j++) { 7646 if (j == 1 && p.syncable) { 7647 // We only want the first authority for a provider to possibly be 7648 // syncable, so if we already added this provider using a different 7649 // authority clear the syncable flag. We copy the provider before 7650 // changing it because the mProviders object contains a reference 7651 // to a provider that we don't want to change. 7652 // Only do this for the second authority since the resulting provider 7653 // object can be the same for all future authorities for this provider. 7654 p = new PackageParser.Provider(p); 7655 p.syncable = false; 7656 } 7657 if (!mProvidersByAuthority.containsKey(names[j])) { 7658 mProvidersByAuthority.put(names[j], p); 7659 if (p.info.authority == null) { 7660 p.info.authority = names[j]; 7661 } else { 7662 p.info.authority = p.info.authority + ";" + names[j]; 7663 } 7664 if (DEBUG_PACKAGE_SCANNING) { 7665 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7666 Log.d(TAG, "Registered content provider: " + names[j] 7667 + ", className = " + p.info.name + ", isSyncable = " 7668 + p.info.isSyncable); 7669 } 7670 } else { 7671 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7672 Slog.w(TAG, "Skipping provider name " + names[j] + 7673 " (in package " + pkg.applicationInfo.packageName + 7674 "): name already used by " 7675 + ((other != null && other.getComponentName() != null) 7676 ? other.getComponentName().getPackageName() : "?")); 7677 } 7678 } 7679 } 7680 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7681 if (r == null) { 7682 r = new StringBuilder(256); 7683 } else { 7684 r.append(' '); 7685 } 7686 r.append(p.info.name); 7687 } 7688 } 7689 if (r != null) { 7690 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7691 } 7692 7693 N = pkg.services.size(); 7694 r = null; 7695 for (i=0; i<N; i++) { 7696 PackageParser.Service s = pkg.services.get(i); 7697 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7698 s.info.processName, pkg.applicationInfo.uid); 7699 mServices.addService(s); 7700 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7701 if (r == null) { 7702 r = new StringBuilder(256); 7703 } else { 7704 r.append(' '); 7705 } 7706 r.append(s.info.name); 7707 } 7708 } 7709 if (r != null) { 7710 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7711 } 7712 7713 N = pkg.receivers.size(); 7714 r = null; 7715 for (i=0; i<N; i++) { 7716 PackageParser.Activity a = pkg.receivers.get(i); 7717 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7718 a.info.processName, pkg.applicationInfo.uid); 7719 mReceivers.addActivity(a, "receiver"); 7720 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7721 if (r == null) { 7722 r = new StringBuilder(256); 7723 } else { 7724 r.append(' '); 7725 } 7726 r.append(a.info.name); 7727 } 7728 } 7729 if (r != null) { 7730 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7731 } 7732 7733 N = pkg.activities.size(); 7734 r = null; 7735 for (i=0; i<N; i++) { 7736 PackageParser.Activity a = pkg.activities.get(i); 7737 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7738 a.info.processName, pkg.applicationInfo.uid); 7739 mActivities.addActivity(a, "activity"); 7740 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7741 if (r == null) { 7742 r = new StringBuilder(256); 7743 } else { 7744 r.append(' '); 7745 } 7746 r.append(a.info.name); 7747 } 7748 } 7749 if (r != null) { 7750 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7751 } 7752 7753 N = pkg.permissionGroups.size(); 7754 r = null; 7755 for (i=0; i<N; i++) { 7756 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7757 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7758 if (cur == null) { 7759 mPermissionGroups.put(pg.info.name, pg); 7760 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7761 if (r == null) { 7762 r = new StringBuilder(256); 7763 } else { 7764 r.append(' '); 7765 } 7766 r.append(pg.info.name); 7767 } 7768 } else { 7769 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7770 + pg.info.packageName + " ignored: original from " 7771 + cur.info.packageName); 7772 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7773 if (r == null) { 7774 r = new StringBuilder(256); 7775 } else { 7776 r.append(' '); 7777 } 7778 r.append("DUP:"); 7779 r.append(pg.info.name); 7780 } 7781 } 7782 } 7783 if (r != null) { 7784 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7785 } 7786 7787 N = pkg.permissions.size(); 7788 r = null; 7789 for (i=0; i<N; i++) { 7790 PackageParser.Permission p = pkg.permissions.get(i); 7791 7792 // Assume by default that we did not install this permission into the system. 7793 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7794 7795 // Now that permission groups have a special meaning, we ignore permission 7796 // groups for legacy apps to prevent unexpected behavior. In particular, 7797 // permissions for one app being granted to someone just becuase they happen 7798 // to be in a group defined by another app (before this had no implications). 7799 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7800 p.group = mPermissionGroups.get(p.info.group); 7801 // Warn for a permission in an unknown group. 7802 if (p.info.group != null && p.group == null) { 7803 Slog.w(TAG, "Permission " + p.info.name + " from package " 7804 + p.info.packageName + " in an unknown group " + p.info.group); 7805 } 7806 } 7807 7808 ArrayMap<String, BasePermission> permissionMap = 7809 p.tree ? mSettings.mPermissionTrees 7810 : mSettings.mPermissions; 7811 BasePermission bp = permissionMap.get(p.info.name); 7812 7813 // Allow system apps to redefine non-system permissions 7814 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7815 final boolean currentOwnerIsSystem = (bp.perm != null 7816 && isSystemApp(bp.perm.owner)); 7817 if (isSystemApp(p.owner)) { 7818 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7819 // It's a built-in permission and no owner, take ownership now 7820 bp.packageSetting = pkgSetting; 7821 bp.perm = p; 7822 bp.uid = pkg.applicationInfo.uid; 7823 bp.sourcePackage = p.info.packageName; 7824 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7825 } else if (!currentOwnerIsSystem) { 7826 String msg = "New decl " + p.owner + " of permission " 7827 + p.info.name + " is system; overriding " + bp.sourcePackage; 7828 reportSettingsProblem(Log.WARN, msg); 7829 bp = null; 7830 } 7831 } 7832 } 7833 7834 if (bp == null) { 7835 bp = new BasePermission(p.info.name, p.info.packageName, 7836 BasePermission.TYPE_NORMAL); 7837 permissionMap.put(p.info.name, bp); 7838 } 7839 7840 if (bp.perm == null) { 7841 if (bp.sourcePackage == null 7842 || bp.sourcePackage.equals(p.info.packageName)) { 7843 BasePermission tree = findPermissionTreeLP(p.info.name); 7844 if (tree == null 7845 || tree.sourcePackage.equals(p.info.packageName)) { 7846 bp.packageSetting = pkgSetting; 7847 bp.perm = p; 7848 bp.uid = pkg.applicationInfo.uid; 7849 bp.sourcePackage = p.info.packageName; 7850 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7851 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7852 if (r == null) { 7853 r = new StringBuilder(256); 7854 } else { 7855 r.append(' '); 7856 } 7857 r.append(p.info.name); 7858 } 7859 } else { 7860 Slog.w(TAG, "Permission " + p.info.name + " from package " 7861 + p.info.packageName + " ignored: base tree " 7862 + tree.name + " is from package " 7863 + tree.sourcePackage); 7864 } 7865 } else { 7866 Slog.w(TAG, "Permission " + p.info.name + " from package " 7867 + p.info.packageName + " ignored: original from " 7868 + bp.sourcePackage); 7869 } 7870 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7871 if (r == null) { 7872 r = new StringBuilder(256); 7873 } else { 7874 r.append(' '); 7875 } 7876 r.append("DUP:"); 7877 r.append(p.info.name); 7878 } 7879 if (bp.perm == p) { 7880 bp.protectionLevel = p.info.protectionLevel; 7881 } 7882 } 7883 7884 if (r != null) { 7885 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7886 } 7887 7888 N = pkg.instrumentation.size(); 7889 r = null; 7890 for (i=0; i<N; i++) { 7891 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7892 a.info.packageName = pkg.applicationInfo.packageName; 7893 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7894 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7895 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7896 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7897 a.info.dataDir = pkg.applicationInfo.dataDir; 7898 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7899 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7900 7901 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7902 // need other information about the application, like the ABI and what not ? 7903 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7904 mInstrumentation.put(a.getComponentName(), a); 7905 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7906 if (r == null) { 7907 r = new StringBuilder(256); 7908 } else { 7909 r.append(' '); 7910 } 7911 r.append(a.info.name); 7912 } 7913 } 7914 if (r != null) { 7915 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7916 } 7917 7918 if (pkg.protectedBroadcasts != null) { 7919 N = pkg.protectedBroadcasts.size(); 7920 for (i=0; i<N; i++) { 7921 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7922 } 7923 } 7924 7925 pkgSetting.setTimeStamp(scanFileTime); 7926 7927 // Create idmap files for pairs of (packages, overlay packages). 7928 // Note: "android", ie framework-res.apk, is handled by native layers. 7929 if (pkg.mOverlayTarget != null) { 7930 // This is an overlay package. 7931 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7932 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7933 mOverlays.put(pkg.mOverlayTarget, 7934 new ArrayMap<String, PackageParser.Package>()); 7935 } 7936 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7937 map.put(pkg.packageName, pkg); 7938 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7939 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7940 createIdmapFailed = true; 7941 } 7942 } 7943 } else if (mOverlays.containsKey(pkg.packageName) && 7944 !pkg.packageName.equals("android")) { 7945 // This is a regular package, with one or more known overlay packages. 7946 createIdmapsForPackageLI(pkg); 7947 } 7948 } 7949 7950 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7951 7952 if (createIdmapFailed) { 7953 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7954 "scanPackageLI failed to createIdmap"); 7955 } 7956 return pkg; 7957 } 7958 7959 /** 7960 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7961 * is derived purely on the basis of the contents of {@code scanFile} and 7962 * {@code cpuAbiOverride}. 7963 * 7964 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7965 */ 7966 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7967 String cpuAbiOverride, boolean extractLibs) 7968 throws PackageManagerException { 7969 // TODO: We can probably be smarter about this stuff. For installed apps, 7970 // we can calculate this information at install time once and for all. For 7971 // system apps, we can probably assume that this information doesn't change 7972 // after the first boot scan. As things stand, we do lots of unnecessary work. 7973 7974 // Give ourselves some initial paths; we'll come back for another 7975 // pass once we've determined ABI below. 7976 setNativeLibraryPaths(pkg); 7977 7978 // We would never need to extract libs for forward-locked and external packages, 7979 // since the container service will do it for us. We shouldn't attempt to 7980 // extract libs from system app when it was not updated. 7981 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7982 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7983 extractLibs = false; 7984 } 7985 7986 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7987 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7988 7989 NativeLibraryHelper.Handle handle = null; 7990 try { 7991 handle = NativeLibraryHelper.Handle.create(pkg); 7992 // TODO(multiArch): This can be null for apps that didn't go through the 7993 // usual installation process. We can calculate it again, like we 7994 // do during install time. 7995 // 7996 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7997 // unnecessary. 7998 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7999 8000 // Null out the abis so that they can be recalculated. 8001 pkg.applicationInfo.primaryCpuAbi = null; 8002 pkg.applicationInfo.secondaryCpuAbi = null; 8003 if (isMultiArch(pkg.applicationInfo)) { 8004 // Warn if we've set an abiOverride for multi-lib packages.. 8005 // By definition, we need to copy both 32 and 64 bit libraries for 8006 // such packages. 8007 if (pkg.cpuAbiOverride != null 8008 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8009 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8010 } 8011 8012 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8013 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8014 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8015 if (extractLibs) { 8016 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8017 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8018 useIsaSpecificSubdirs); 8019 } else { 8020 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8021 } 8022 } 8023 8024 maybeThrowExceptionForMultiArchCopy( 8025 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8026 8027 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8028 if (extractLibs) { 8029 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8030 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8031 useIsaSpecificSubdirs); 8032 } else { 8033 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8034 } 8035 } 8036 8037 maybeThrowExceptionForMultiArchCopy( 8038 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8039 8040 if (abi64 >= 0) { 8041 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8042 } 8043 8044 if (abi32 >= 0) { 8045 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8046 if (abi64 >= 0) { 8047 pkg.applicationInfo.secondaryCpuAbi = abi; 8048 } else { 8049 pkg.applicationInfo.primaryCpuAbi = abi; 8050 } 8051 } 8052 } else { 8053 String[] abiList = (cpuAbiOverride != null) ? 8054 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8055 8056 // Enable gross and lame hacks for apps that are built with old 8057 // SDK tools. We must scan their APKs for renderscript bitcode and 8058 // not launch them if it's present. Don't bother checking on devices 8059 // that don't have 64 bit support. 8060 boolean needsRenderScriptOverride = false; 8061 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8062 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8063 abiList = Build.SUPPORTED_32_BIT_ABIS; 8064 needsRenderScriptOverride = true; 8065 } 8066 8067 final int copyRet; 8068 if (extractLibs) { 8069 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8070 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8071 } else { 8072 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8073 } 8074 8075 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8076 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8077 "Error unpackaging native libs for app, errorCode=" + copyRet); 8078 } 8079 8080 if (copyRet >= 0) { 8081 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8082 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8083 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8084 } else if (needsRenderScriptOverride) { 8085 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8086 } 8087 } 8088 } catch (IOException ioe) { 8089 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8090 } finally { 8091 IoUtils.closeQuietly(handle); 8092 } 8093 8094 // Now that we've calculated the ABIs and determined if it's an internal app, 8095 // we will go ahead and populate the nativeLibraryPath. 8096 setNativeLibraryPaths(pkg); 8097 } 8098 8099 /** 8100 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8101 * i.e, so that all packages can be run inside a single process if required. 8102 * 8103 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8104 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8105 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8106 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8107 * updating a package that belongs to a shared user. 8108 * 8109 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8110 * adds unnecessary complexity. 8111 */ 8112 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8113 PackageParser.Package scannedPackage, boolean bootComplete) { 8114 String requiredInstructionSet = null; 8115 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8116 requiredInstructionSet = VMRuntime.getInstructionSet( 8117 scannedPackage.applicationInfo.primaryCpuAbi); 8118 } 8119 8120 PackageSetting requirer = null; 8121 for (PackageSetting ps : packagesForUser) { 8122 // If packagesForUser contains scannedPackage, we skip it. This will happen 8123 // when scannedPackage is an update of an existing package. Without this check, 8124 // we will never be able to change the ABI of any package belonging to a shared 8125 // user, even if it's compatible with other packages. 8126 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8127 if (ps.primaryCpuAbiString == null) { 8128 continue; 8129 } 8130 8131 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8132 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8133 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8134 // this but there's not much we can do. 8135 String errorMessage = "Instruction set mismatch, " 8136 + ((requirer == null) ? "[caller]" : requirer) 8137 + " requires " + requiredInstructionSet + " whereas " + ps 8138 + " requires " + instructionSet; 8139 Slog.w(TAG, errorMessage); 8140 } 8141 8142 if (requiredInstructionSet == null) { 8143 requiredInstructionSet = instructionSet; 8144 requirer = ps; 8145 } 8146 } 8147 } 8148 8149 if (requiredInstructionSet != null) { 8150 String adjustedAbi; 8151 if (requirer != null) { 8152 // requirer != null implies that either scannedPackage was null or that scannedPackage 8153 // did not require an ABI, in which case we have to adjust scannedPackage to match 8154 // the ABI of the set (which is the same as requirer's ABI) 8155 adjustedAbi = requirer.primaryCpuAbiString; 8156 if (scannedPackage != null) { 8157 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8158 } 8159 } else { 8160 // requirer == null implies that we're updating all ABIs in the set to 8161 // match scannedPackage. 8162 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8163 } 8164 8165 for (PackageSetting ps : packagesForUser) { 8166 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8167 if (ps.primaryCpuAbiString != null) { 8168 continue; 8169 } 8170 8171 ps.primaryCpuAbiString = adjustedAbi; 8172 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8173 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8174 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8175 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8176 + " (requirer=" 8177 + (requirer == null ? "null" : requirer.pkg.packageName) 8178 + ", scannedPackage=" 8179 + (scannedPackage != null ? scannedPackage.packageName : "null") 8180 + ")"); 8181 try { 8182 mInstaller.rmdex(ps.codePathString, 8183 getDexCodeInstructionSet(getPreferredInstructionSet())); 8184 } catch (InstallerException ignored) { 8185 } 8186 } 8187 } 8188 } 8189 } 8190 } 8191 8192 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8193 synchronized (mPackages) { 8194 mResolverReplaced = true; 8195 // Set up information for custom user intent resolution activity. 8196 mResolveActivity.applicationInfo = pkg.applicationInfo; 8197 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8198 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8199 mResolveActivity.processName = pkg.applicationInfo.packageName; 8200 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8201 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8202 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8203 mResolveActivity.theme = 0; 8204 mResolveActivity.exported = true; 8205 mResolveActivity.enabled = true; 8206 mResolveInfo.activityInfo = mResolveActivity; 8207 mResolveInfo.priority = 0; 8208 mResolveInfo.preferredOrder = 0; 8209 mResolveInfo.match = 0; 8210 mResolveComponentName = mCustomResolverComponentName; 8211 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8212 mResolveComponentName); 8213 } 8214 } 8215 8216 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8217 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8218 8219 // Set up information for ephemeral installer activity 8220 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8221 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8222 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8223 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8224 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8225 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8226 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8227 mEphemeralInstallerActivity.theme = 0; 8228 mEphemeralInstallerActivity.exported = true; 8229 mEphemeralInstallerActivity.enabled = true; 8230 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8231 mEphemeralInstallerInfo.priority = 0; 8232 mEphemeralInstallerInfo.preferredOrder = 0; 8233 mEphemeralInstallerInfo.match = 0; 8234 8235 if (DEBUG_EPHEMERAL) { 8236 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8237 } 8238 } 8239 8240 private static String calculateBundledApkRoot(final String codePathString) { 8241 final File codePath = new File(codePathString); 8242 final File codeRoot; 8243 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8244 codeRoot = Environment.getRootDirectory(); 8245 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8246 codeRoot = Environment.getOemDirectory(); 8247 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8248 codeRoot = Environment.getVendorDirectory(); 8249 } else { 8250 // Unrecognized code path; take its top real segment as the apk root: 8251 // e.g. /something/app/blah.apk => /something 8252 try { 8253 File f = codePath.getCanonicalFile(); 8254 File parent = f.getParentFile(); // non-null because codePath is a file 8255 File tmp; 8256 while ((tmp = parent.getParentFile()) != null) { 8257 f = parent; 8258 parent = tmp; 8259 } 8260 codeRoot = f; 8261 Slog.w(TAG, "Unrecognized code path " 8262 + codePath + " - using " + codeRoot); 8263 } catch (IOException e) { 8264 // Can't canonicalize the code path -- shenanigans? 8265 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8266 return Environment.getRootDirectory().getPath(); 8267 } 8268 } 8269 return codeRoot.getPath(); 8270 } 8271 8272 /** 8273 * Derive and set the location of native libraries for the given package, 8274 * which varies depending on where and how the package was installed. 8275 */ 8276 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8277 final ApplicationInfo info = pkg.applicationInfo; 8278 final String codePath = pkg.codePath; 8279 final File codeFile = new File(codePath); 8280 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8281 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8282 8283 info.nativeLibraryRootDir = null; 8284 info.nativeLibraryRootRequiresIsa = false; 8285 info.nativeLibraryDir = null; 8286 info.secondaryNativeLibraryDir = null; 8287 8288 if (isApkFile(codeFile)) { 8289 // Monolithic install 8290 if (bundledApp) { 8291 // If "/system/lib64/apkname" exists, assume that is the per-package 8292 // native library directory to use; otherwise use "/system/lib/apkname". 8293 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8294 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8295 getPrimaryInstructionSet(info)); 8296 8297 // This is a bundled system app so choose the path based on the ABI. 8298 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8299 // is just the default path. 8300 final String apkName = deriveCodePathName(codePath); 8301 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8302 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8303 apkName).getAbsolutePath(); 8304 8305 if (info.secondaryCpuAbi != null) { 8306 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8307 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8308 secondaryLibDir, apkName).getAbsolutePath(); 8309 } 8310 } else if (asecApp) { 8311 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8312 .getAbsolutePath(); 8313 } else { 8314 final String apkName = deriveCodePathName(codePath); 8315 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8316 .getAbsolutePath(); 8317 } 8318 8319 info.nativeLibraryRootRequiresIsa = false; 8320 info.nativeLibraryDir = info.nativeLibraryRootDir; 8321 } else { 8322 // Cluster install 8323 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8324 info.nativeLibraryRootRequiresIsa = true; 8325 8326 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8327 getPrimaryInstructionSet(info)).getAbsolutePath(); 8328 8329 if (info.secondaryCpuAbi != null) { 8330 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8331 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8332 } 8333 } 8334 } 8335 8336 /** 8337 * Calculate the abis and roots for a bundled app. These can uniquely 8338 * be determined from the contents of the system partition, i.e whether 8339 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8340 * of this information, and instead assume that the system was built 8341 * sensibly. 8342 */ 8343 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8344 PackageSetting pkgSetting) { 8345 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8346 8347 // If "/system/lib64/apkname" exists, assume that is the per-package 8348 // native library directory to use; otherwise use "/system/lib/apkname". 8349 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8350 setBundledAppAbi(pkg, apkRoot, apkName); 8351 // pkgSetting might be null during rescan following uninstall of updates 8352 // to a bundled app, so accommodate that possibility. The settings in 8353 // that case will be established later from the parsed package. 8354 // 8355 // If the settings aren't null, sync them up with what we've just derived. 8356 // note that apkRoot isn't stored in the package settings. 8357 if (pkgSetting != null) { 8358 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8359 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8360 } 8361 } 8362 8363 /** 8364 * Deduces the ABI of a bundled app and sets the relevant fields on the 8365 * parsed pkg object. 8366 * 8367 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8368 * under which system libraries are installed. 8369 * @param apkName the name of the installed package. 8370 */ 8371 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8372 final File codeFile = new File(pkg.codePath); 8373 8374 final boolean has64BitLibs; 8375 final boolean has32BitLibs; 8376 if (isApkFile(codeFile)) { 8377 // Monolithic install 8378 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8379 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8380 } else { 8381 // Cluster install 8382 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8383 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8384 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8385 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8386 has64BitLibs = (new File(rootDir, isa)).exists(); 8387 } else { 8388 has64BitLibs = false; 8389 } 8390 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8391 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8392 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8393 has32BitLibs = (new File(rootDir, isa)).exists(); 8394 } else { 8395 has32BitLibs = false; 8396 } 8397 } 8398 8399 if (has64BitLibs && !has32BitLibs) { 8400 // The package has 64 bit libs, but not 32 bit libs. Its primary 8401 // ABI should be 64 bit. We can safely assume here that the bundled 8402 // native libraries correspond to the most preferred ABI in the list. 8403 8404 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8405 pkg.applicationInfo.secondaryCpuAbi = null; 8406 } else if (has32BitLibs && !has64BitLibs) { 8407 // The package has 32 bit libs but not 64 bit libs. Its primary 8408 // ABI should be 32 bit. 8409 8410 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8411 pkg.applicationInfo.secondaryCpuAbi = null; 8412 } else if (has32BitLibs && has64BitLibs) { 8413 // The application has both 64 and 32 bit bundled libraries. We check 8414 // here that the app declares multiArch support, and warn if it doesn't. 8415 // 8416 // We will be lenient here and record both ABIs. The primary will be the 8417 // ABI that's higher on the list, i.e, a device that's configured to prefer 8418 // 64 bit apps will see a 64 bit primary ABI, 8419 8420 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8421 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8422 } 8423 8424 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8425 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8426 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8427 } else { 8428 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8429 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8430 } 8431 } else { 8432 pkg.applicationInfo.primaryCpuAbi = null; 8433 pkg.applicationInfo.secondaryCpuAbi = null; 8434 } 8435 } 8436 8437 private void killApplication(String pkgName, int appId, String reason) { 8438 // Request the ActivityManager to kill the process(only for existing packages) 8439 // so that we do not end up in a confused state while the user is still using the older 8440 // version of the application while the new one gets installed. 8441 IActivityManager am = ActivityManagerNative.getDefault(); 8442 if (am != null) { 8443 try { 8444 am.killApplicationWithAppId(pkgName, appId, reason); 8445 } catch (RemoteException e) { 8446 } 8447 } 8448 } 8449 8450 void removePackageLI(PackageSetting ps, boolean chatty) { 8451 if (DEBUG_INSTALL) { 8452 if (chatty) 8453 Log.d(TAG, "Removing package " + ps.name); 8454 } 8455 8456 // writer 8457 synchronized (mPackages) { 8458 mPackages.remove(ps.name); 8459 final PackageParser.Package pkg = ps.pkg; 8460 if (pkg != null) { 8461 cleanPackageDataStructuresLILPw(pkg, chatty); 8462 } 8463 } 8464 } 8465 8466 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8467 if (DEBUG_INSTALL) { 8468 if (chatty) 8469 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8470 } 8471 8472 // writer 8473 synchronized (mPackages) { 8474 mPackages.remove(pkg.applicationInfo.packageName); 8475 cleanPackageDataStructuresLILPw(pkg, chatty); 8476 } 8477 } 8478 8479 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8480 int N = pkg.providers.size(); 8481 StringBuilder r = null; 8482 int i; 8483 for (i=0; i<N; i++) { 8484 PackageParser.Provider p = pkg.providers.get(i); 8485 mProviders.removeProvider(p); 8486 if (p.info.authority == null) { 8487 8488 /* There was another ContentProvider with this authority when 8489 * this app was installed so this authority is null, 8490 * Ignore it as we don't have to unregister the provider. 8491 */ 8492 continue; 8493 } 8494 String names[] = p.info.authority.split(";"); 8495 for (int j = 0; j < names.length; j++) { 8496 if (mProvidersByAuthority.get(names[j]) == p) { 8497 mProvidersByAuthority.remove(names[j]); 8498 if (DEBUG_REMOVE) { 8499 if (chatty) 8500 Log.d(TAG, "Unregistered content provider: " + names[j] 8501 + ", className = " + p.info.name + ", isSyncable = " 8502 + p.info.isSyncable); 8503 } 8504 } 8505 } 8506 if (DEBUG_REMOVE && chatty) { 8507 if (r == null) { 8508 r = new StringBuilder(256); 8509 } else { 8510 r.append(' '); 8511 } 8512 r.append(p.info.name); 8513 } 8514 } 8515 if (r != null) { 8516 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8517 } 8518 8519 N = pkg.services.size(); 8520 r = null; 8521 for (i=0; i<N; i++) { 8522 PackageParser.Service s = pkg.services.get(i); 8523 mServices.removeService(s); 8524 if (chatty) { 8525 if (r == null) { 8526 r = new StringBuilder(256); 8527 } else { 8528 r.append(' '); 8529 } 8530 r.append(s.info.name); 8531 } 8532 } 8533 if (r != null) { 8534 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8535 } 8536 8537 N = pkg.receivers.size(); 8538 r = null; 8539 for (i=0; i<N; i++) { 8540 PackageParser.Activity a = pkg.receivers.get(i); 8541 mReceivers.removeActivity(a, "receiver"); 8542 if (DEBUG_REMOVE && chatty) { 8543 if (r == null) { 8544 r = new StringBuilder(256); 8545 } else { 8546 r.append(' '); 8547 } 8548 r.append(a.info.name); 8549 } 8550 } 8551 if (r != null) { 8552 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8553 } 8554 8555 N = pkg.activities.size(); 8556 r = null; 8557 for (i=0; i<N; i++) { 8558 PackageParser.Activity a = pkg.activities.get(i); 8559 mActivities.removeActivity(a, "activity"); 8560 if (DEBUG_REMOVE && chatty) { 8561 if (r == null) { 8562 r = new StringBuilder(256); 8563 } else { 8564 r.append(' '); 8565 } 8566 r.append(a.info.name); 8567 } 8568 } 8569 if (r != null) { 8570 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8571 } 8572 8573 N = pkg.permissions.size(); 8574 r = null; 8575 for (i=0; i<N; i++) { 8576 PackageParser.Permission p = pkg.permissions.get(i); 8577 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8578 if (bp == null) { 8579 bp = mSettings.mPermissionTrees.get(p.info.name); 8580 } 8581 if (bp != null && bp.perm == p) { 8582 bp.perm = null; 8583 if (DEBUG_REMOVE && chatty) { 8584 if (r == null) { 8585 r = new StringBuilder(256); 8586 } else { 8587 r.append(' '); 8588 } 8589 r.append(p.info.name); 8590 } 8591 } 8592 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8593 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8594 if (appOpPkgs != null) { 8595 appOpPkgs.remove(pkg.packageName); 8596 } 8597 } 8598 } 8599 if (r != null) { 8600 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8601 } 8602 8603 N = pkg.requestedPermissions.size(); 8604 r = null; 8605 for (i=0; i<N; i++) { 8606 String perm = pkg.requestedPermissions.get(i); 8607 BasePermission bp = mSettings.mPermissions.get(perm); 8608 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8609 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8610 if (appOpPkgs != null) { 8611 appOpPkgs.remove(pkg.packageName); 8612 if (appOpPkgs.isEmpty()) { 8613 mAppOpPermissionPackages.remove(perm); 8614 } 8615 } 8616 } 8617 } 8618 if (r != null) { 8619 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8620 } 8621 8622 N = pkg.instrumentation.size(); 8623 r = null; 8624 for (i=0; i<N; i++) { 8625 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8626 mInstrumentation.remove(a.getComponentName()); 8627 if (DEBUG_REMOVE && chatty) { 8628 if (r == null) { 8629 r = new StringBuilder(256); 8630 } else { 8631 r.append(' '); 8632 } 8633 r.append(a.info.name); 8634 } 8635 } 8636 if (r != null) { 8637 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8638 } 8639 8640 r = null; 8641 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8642 // Only system apps can hold shared libraries. 8643 if (pkg.libraryNames != null) { 8644 for (i=0; i<pkg.libraryNames.size(); i++) { 8645 String name = pkg.libraryNames.get(i); 8646 SharedLibraryEntry cur = mSharedLibraries.get(name); 8647 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8648 mSharedLibraries.remove(name); 8649 if (DEBUG_REMOVE && chatty) { 8650 if (r == null) { 8651 r = new StringBuilder(256); 8652 } else { 8653 r.append(' '); 8654 } 8655 r.append(name); 8656 } 8657 } 8658 } 8659 } 8660 } 8661 if (r != null) { 8662 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8663 } 8664 } 8665 8666 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8667 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8668 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8669 return true; 8670 } 8671 } 8672 return false; 8673 } 8674 8675 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8676 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8677 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8678 8679 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8680 int flags) { 8681 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8682 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8683 } 8684 8685 private void updatePermissionsLPw(String changingPkg, 8686 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8687 // Make sure there are no dangling permission trees. 8688 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8689 while (it.hasNext()) { 8690 final BasePermission bp = it.next(); 8691 if (bp.packageSetting == null) { 8692 // We may not yet have parsed the package, so just see if 8693 // we still know about its settings. 8694 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8695 } 8696 if (bp.packageSetting == null) { 8697 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8698 + " from package " + bp.sourcePackage); 8699 it.remove(); 8700 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8701 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8702 Slog.i(TAG, "Removing old permission tree: " + bp.name 8703 + " from package " + bp.sourcePackage); 8704 flags |= UPDATE_PERMISSIONS_ALL; 8705 it.remove(); 8706 } 8707 } 8708 } 8709 8710 // Make sure all dynamic permissions have been assigned to a package, 8711 // and make sure there are no dangling permissions. 8712 it = mSettings.mPermissions.values().iterator(); 8713 while (it.hasNext()) { 8714 final BasePermission bp = it.next(); 8715 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8716 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8717 + bp.name + " pkg=" + bp.sourcePackage 8718 + " info=" + bp.pendingInfo); 8719 if (bp.packageSetting == null && bp.pendingInfo != null) { 8720 final BasePermission tree = findPermissionTreeLP(bp.name); 8721 if (tree != null && tree.perm != null) { 8722 bp.packageSetting = tree.packageSetting; 8723 bp.perm = new PackageParser.Permission(tree.perm.owner, 8724 new PermissionInfo(bp.pendingInfo)); 8725 bp.perm.info.packageName = tree.perm.info.packageName; 8726 bp.perm.info.name = bp.name; 8727 bp.uid = tree.uid; 8728 } 8729 } 8730 } 8731 if (bp.packageSetting == null) { 8732 // We may not yet have parsed the package, so just see if 8733 // we still know about its settings. 8734 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8735 } 8736 if (bp.packageSetting == null) { 8737 Slog.w(TAG, "Removing dangling permission: " + bp.name 8738 + " from package " + bp.sourcePackage); 8739 it.remove(); 8740 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8741 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8742 Slog.i(TAG, "Removing old permission: " + bp.name 8743 + " from package " + bp.sourcePackage); 8744 flags |= UPDATE_PERMISSIONS_ALL; 8745 it.remove(); 8746 } 8747 } 8748 } 8749 8750 // Now update the permissions for all packages, in particular 8751 // replace the granted permissions of the system packages. 8752 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8753 for (PackageParser.Package pkg : mPackages.values()) { 8754 if (pkg != pkgInfo) { 8755 // Only replace for packages on requested volume 8756 final String volumeUuid = getVolumeUuidForPackage(pkg); 8757 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8758 && Objects.equals(replaceVolumeUuid, volumeUuid); 8759 grantPermissionsLPw(pkg, replace, changingPkg); 8760 } 8761 } 8762 } 8763 8764 if (pkgInfo != null) { 8765 // Only replace for packages on requested volume 8766 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8767 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8768 && Objects.equals(replaceVolumeUuid, volumeUuid); 8769 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8770 } 8771 } 8772 8773 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8774 String packageOfInterest) { 8775 // IMPORTANT: There are two types of permissions: install and runtime. 8776 // Install time permissions are granted when the app is installed to 8777 // all device users and users added in the future. Runtime permissions 8778 // are granted at runtime explicitly to specific users. Normal and signature 8779 // protected permissions are install time permissions. Dangerous permissions 8780 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8781 // otherwise they are runtime permissions. This function does not manage 8782 // runtime permissions except for the case an app targeting Lollipop MR1 8783 // being upgraded to target a newer SDK, in which case dangerous permissions 8784 // are transformed from install time to runtime ones. 8785 8786 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8787 if (ps == null) { 8788 return; 8789 } 8790 8791 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8792 8793 PermissionsState permissionsState = ps.getPermissionsState(); 8794 PermissionsState origPermissions = permissionsState; 8795 8796 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8797 8798 boolean runtimePermissionsRevoked = false; 8799 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8800 8801 boolean changedInstallPermission = false; 8802 8803 if (replace) { 8804 ps.installPermissionsFixed = false; 8805 if (!ps.isSharedUser()) { 8806 origPermissions = new PermissionsState(permissionsState); 8807 permissionsState.reset(); 8808 } else { 8809 // We need to know only about runtime permission changes since the 8810 // calling code always writes the install permissions state but 8811 // the runtime ones are written only if changed. The only cases of 8812 // changed runtime permissions here are promotion of an install to 8813 // runtime and revocation of a runtime from a shared user. 8814 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8815 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8816 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8817 runtimePermissionsRevoked = true; 8818 } 8819 } 8820 } 8821 8822 permissionsState.setGlobalGids(mGlobalGids); 8823 8824 final int N = pkg.requestedPermissions.size(); 8825 for (int i=0; i<N; i++) { 8826 final String name = pkg.requestedPermissions.get(i); 8827 final BasePermission bp = mSettings.mPermissions.get(name); 8828 8829 if (DEBUG_INSTALL) { 8830 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8831 } 8832 8833 if (bp == null || bp.packageSetting == null) { 8834 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8835 Slog.w(TAG, "Unknown permission " + name 8836 + " in package " + pkg.packageName); 8837 } 8838 continue; 8839 } 8840 8841 final String perm = bp.name; 8842 boolean allowedSig = false; 8843 int grant = GRANT_DENIED; 8844 8845 // Keep track of app op permissions. 8846 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8847 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8848 if (pkgs == null) { 8849 pkgs = new ArraySet<>(); 8850 mAppOpPermissionPackages.put(bp.name, pkgs); 8851 } 8852 pkgs.add(pkg.packageName); 8853 } 8854 8855 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8856 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 8857 >= Build.VERSION_CODES.M; 8858 switch (level) { 8859 case PermissionInfo.PROTECTION_NORMAL: { 8860 // For all apps normal permissions are install time ones. 8861 grant = GRANT_INSTALL; 8862 } break; 8863 8864 case PermissionInfo.PROTECTION_DANGEROUS: { 8865 // If a permission review is required for legacy apps we represent 8866 // their permissions as always granted runtime ones since we need 8867 // to keep the review required permission flag per user while an 8868 // install permission's state is shared across all users. 8869 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 8870 // For legacy apps dangerous permissions are install time ones. 8871 grant = GRANT_INSTALL; 8872 } else if (origPermissions.hasInstallPermission(bp.name)) { 8873 // For legacy apps that became modern, install becomes runtime. 8874 grant = GRANT_UPGRADE; 8875 } else if (mPromoteSystemApps 8876 && isSystemApp(ps) 8877 && mExistingSystemPackages.contains(ps.name)) { 8878 // For legacy system apps, install becomes runtime. 8879 // We cannot check hasInstallPermission() for system apps since those 8880 // permissions were granted implicitly and not persisted pre-M. 8881 grant = GRANT_UPGRADE; 8882 } else { 8883 // For modern apps keep runtime permissions unchanged. 8884 grant = GRANT_RUNTIME; 8885 } 8886 } break; 8887 8888 case PermissionInfo.PROTECTION_SIGNATURE: { 8889 // For all apps signature permissions are install time ones. 8890 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8891 if (allowedSig) { 8892 grant = GRANT_INSTALL; 8893 } 8894 } break; 8895 } 8896 8897 if (DEBUG_INSTALL) { 8898 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8899 } 8900 8901 if (grant != GRANT_DENIED) { 8902 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8903 // If this is an existing, non-system package, then 8904 // we can't add any new permissions to it. 8905 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8906 // Except... if this is a permission that was added 8907 // to the platform (note: need to only do this when 8908 // updating the platform). 8909 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8910 grant = GRANT_DENIED; 8911 } 8912 } 8913 } 8914 8915 switch (grant) { 8916 case GRANT_INSTALL: { 8917 // Revoke this as runtime permission to handle the case of 8918 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 8919 for (int userId : UserManagerService.getInstance().getUserIds()) { 8920 if (origPermissions.getRuntimePermissionState( 8921 bp.name, userId) != null) { 8922 // Revoke the runtime permission and clear the flags. 8923 origPermissions.revokeRuntimePermission(bp, userId); 8924 origPermissions.updatePermissionFlags(bp, userId, 8925 PackageManager.MASK_PERMISSION_FLAGS, 0); 8926 // If we revoked a permission permission, we have to write. 8927 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8928 changedRuntimePermissionUserIds, userId); 8929 } 8930 } 8931 // Grant an install permission. 8932 if (permissionsState.grantInstallPermission(bp) != 8933 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8934 changedInstallPermission = true; 8935 } 8936 } break; 8937 8938 case GRANT_RUNTIME: { 8939 // Grant previously granted runtime permissions. 8940 for (int userId : UserManagerService.getInstance().getUserIds()) { 8941 PermissionState permissionState = origPermissions 8942 .getRuntimePermissionState(bp.name, userId); 8943 int flags = permissionState != null 8944 ? permissionState.getFlags() : 0; 8945 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8946 if (permissionsState.grantRuntimePermission(bp, userId) == 8947 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8948 // If we cannot put the permission as it was, we have to write. 8949 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8950 changedRuntimePermissionUserIds, userId); 8951 } 8952 // If the app supports runtime permissions no need for a review. 8953 if (Build.PERMISSIONS_REVIEW_REQUIRED 8954 && appSupportsRuntimePermissions 8955 && (flags & PackageManager 8956 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 8957 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 8958 // Since we changed the flags, we have to write. 8959 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8960 changedRuntimePermissionUserIds, userId); 8961 } 8962 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 8963 && !appSupportsRuntimePermissions) { 8964 // For legacy apps that need a permission review, every new 8965 // runtime permission is granted but it is pending a review. 8966 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 8967 permissionsState.grantRuntimePermission(bp, userId); 8968 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 8969 // We changed the permission and flags, hence have to write. 8970 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8971 changedRuntimePermissionUserIds, userId); 8972 } 8973 } 8974 // Propagate the permission flags. 8975 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8976 } 8977 } break; 8978 8979 case GRANT_UPGRADE: { 8980 // Grant runtime permissions for a previously held install permission. 8981 PermissionState permissionState = origPermissions 8982 .getInstallPermissionState(bp.name); 8983 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8984 8985 if (origPermissions.revokeInstallPermission(bp) 8986 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8987 // We will be transferring the permission flags, so clear them. 8988 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8989 PackageManager.MASK_PERMISSION_FLAGS, 0); 8990 changedInstallPermission = true; 8991 } 8992 8993 // If the permission is not to be promoted to runtime we ignore it and 8994 // also its other flags as they are not applicable to install permissions. 8995 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8996 for (int userId : currentUserIds) { 8997 if (permissionsState.grantRuntimePermission(bp, userId) != 8998 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8999 // Transfer the permission flags. 9000 permissionsState.updatePermissionFlags(bp, userId, 9001 flags, flags); 9002 // If we granted the permission, we have to write. 9003 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9004 changedRuntimePermissionUserIds, userId); 9005 } 9006 } 9007 } 9008 } break; 9009 9010 default: { 9011 if (packageOfInterest == null 9012 || packageOfInterest.equals(pkg.packageName)) { 9013 Slog.w(TAG, "Not granting permission " + perm 9014 + " to package " + pkg.packageName 9015 + " because it was previously installed without"); 9016 } 9017 } break; 9018 } 9019 } else { 9020 if (permissionsState.revokeInstallPermission(bp) != 9021 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9022 // Also drop the permission flags. 9023 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9024 PackageManager.MASK_PERMISSION_FLAGS, 0); 9025 changedInstallPermission = true; 9026 Slog.i(TAG, "Un-granting permission " + perm 9027 + " from package " + pkg.packageName 9028 + " (protectionLevel=" + bp.protectionLevel 9029 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9030 + ")"); 9031 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9032 // Don't print warning for app op permissions, since it is fine for them 9033 // not to be granted, there is a UI for the user to decide. 9034 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9035 Slog.w(TAG, "Not granting permission " + perm 9036 + " to package " + pkg.packageName 9037 + " (protectionLevel=" + bp.protectionLevel 9038 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9039 + ")"); 9040 } 9041 } 9042 } 9043 } 9044 9045 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9046 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9047 // This is the first that we have heard about this package, so the 9048 // permissions we have now selected are fixed until explicitly 9049 // changed. 9050 ps.installPermissionsFixed = true; 9051 } 9052 9053 // Persist the runtime permissions state for users with changes. If permissions 9054 // were revoked because no app in the shared user declares them we have to 9055 // write synchronously to avoid losing runtime permissions state. 9056 for (int userId : changedRuntimePermissionUserIds) { 9057 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9058 } 9059 9060 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9061 } 9062 9063 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9064 boolean allowed = false; 9065 final int NP = PackageParser.NEW_PERMISSIONS.length; 9066 for (int ip=0; ip<NP; ip++) { 9067 final PackageParser.NewPermissionInfo npi 9068 = PackageParser.NEW_PERMISSIONS[ip]; 9069 if (npi.name.equals(perm) 9070 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9071 allowed = true; 9072 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9073 + pkg.packageName); 9074 break; 9075 } 9076 } 9077 return allowed; 9078 } 9079 9080 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9081 BasePermission bp, PermissionsState origPermissions) { 9082 boolean allowed; 9083 allowed = (compareSignatures( 9084 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9085 == PackageManager.SIGNATURE_MATCH) 9086 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9087 == PackageManager.SIGNATURE_MATCH); 9088 if (!allowed && (bp.protectionLevel 9089 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9090 if (isSystemApp(pkg)) { 9091 // For updated system applications, a system permission 9092 // is granted only if it had been defined by the original application. 9093 if (pkg.isUpdatedSystemApp()) { 9094 final PackageSetting sysPs = mSettings 9095 .getDisabledSystemPkgLPr(pkg.packageName); 9096 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 9097 // If the original was granted this permission, we take 9098 // that grant decision as read and propagate it to the 9099 // update. 9100 if (sysPs.isPrivileged()) { 9101 allowed = true; 9102 } 9103 } else { 9104 // The system apk may have been updated with an older 9105 // version of the one on the data partition, but which 9106 // granted a new system permission that it didn't have 9107 // before. In this case we do want to allow the app to 9108 // now get the new permission if the ancestral apk is 9109 // privileged to get it. 9110 if (sysPs.pkg != null && sysPs.isPrivileged()) { 9111 for (int j=0; 9112 j<sysPs.pkg.requestedPermissions.size(); j++) { 9113 if (perm.equals( 9114 sysPs.pkg.requestedPermissions.get(j))) { 9115 allowed = true; 9116 break; 9117 } 9118 } 9119 } 9120 } 9121 } else { 9122 allowed = isPrivilegedApp(pkg); 9123 } 9124 } 9125 } 9126 if (!allowed) { 9127 if (!allowed && (bp.protectionLevel 9128 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9129 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9130 // If this was a previously normal/dangerous permission that got moved 9131 // to a system permission as part of the runtime permission redesign, then 9132 // we still want to blindly grant it to old apps. 9133 allowed = true; 9134 } 9135 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9136 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9137 // If this permission is to be granted to the system installer and 9138 // this app is an installer, then it gets the permission. 9139 allowed = true; 9140 } 9141 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9142 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9143 // If this permission is to be granted to the system verifier and 9144 // this app is a verifier, then it gets the permission. 9145 allowed = true; 9146 } 9147 if (!allowed && (bp.protectionLevel 9148 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9149 && isSystemApp(pkg)) { 9150 // Any pre-installed system app is allowed to get this permission. 9151 allowed = true; 9152 } 9153 if (!allowed && (bp.protectionLevel 9154 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9155 // For development permissions, a development permission 9156 // is granted only if it was already granted. 9157 allowed = origPermissions.hasInstallPermission(perm); 9158 } 9159 } 9160 return allowed; 9161 } 9162 9163 final class ActivityIntentResolver 9164 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9165 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9166 boolean defaultOnly, int userId) { 9167 if (!sUserManager.exists(userId)) return null; 9168 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9169 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9170 } 9171 9172 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9173 int userId) { 9174 if (!sUserManager.exists(userId)) return null; 9175 mFlags = flags; 9176 return super.queryIntent(intent, resolvedType, 9177 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9178 } 9179 9180 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9181 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9182 if (!sUserManager.exists(userId)) return null; 9183 if (packageActivities == null) { 9184 return null; 9185 } 9186 mFlags = flags; 9187 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9188 final int N = packageActivities.size(); 9189 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9190 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9191 9192 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9193 for (int i = 0; i < N; ++i) { 9194 intentFilters = packageActivities.get(i).intents; 9195 if (intentFilters != null && intentFilters.size() > 0) { 9196 PackageParser.ActivityIntentInfo[] array = 9197 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9198 intentFilters.toArray(array); 9199 listCut.add(array); 9200 } 9201 } 9202 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9203 } 9204 9205 public final void addActivity(PackageParser.Activity a, String type) { 9206 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9207 mActivities.put(a.getComponentName(), a); 9208 if (DEBUG_SHOW_INFO) 9209 Log.v( 9210 TAG, " " + type + " " + 9211 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9212 if (DEBUG_SHOW_INFO) 9213 Log.v(TAG, " Class=" + a.info.name); 9214 final int NI = a.intents.size(); 9215 for (int j=0; j<NI; j++) { 9216 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9217 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9218 intent.setPriority(0); 9219 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9220 + a.className + " with priority > 0, forcing to 0"); 9221 } 9222 if (DEBUG_SHOW_INFO) { 9223 Log.v(TAG, " IntentFilter:"); 9224 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9225 } 9226 if (!intent.debugCheck()) { 9227 Log.w(TAG, "==> For Activity " + a.info.name); 9228 } 9229 addFilter(intent); 9230 } 9231 } 9232 9233 public final void removeActivity(PackageParser.Activity a, String type) { 9234 mActivities.remove(a.getComponentName()); 9235 if (DEBUG_SHOW_INFO) { 9236 Log.v(TAG, " " + type + " " 9237 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9238 : a.info.name) + ":"); 9239 Log.v(TAG, " Class=" + a.info.name); 9240 } 9241 final int NI = a.intents.size(); 9242 for (int j=0; j<NI; j++) { 9243 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9244 if (DEBUG_SHOW_INFO) { 9245 Log.v(TAG, " IntentFilter:"); 9246 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9247 } 9248 removeFilter(intent); 9249 } 9250 } 9251 9252 @Override 9253 protected boolean allowFilterResult( 9254 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9255 ActivityInfo filterAi = filter.activity.info; 9256 for (int i=dest.size()-1; i>=0; i--) { 9257 ActivityInfo destAi = dest.get(i).activityInfo; 9258 if (destAi.name == filterAi.name 9259 && destAi.packageName == filterAi.packageName) { 9260 return false; 9261 } 9262 } 9263 return true; 9264 } 9265 9266 @Override 9267 protected ActivityIntentInfo[] newArray(int size) { 9268 return new ActivityIntentInfo[size]; 9269 } 9270 9271 @Override 9272 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9273 if (!sUserManager.exists(userId)) return true; 9274 PackageParser.Package p = filter.activity.owner; 9275 if (p != null) { 9276 PackageSetting ps = (PackageSetting)p.mExtras; 9277 if (ps != null) { 9278 // System apps are never considered stopped for purposes of 9279 // filtering, because there may be no way for the user to 9280 // actually re-launch them. 9281 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9282 && ps.getStopped(userId); 9283 } 9284 } 9285 return false; 9286 } 9287 9288 @Override 9289 protected boolean isPackageForFilter(String packageName, 9290 PackageParser.ActivityIntentInfo info) { 9291 return packageName.equals(info.activity.owner.packageName); 9292 } 9293 9294 @Override 9295 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9296 int match, int userId) { 9297 if (!sUserManager.exists(userId)) return null; 9298 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9299 return null; 9300 } 9301 final PackageParser.Activity activity = info.activity; 9302 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9303 if (ps == null) { 9304 return null; 9305 } 9306 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9307 ps.readUserState(userId), userId); 9308 if (ai == null) { 9309 return null; 9310 } 9311 final ResolveInfo res = new ResolveInfo(); 9312 res.activityInfo = ai; 9313 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9314 res.filter = info; 9315 } 9316 if (info != null) { 9317 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9318 } 9319 res.priority = info.getPriority(); 9320 res.preferredOrder = activity.owner.mPreferredOrder; 9321 //System.out.println("Result: " + res.activityInfo.className + 9322 // " = " + res.priority); 9323 res.match = match; 9324 res.isDefault = info.hasDefault; 9325 res.labelRes = info.labelRes; 9326 res.nonLocalizedLabel = info.nonLocalizedLabel; 9327 if (userNeedsBadging(userId)) { 9328 res.noResourceId = true; 9329 } else { 9330 res.icon = info.icon; 9331 } 9332 res.iconResourceId = info.icon; 9333 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9334 return res; 9335 } 9336 9337 @Override 9338 protected void sortResults(List<ResolveInfo> results) { 9339 Collections.sort(results, mResolvePrioritySorter); 9340 } 9341 9342 @Override 9343 protected void dumpFilter(PrintWriter out, String prefix, 9344 PackageParser.ActivityIntentInfo filter) { 9345 out.print(prefix); out.print( 9346 Integer.toHexString(System.identityHashCode(filter.activity))); 9347 out.print(' '); 9348 filter.activity.printComponentShortName(out); 9349 out.print(" filter "); 9350 out.println(Integer.toHexString(System.identityHashCode(filter))); 9351 } 9352 9353 @Override 9354 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9355 return filter.activity; 9356 } 9357 9358 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9359 PackageParser.Activity activity = (PackageParser.Activity)label; 9360 out.print(prefix); out.print( 9361 Integer.toHexString(System.identityHashCode(activity))); 9362 out.print(' '); 9363 activity.printComponentShortName(out); 9364 if (count > 1) { 9365 out.print(" ("); out.print(count); out.print(" filters)"); 9366 } 9367 out.println(); 9368 } 9369 9370// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9371// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9372// final List<ResolveInfo> retList = Lists.newArrayList(); 9373// while (i.hasNext()) { 9374// final ResolveInfo resolveInfo = i.next(); 9375// if (isEnabledLP(resolveInfo.activityInfo)) { 9376// retList.add(resolveInfo); 9377// } 9378// } 9379// return retList; 9380// } 9381 9382 // Keys are String (activity class name), values are Activity. 9383 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9384 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9385 private int mFlags; 9386 } 9387 9388 private final class ServiceIntentResolver 9389 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9390 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9391 boolean defaultOnly, int userId) { 9392 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9393 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9394 } 9395 9396 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9397 int userId) { 9398 if (!sUserManager.exists(userId)) return null; 9399 mFlags = flags; 9400 return super.queryIntent(intent, resolvedType, 9401 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9402 } 9403 9404 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9405 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9406 if (!sUserManager.exists(userId)) return null; 9407 if (packageServices == null) { 9408 return null; 9409 } 9410 mFlags = flags; 9411 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9412 final int N = packageServices.size(); 9413 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9414 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9415 9416 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9417 for (int i = 0; i < N; ++i) { 9418 intentFilters = packageServices.get(i).intents; 9419 if (intentFilters != null && intentFilters.size() > 0) { 9420 PackageParser.ServiceIntentInfo[] array = 9421 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9422 intentFilters.toArray(array); 9423 listCut.add(array); 9424 } 9425 } 9426 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9427 } 9428 9429 public final void addService(PackageParser.Service s) { 9430 mServices.put(s.getComponentName(), s); 9431 if (DEBUG_SHOW_INFO) { 9432 Log.v(TAG, " " 9433 + (s.info.nonLocalizedLabel != null 9434 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9435 Log.v(TAG, " Class=" + s.info.name); 9436 } 9437 final int NI = s.intents.size(); 9438 int j; 9439 for (j=0; j<NI; j++) { 9440 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9441 if (DEBUG_SHOW_INFO) { 9442 Log.v(TAG, " IntentFilter:"); 9443 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9444 } 9445 if (!intent.debugCheck()) { 9446 Log.w(TAG, "==> For Service " + s.info.name); 9447 } 9448 addFilter(intent); 9449 } 9450 } 9451 9452 public final void removeService(PackageParser.Service s) { 9453 mServices.remove(s.getComponentName()); 9454 if (DEBUG_SHOW_INFO) { 9455 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9456 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9457 Log.v(TAG, " Class=" + s.info.name); 9458 } 9459 final int NI = s.intents.size(); 9460 int j; 9461 for (j=0; j<NI; j++) { 9462 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9463 if (DEBUG_SHOW_INFO) { 9464 Log.v(TAG, " IntentFilter:"); 9465 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9466 } 9467 removeFilter(intent); 9468 } 9469 } 9470 9471 @Override 9472 protected boolean allowFilterResult( 9473 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9474 ServiceInfo filterSi = filter.service.info; 9475 for (int i=dest.size()-1; i>=0; i--) { 9476 ServiceInfo destAi = dest.get(i).serviceInfo; 9477 if (destAi.name == filterSi.name 9478 && destAi.packageName == filterSi.packageName) { 9479 return false; 9480 } 9481 } 9482 return true; 9483 } 9484 9485 @Override 9486 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9487 return new PackageParser.ServiceIntentInfo[size]; 9488 } 9489 9490 @Override 9491 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9492 if (!sUserManager.exists(userId)) return true; 9493 PackageParser.Package p = filter.service.owner; 9494 if (p != null) { 9495 PackageSetting ps = (PackageSetting)p.mExtras; 9496 if (ps != null) { 9497 // System apps are never considered stopped for purposes of 9498 // filtering, because there may be no way for the user to 9499 // actually re-launch them. 9500 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9501 && ps.getStopped(userId); 9502 } 9503 } 9504 return false; 9505 } 9506 9507 @Override 9508 protected boolean isPackageForFilter(String packageName, 9509 PackageParser.ServiceIntentInfo info) { 9510 return packageName.equals(info.service.owner.packageName); 9511 } 9512 9513 @Override 9514 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9515 int match, int userId) { 9516 if (!sUserManager.exists(userId)) return null; 9517 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9518 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9519 return null; 9520 } 9521 final PackageParser.Service service = info.service; 9522 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9523 if (ps == null) { 9524 return null; 9525 } 9526 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9527 ps.readUserState(userId), userId); 9528 if (si == null) { 9529 return null; 9530 } 9531 final ResolveInfo res = new ResolveInfo(); 9532 res.serviceInfo = si; 9533 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9534 res.filter = filter; 9535 } 9536 res.priority = info.getPriority(); 9537 res.preferredOrder = service.owner.mPreferredOrder; 9538 res.match = match; 9539 res.isDefault = info.hasDefault; 9540 res.labelRes = info.labelRes; 9541 res.nonLocalizedLabel = info.nonLocalizedLabel; 9542 res.icon = info.icon; 9543 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9544 return res; 9545 } 9546 9547 @Override 9548 protected void sortResults(List<ResolveInfo> results) { 9549 Collections.sort(results, mResolvePrioritySorter); 9550 } 9551 9552 @Override 9553 protected void dumpFilter(PrintWriter out, String prefix, 9554 PackageParser.ServiceIntentInfo filter) { 9555 out.print(prefix); out.print( 9556 Integer.toHexString(System.identityHashCode(filter.service))); 9557 out.print(' '); 9558 filter.service.printComponentShortName(out); 9559 out.print(" filter "); 9560 out.println(Integer.toHexString(System.identityHashCode(filter))); 9561 } 9562 9563 @Override 9564 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9565 return filter.service; 9566 } 9567 9568 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9569 PackageParser.Service service = (PackageParser.Service)label; 9570 out.print(prefix); out.print( 9571 Integer.toHexString(System.identityHashCode(service))); 9572 out.print(' '); 9573 service.printComponentShortName(out); 9574 if (count > 1) { 9575 out.print(" ("); out.print(count); out.print(" filters)"); 9576 } 9577 out.println(); 9578 } 9579 9580// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9581// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9582// final List<ResolveInfo> retList = Lists.newArrayList(); 9583// while (i.hasNext()) { 9584// final ResolveInfo resolveInfo = (ResolveInfo) i; 9585// if (isEnabledLP(resolveInfo.serviceInfo)) { 9586// retList.add(resolveInfo); 9587// } 9588// } 9589// return retList; 9590// } 9591 9592 // Keys are String (activity class name), values are Activity. 9593 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9594 = new ArrayMap<ComponentName, PackageParser.Service>(); 9595 private int mFlags; 9596 }; 9597 9598 private final class ProviderIntentResolver 9599 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9600 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9601 boolean defaultOnly, int userId) { 9602 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9603 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9604 } 9605 9606 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9607 int userId) { 9608 if (!sUserManager.exists(userId)) 9609 return null; 9610 mFlags = flags; 9611 return super.queryIntent(intent, resolvedType, 9612 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9613 } 9614 9615 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9616 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9617 if (!sUserManager.exists(userId)) 9618 return null; 9619 if (packageProviders == null) { 9620 return null; 9621 } 9622 mFlags = flags; 9623 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9624 final int N = packageProviders.size(); 9625 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9626 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9627 9628 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9629 for (int i = 0; i < N; ++i) { 9630 intentFilters = packageProviders.get(i).intents; 9631 if (intentFilters != null && intentFilters.size() > 0) { 9632 PackageParser.ProviderIntentInfo[] array = 9633 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9634 intentFilters.toArray(array); 9635 listCut.add(array); 9636 } 9637 } 9638 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9639 } 9640 9641 public final void addProvider(PackageParser.Provider p) { 9642 if (mProviders.containsKey(p.getComponentName())) { 9643 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9644 return; 9645 } 9646 9647 mProviders.put(p.getComponentName(), p); 9648 if (DEBUG_SHOW_INFO) { 9649 Log.v(TAG, " " 9650 + (p.info.nonLocalizedLabel != null 9651 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9652 Log.v(TAG, " Class=" + p.info.name); 9653 } 9654 final int NI = p.intents.size(); 9655 int j; 9656 for (j = 0; j < NI; j++) { 9657 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9658 if (DEBUG_SHOW_INFO) { 9659 Log.v(TAG, " IntentFilter:"); 9660 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9661 } 9662 if (!intent.debugCheck()) { 9663 Log.w(TAG, "==> For Provider " + p.info.name); 9664 } 9665 addFilter(intent); 9666 } 9667 } 9668 9669 public final void removeProvider(PackageParser.Provider p) { 9670 mProviders.remove(p.getComponentName()); 9671 if (DEBUG_SHOW_INFO) { 9672 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9673 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9674 Log.v(TAG, " Class=" + p.info.name); 9675 } 9676 final int NI = p.intents.size(); 9677 int j; 9678 for (j = 0; j < NI; j++) { 9679 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9680 if (DEBUG_SHOW_INFO) { 9681 Log.v(TAG, " IntentFilter:"); 9682 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9683 } 9684 removeFilter(intent); 9685 } 9686 } 9687 9688 @Override 9689 protected boolean allowFilterResult( 9690 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9691 ProviderInfo filterPi = filter.provider.info; 9692 for (int i = dest.size() - 1; i >= 0; i--) { 9693 ProviderInfo destPi = dest.get(i).providerInfo; 9694 if (destPi.name == filterPi.name 9695 && destPi.packageName == filterPi.packageName) { 9696 return false; 9697 } 9698 } 9699 return true; 9700 } 9701 9702 @Override 9703 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9704 return new PackageParser.ProviderIntentInfo[size]; 9705 } 9706 9707 @Override 9708 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9709 if (!sUserManager.exists(userId)) 9710 return true; 9711 PackageParser.Package p = filter.provider.owner; 9712 if (p != null) { 9713 PackageSetting ps = (PackageSetting) p.mExtras; 9714 if (ps != null) { 9715 // System apps are never considered stopped for purposes of 9716 // filtering, because there may be no way for the user to 9717 // actually re-launch them. 9718 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9719 && ps.getStopped(userId); 9720 } 9721 } 9722 return false; 9723 } 9724 9725 @Override 9726 protected boolean isPackageForFilter(String packageName, 9727 PackageParser.ProviderIntentInfo info) { 9728 return packageName.equals(info.provider.owner.packageName); 9729 } 9730 9731 @Override 9732 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9733 int match, int userId) { 9734 if (!sUserManager.exists(userId)) 9735 return null; 9736 final PackageParser.ProviderIntentInfo info = filter; 9737 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 9738 return null; 9739 } 9740 final PackageParser.Provider provider = info.provider; 9741 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9742 if (ps == null) { 9743 return null; 9744 } 9745 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9746 ps.readUserState(userId), userId); 9747 if (pi == null) { 9748 return null; 9749 } 9750 final ResolveInfo res = new ResolveInfo(); 9751 res.providerInfo = pi; 9752 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9753 res.filter = filter; 9754 } 9755 res.priority = info.getPriority(); 9756 res.preferredOrder = provider.owner.mPreferredOrder; 9757 res.match = match; 9758 res.isDefault = info.hasDefault; 9759 res.labelRes = info.labelRes; 9760 res.nonLocalizedLabel = info.nonLocalizedLabel; 9761 res.icon = info.icon; 9762 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9763 return res; 9764 } 9765 9766 @Override 9767 protected void sortResults(List<ResolveInfo> results) { 9768 Collections.sort(results, mResolvePrioritySorter); 9769 } 9770 9771 @Override 9772 protected void dumpFilter(PrintWriter out, String prefix, 9773 PackageParser.ProviderIntentInfo filter) { 9774 out.print(prefix); 9775 out.print( 9776 Integer.toHexString(System.identityHashCode(filter.provider))); 9777 out.print(' '); 9778 filter.provider.printComponentShortName(out); 9779 out.print(" filter "); 9780 out.println(Integer.toHexString(System.identityHashCode(filter))); 9781 } 9782 9783 @Override 9784 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9785 return filter.provider; 9786 } 9787 9788 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9789 PackageParser.Provider provider = (PackageParser.Provider)label; 9790 out.print(prefix); out.print( 9791 Integer.toHexString(System.identityHashCode(provider))); 9792 out.print(' '); 9793 provider.printComponentShortName(out); 9794 if (count > 1) { 9795 out.print(" ("); out.print(count); out.print(" filters)"); 9796 } 9797 out.println(); 9798 } 9799 9800 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9801 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9802 private int mFlags; 9803 } 9804 9805 private static final class EphemeralIntentResolver 9806 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 9807 @Override 9808 protected EphemeralResolveIntentInfo[] newArray(int size) { 9809 return new EphemeralResolveIntentInfo[size]; 9810 } 9811 9812 @Override 9813 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 9814 return true; 9815 } 9816 9817 @Override 9818 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 9819 int userId) { 9820 if (!sUserManager.exists(userId)) { 9821 return null; 9822 } 9823 return info.getEphemeralResolveInfo(); 9824 } 9825 } 9826 9827 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9828 new Comparator<ResolveInfo>() { 9829 public int compare(ResolveInfo r1, ResolveInfo r2) { 9830 int v1 = r1.priority; 9831 int v2 = r2.priority; 9832 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9833 if (v1 != v2) { 9834 return (v1 > v2) ? -1 : 1; 9835 } 9836 v1 = r1.preferredOrder; 9837 v2 = r2.preferredOrder; 9838 if (v1 != v2) { 9839 return (v1 > v2) ? -1 : 1; 9840 } 9841 if (r1.isDefault != r2.isDefault) { 9842 return r1.isDefault ? -1 : 1; 9843 } 9844 v1 = r1.match; 9845 v2 = r2.match; 9846 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9847 if (v1 != v2) { 9848 return (v1 > v2) ? -1 : 1; 9849 } 9850 if (r1.system != r2.system) { 9851 return r1.system ? -1 : 1; 9852 } 9853 if (r1.activityInfo != null) { 9854 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 9855 } 9856 if (r1.serviceInfo != null) { 9857 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 9858 } 9859 if (r1.providerInfo != null) { 9860 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 9861 } 9862 return 0; 9863 } 9864 }; 9865 9866 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9867 new Comparator<ProviderInfo>() { 9868 public int compare(ProviderInfo p1, ProviderInfo p2) { 9869 final int v1 = p1.initOrder; 9870 final int v2 = p2.initOrder; 9871 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9872 } 9873 }; 9874 9875 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 9876 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 9877 final int[] userIds) { 9878 mHandler.post(new Runnable() { 9879 @Override 9880 public void run() { 9881 try { 9882 final IActivityManager am = ActivityManagerNative.getDefault(); 9883 if (am == null) return; 9884 final int[] resolvedUserIds; 9885 if (userIds == null) { 9886 resolvedUserIds = am.getRunningUserIds(); 9887 } else { 9888 resolvedUserIds = userIds; 9889 } 9890 for (int id : resolvedUserIds) { 9891 final Intent intent = new Intent(action, 9892 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9893 if (extras != null) { 9894 intent.putExtras(extras); 9895 } 9896 if (targetPkg != null) { 9897 intent.setPackage(targetPkg); 9898 } 9899 // Modify the UID when posting to other users 9900 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9901 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9902 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9903 intent.putExtra(Intent.EXTRA_UID, uid); 9904 } 9905 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9906 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 9907 if (DEBUG_BROADCASTS) { 9908 RuntimeException here = new RuntimeException("here"); 9909 here.fillInStackTrace(); 9910 Slog.d(TAG, "Sending to user " + id + ": " 9911 + intent.toShortString(false, true, false, false) 9912 + " " + intent.getExtras(), here); 9913 } 9914 am.broadcastIntent(null, intent, null, finishedReceiver, 9915 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9916 null, finishedReceiver != null, false, id); 9917 } 9918 } catch (RemoteException ex) { 9919 } 9920 } 9921 }); 9922 } 9923 9924 /** 9925 * Check if the external storage media is available. This is true if there 9926 * is a mounted external storage medium or if the external storage is 9927 * emulated. 9928 */ 9929 private boolean isExternalMediaAvailable() { 9930 return mMediaMounted || Environment.isExternalStorageEmulated(); 9931 } 9932 9933 @Override 9934 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9935 // writer 9936 synchronized (mPackages) { 9937 if (!isExternalMediaAvailable()) { 9938 // If the external storage is no longer mounted at this point, 9939 // the caller may not have been able to delete all of this 9940 // packages files and can not delete any more. Bail. 9941 return null; 9942 } 9943 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9944 if (lastPackage != null) { 9945 pkgs.remove(lastPackage); 9946 } 9947 if (pkgs.size() > 0) { 9948 return pkgs.get(0); 9949 } 9950 } 9951 return null; 9952 } 9953 9954 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9955 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9956 userId, andCode ? 1 : 0, packageName); 9957 if (mSystemReady) { 9958 msg.sendToTarget(); 9959 } else { 9960 if (mPostSystemReadyMessages == null) { 9961 mPostSystemReadyMessages = new ArrayList<>(); 9962 } 9963 mPostSystemReadyMessages.add(msg); 9964 } 9965 } 9966 9967 void startCleaningPackages() { 9968 // reader 9969 synchronized (mPackages) { 9970 if (!isExternalMediaAvailable()) { 9971 return; 9972 } 9973 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9974 return; 9975 } 9976 } 9977 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9978 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9979 IActivityManager am = ActivityManagerNative.getDefault(); 9980 if (am != null) { 9981 try { 9982 am.startService(null, intent, null, mContext.getOpPackageName(), 9983 UserHandle.USER_SYSTEM); 9984 } catch (RemoteException e) { 9985 } 9986 } 9987 } 9988 9989 @Override 9990 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9991 int installFlags, String installerPackageName, VerificationParams verificationParams, 9992 String packageAbiOverride) { 9993 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9994 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9995 } 9996 9997 @Override 9998 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9999 int installFlags, String installerPackageName, VerificationParams verificationParams, 10000 String packageAbiOverride, int userId) { 10001 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10002 10003 final int callingUid = Binder.getCallingUid(); 10004 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 10005 10006 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10007 try { 10008 if (observer != null) { 10009 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10010 } 10011 } catch (RemoteException re) { 10012 } 10013 return; 10014 } 10015 10016 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10017 installFlags |= PackageManager.INSTALL_FROM_ADB; 10018 10019 } else { 10020 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10021 // about installerPackageName. 10022 10023 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10024 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10025 } 10026 10027 UserHandle user; 10028 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10029 user = UserHandle.ALL; 10030 } else { 10031 user = new UserHandle(userId); 10032 } 10033 10034 // Only system components can circumvent runtime permissions when installing. 10035 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10036 && mContext.checkCallingOrSelfPermission(Manifest.permission 10037 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10038 throw new SecurityException("You need the " 10039 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10040 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10041 } 10042 10043 verificationParams.setInstallerUid(callingUid); 10044 10045 final File originFile = new File(originPath); 10046 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10047 10048 final Message msg = mHandler.obtainMessage(INIT_COPY); 10049 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 10050 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 10051 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10052 msg.obj = params; 10053 10054 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10055 System.identityHashCode(msg.obj)); 10056 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10057 System.identityHashCode(msg.obj)); 10058 10059 mHandler.sendMessage(msg); 10060 } 10061 10062 void installStage(String packageName, File stagedDir, String stagedCid, 10063 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10064 String installerPackageName, int installerUid, UserHandle user) { 10065 if (DEBUG_EPHEMERAL) { 10066 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10067 Slog.d(TAG, "Ephemeral install of " + packageName); 10068 } 10069 } 10070 final VerificationParams verifParams = new VerificationParams( 10071 null, sessionParams.originatingUri, sessionParams.referrerUri, 10072 sessionParams.originatingUid); 10073 verifParams.setInstallerUid(installerUid); 10074 10075 final OriginInfo origin; 10076 if (stagedDir != null) { 10077 origin = OriginInfo.fromStagedFile(stagedDir); 10078 } else { 10079 origin = OriginInfo.fromStagedContainer(stagedCid); 10080 } 10081 10082 final Message msg = mHandler.obtainMessage(INIT_COPY); 10083 final InstallParams params = new InstallParams(origin, null, observer, 10084 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10085 verifParams, user, sessionParams.abiOverride, 10086 sessionParams.grantedRuntimePermissions); 10087 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10088 msg.obj = params; 10089 10090 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10091 System.identityHashCode(msg.obj)); 10092 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10093 System.identityHashCode(msg.obj)); 10094 10095 mHandler.sendMessage(msg); 10096 } 10097 10098 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 10099 Bundle extras = new Bundle(1); 10100 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 10101 10102 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10103 packageName, extras, 0, null, null, new int[] {userId}); 10104 try { 10105 IActivityManager am = ActivityManagerNative.getDefault(); 10106 final boolean isSystem = 10107 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10108 if (isSystem && am.isUserRunning(userId, 0)) { 10109 // The just-installed/enabled app is bundled on the system, so presumed 10110 // to be able to run automatically without needing an explicit launch. 10111 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10112 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10113 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10114 .setPackage(packageName); 10115 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10116 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10117 } 10118 } catch (RemoteException e) { 10119 // shouldn't happen 10120 Slog.w(TAG, "Unable to bootstrap installed package", e); 10121 } 10122 } 10123 10124 @Override 10125 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10126 int userId) { 10127 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10128 PackageSetting pkgSetting; 10129 final int uid = Binder.getCallingUid(); 10130 enforceCrossUserPermission(uid, userId, true, true, 10131 "setApplicationHiddenSetting for user " + userId); 10132 10133 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10134 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10135 return false; 10136 } 10137 10138 long callingId = Binder.clearCallingIdentity(); 10139 try { 10140 boolean sendAdded = false; 10141 boolean sendRemoved = false; 10142 // writer 10143 synchronized (mPackages) { 10144 pkgSetting = mSettings.mPackages.get(packageName); 10145 if (pkgSetting == null) { 10146 return false; 10147 } 10148 if (pkgSetting.getHidden(userId) != hidden) { 10149 pkgSetting.setHidden(hidden, userId); 10150 mSettings.writePackageRestrictionsLPr(userId); 10151 if (hidden) { 10152 sendRemoved = true; 10153 } else { 10154 sendAdded = true; 10155 } 10156 } 10157 } 10158 if (sendAdded) { 10159 sendPackageAddedForUser(packageName, pkgSetting, userId); 10160 return true; 10161 } 10162 if (sendRemoved) { 10163 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10164 "hiding pkg"); 10165 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10166 return true; 10167 } 10168 } finally { 10169 Binder.restoreCallingIdentity(callingId); 10170 } 10171 return false; 10172 } 10173 10174 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10175 int userId) { 10176 final PackageRemovedInfo info = new PackageRemovedInfo(); 10177 info.removedPackage = packageName; 10178 info.removedUsers = new int[] {userId}; 10179 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10180 info.sendBroadcast(false, false, false); 10181 } 10182 10183 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10184 if (pkgList.length > 0) { 10185 Bundle extras = new Bundle(1); 10186 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10187 10188 sendPackageBroadcast( 10189 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10190 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10191 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10192 new int[] {userId}); 10193 } 10194 } 10195 10196 /** 10197 * Returns true if application is not found or there was an error. Otherwise it returns 10198 * the hidden state of the package for the given user. 10199 */ 10200 @Override 10201 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10202 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10203 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10204 false, "getApplicationHidden for user " + userId); 10205 PackageSetting pkgSetting; 10206 long callingId = Binder.clearCallingIdentity(); 10207 try { 10208 // writer 10209 synchronized (mPackages) { 10210 pkgSetting = mSettings.mPackages.get(packageName); 10211 if (pkgSetting == null) { 10212 return true; 10213 } 10214 return pkgSetting.getHidden(userId); 10215 } 10216 } finally { 10217 Binder.restoreCallingIdentity(callingId); 10218 } 10219 } 10220 10221 /** 10222 * @hide 10223 */ 10224 @Override 10225 public int installExistingPackageAsUser(String packageName, int userId) { 10226 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10227 null); 10228 PackageSetting pkgSetting; 10229 final int uid = Binder.getCallingUid(); 10230 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10231 + userId); 10232 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10233 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10234 } 10235 10236 long callingId = Binder.clearCallingIdentity(); 10237 try { 10238 boolean installed = false; 10239 10240 // writer 10241 synchronized (mPackages) { 10242 pkgSetting = mSettings.mPackages.get(packageName); 10243 if (pkgSetting == null) { 10244 return PackageManager.INSTALL_FAILED_INVALID_URI; 10245 } 10246 if (!pkgSetting.getInstalled(userId)) { 10247 pkgSetting.setInstalled(true, userId); 10248 pkgSetting.setHidden(false, userId); 10249 mSettings.writePackageRestrictionsLPr(userId); 10250 if (pkgSetting.pkg != null) { 10251 prepareAppDataAfterInstall(pkgSetting.pkg); 10252 } 10253 installed = true; 10254 } 10255 } 10256 10257 if (installed) { 10258 sendPackageAddedForUser(packageName, pkgSetting, userId); 10259 } 10260 } finally { 10261 Binder.restoreCallingIdentity(callingId); 10262 } 10263 10264 return PackageManager.INSTALL_SUCCEEDED; 10265 } 10266 10267 boolean isUserRestricted(int userId, String restrictionKey) { 10268 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10269 if (restrictions.getBoolean(restrictionKey, false)) { 10270 Log.w(TAG, "User is restricted: " + restrictionKey); 10271 return true; 10272 } 10273 return false; 10274 } 10275 10276 @Override 10277 public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) { 10278 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10279 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true, 10280 "setPackageSuspended for user " + userId); 10281 10282 // TODO: investigate and add more restrictions for suspending crucial packages. 10283 if (isPackageDeviceAdmin(packageName, userId)) { 10284 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10285 + "\": has active device admin"); 10286 return false; 10287 } 10288 10289 long callingId = Binder.clearCallingIdentity(); 10290 try { 10291 boolean changed = false; 10292 boolean success = false; 10293 int appId = -1; 10294 synchronized (mPackages) { 10295 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10296 if (pkgSetting != null) { 10297 if (pkgSetting.getSuspended(userId) != suspended) { 10298 pkgSetting.setSuspended(suspended, userId); 10299 mSettings.writePackageRestrictionsLPr(userId); 10300 appId = pkgSetting.appId; 10301 changed = true; 10302 } 10303 success = true; 10304 } 10305 } 10306 10307 if (changed) { 10308 sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended); 10309 if (suspended) { 10310 killApplication(packageName, UserHandle.getUid(userId, appId), 10311 "suspending package"); 10312 } 10313 } 10314 return success; 10315 } finally { 10316 Binder.restoreCallingIdentity(callingId); 10317 } 10318 } 10319 10320 @Override 10321 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10322 mContext.enforceCallingOrSelfPermission( 10323 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10324 "Only package verification agents can verify applications"); 10325 10326 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10327 final PackageVerificationResponse response = new PackageVerificationResponse( 10328 verificationCode, Binder.getCallingUid()); 10329 msg.arg1 = id; 10330 msg.obj = response; 10331 mHandler.sendMessage(msg); 10332 } 10333 10334 @Override 10335 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10336 long millisecondsToDelay) { 10337 mContext.enforceCallingOrSelfPermission( 10338 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10339 "Only package verification agents can extend verification timeouts"); 10340 10341 final PackageVerificationState state = mPendingVerification.get(id); 10342 final PackageVerificationResponse response = new PackageVerificationResponse( 10343 verificationCodeAtTimeout, Binder.getCallingUid()); 10344 10345 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10346 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10347 } 10348 if (millisecondsToDelay < 0) { 10349 millisecondsToDelay = 0; 10350 } 10351 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10352 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10353 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10354 } 10355 10356 if ((state != null) && !state.timeoutExtended()) { 10357 state.extendTimeout(); 10358 10359 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10360 msg.arg1 = id; 10361 msg.obj = response; 10362 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10363 } 10364 } 10365 10366 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10367 int verificationCode, UserHandle user) { 10368 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10369 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10370 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10371 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10372 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10373 10374 mContext.sendBroadcastAsUser(intent, user, 10375 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10376 } 10377 10378 private ComponentName matchComponentForVerifier(String packageName, 10379 List<ResolveInfo> receivers) { 10380 ActivityInfo targetReceiver = null; 10381 10382 final int NR = receivers.size(); 10383 for (int i = 0; i < NR; i++) { 10384 final ResolveInfo info = receivers.get(i); 10385 if (info.activityInfo == null) { 10386 continue; 10387 } 10388 10389 if (packageName.equals(info.activityInfo.packageName)) { 10390 targetReceiver = info.activityInfo; 10391 break; 10392 } 10393 } 10394 10395 if (targetReceiver == null) { 10396 return null; 10397 } 10398 10399 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10400 } 10401 10402 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10403 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10404 if (pkgInfo.verifiers.length == 0) { 10405 return null; 10406 } 10407 10408 final int N = pkgInfo.verifiers.length; 10409 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10410 for (int i = 0; i < N; i++) { 10411 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10412 10413 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10414 receivers); 10415 if (comp == null) { 10416 continue; 10417 } 10418 10419 final int verifierUid = getUidForVerifier(verifierInfo); 10420 if (verifierUid == -1) { 10421 continue; 10422 } 10423 10424 if (DEBUG_VERIFY) { 10425 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10426 + " with the correct signature"); 10427 } 10428 sufficientVerifiers.add(comp); 10429 verificationState.addSufficientVerifier(verifierUid); 10430 } 10431 10432 return sufficientVerifiers; 10433 } 10434 10435 private int getUidForVerifier(VerifierInfo verifierInfo) { 10436 synchronized (mPackages) { 10437 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10438 if (pkg == null) { 10439 return -1; 10440 } else if (pkg.mSignatures.length != 1) { 10441 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10442 + " has more than one signature; ignoring"); 10443 return -1; 10444 } 10445 10446 /* 10447 * If the public key of the package's signature does not match 10448 * our expected public key, then this is a different package and 10449 * we should skip. 10450 */ 10451 10452 final byte[] expectedPublicKey; 10453 try { 10454 final Signature verifierSig = pkg.mSignatures[0]; 10455 final PublicKey publicKey = verifierSig.getPublicKey(); 10456 expectedPublicKey = publicKey.getEncoded(); 10457 } catch (CertificateException e) { 10458 return -1; 10459 } 10460 10461 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10462 10463 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10464 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10465 + " does not have the expected public key; ignoring"); 10466 return -1; 10467 } 10468 10469 return pkg.applicationInfo.uid; 10470 } 10471 } 10472 10473 @Override 10474 public void finishPackageInstall(int token) { 10475 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10476 10477 if (DEBUG_INSTALL) { 10478 Slog.v(TAG, "BM finishing package install for " + token); 10479 } 10480 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10481 10482 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10483 mHandler.sendMessage(msg); 10484 } 10485 10486 /** 10487 * Get the verification agent timeout. 10488 * 10489 * @return verification timeout in milliseconds 10490 */ 10491 private long getVerificationTimeout() { 10492 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10493 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10494 DEFAULT_VERIFICATION_TIMEOUT); 10495 } 10496 10497 /** 10498 * Get the default verification agent response code. 10499 * 10500 * @return default verification response code 10501 */ 10502 private int getDefaultVerificationResponse() { 10503 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10504 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10505 DEFAULT_VERIFICATION_RESPONSE); 10506 } 10507 10508 /** 10509 * Check whether or not package verification has been enabled. 10510 * 10511 * @return true if verification should be performed 10512 */ 10513 private boolean isVerificationEnabled(int userId, int installFlags) { 10514 if (!DEFAULT_VERIFY_ENABLE) { 10515 return false; 10516 } 10517 // Ephemeral apps don't get the full verification treatment 10518 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10519 if (DEBUG_EPHEMERAL) { 10520 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10521 } 10522 return false; 10523 } 10524 10525 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10526 10527 // Check if installing from ADB 10528 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10529 // Do not run verification in a test harness environment 10530 if (ActivityManager.isRunningInTestHarness()) { 10531 return false; 10532 } 10533 if (ensureVerifyAppsEnabled) { 10534 return true; 10535 } 10536 // Check if the developer does not want package verification for ADB installs 10537 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10538 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10539 return false; 10540 } 10541 } 10542 10543 if (ensureVerifyAppsEnabled) { 10544 return true; 10545 } 10546 10547 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10548 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10549 } 10550 10551 @Override 10552 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10553 throws RemoteException { 10554 mContext.enforceCallingOrSelfPermission( 10555 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10556 "Only intentfilter verification agents can verify applications"); 10557 10558 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10559 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10560 Binder.getCallingUid(), verificationCode, failedDomains); 10561 msg.arg1 = id; 10562 msg.obj = response; 10563 mHandler.sendMessage(msg); 10564 } 10565 10566 @Override 10567 public int getIntentVerificationStatus(String packageName, int userId) { 10568 synchronized (mPackages) { 10569 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10570 } 10571 } 10572 10573 @Override 10574 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10575 mContext.enforceCallingOrSelfPermission( 10576 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10577 10578 boolean result = false; 10579 synchronized (mPackages) { 10580 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10581 } 10582 if (result) { 10583 scheduleWritePackageRestrictionsLocked(userId); 10584 } 10585 return result; 10586 } 10587 10588 @Override 10589 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10590 synchronized (mPackages) { 10591 return mSettings.getIntentFilterVerificationsLPr(packageName); 10592 } 10593 } 10594 10595 @Override 10596 public List<IntentFilter> getAllIntentFilters(String packageName) { 10597 if (TextUtils.isEmpty(packageName)) { 10598 return Collections.<IntentFilter>emptyList(); 10599 } 10600 synchronized (mPackages) { 10601 PackageParser.Package pkg = mPackages.get(packageName); 10602 if (pkg == null || pkg.activities == null) { 10603 return Collections.<IntentFilter>emptyList(); 10604 } 10605 final int count = pkg.activities.size(); 10606 ArrayList<IntentFilter> result = new ArrayList<>(); 10607 for (int n=0; n<count; n++) { 10608 PackageParser.Activity activity = pkg.activities.get(n); 10609 if (activity.intents != null && activity.intents.size() > 0) { 10610 result.addAll(activity.intents); 10611 } 10612 } 10613 return result; 10614 } 10615 } 10616 10617 @Override 10618 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10619 mContext.enforceCallingOrSelfPermission( 10620 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10621 10622 synchronized (mPackages) { 10623 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10624 if (packageName != null) { 10625 result |= updateIntentVerificationStatus(packageName, 10626 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10627 userId); 10628 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10629 packageName, userId); 10630 } 10631 return result; 10632 } 10633 } 10634 10635 @Override 10636 public String getDefaultBrowserPackageName(int userId) { 10637 synchronized (mPackages) { 10638 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10639 } 10640 } 10641 10642 /** 10643 * Get the "allow unknown sources" setting. 10644 * 10645 * @return the current "allow unknown sources" setting 10646 */ 10647 private int getUnknownSourcesSettings() { 10648 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10649 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10650 -1); 10651 } 10652 10653 @Override 10654 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10655 final int uid = Binder.getCallingUid(); 10656 // writer 10657 synchronized (mPackages) { 10658 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10659 if (targetPackageSetting == null) { 10660 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10661 } 10662 10663 PackageSetting installerPackageSetting; 10664 if (installerPackageName != null) { 10665 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10666 if (installerPackageSetting == null) { 10667 throw new IllegalArgumentException("Unknown installer package: " 10668 + installerPackageName); 10669 } 10670 } else { 10671 installerPackageSetting = null; 10672 } 10673 10674 Signature[] callerSignature; 10675 Object obj = mSettings.getUserIdLPr(uid); 10676 if (obj != null) { 10677 if (obj instanceof SharedUserSetting) { 10678 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10679 } else if (obj instanceof PackageSetting) { 10680 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10681 } else { 10682 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10683 } 10684 } else { 10685 throw new SecurityException("Unknown calling UID: " + uid); 10686 } 10687 10688 // Verify: can't set installerPackageName to a package that is 10689 // not signed with the same cert as the caller. 10690 if (installerPackageSetting != null) { 10691 if (compareSignatures(callerSignature, 10692 installerPackageSetting.signatures.mSignatures) 10693 != PackageManager.SIGNATURE_MATCH) { 10694 throw new SecurityException( 10695 "Caller does not have same cert as new installer package " 10696 + installerPackageName); 10697 } 10698 } 10699 10700 // Verify: if target already has an installer package, it must 10701 // be signed with the same cert as the caller. 10702 if (targetPackageSetting.installerPackageName != null) { 10703 PackageSetting setting = mSettings.mPackages.get( 10704 targetPackageSetting.installerPackageName); 10705 // If the currently set package isn't valid, then it's always 10706 // okay to change it. 10707 if (setting != null) { 10708 if (compareSignatures(callerSignature, 10709 setting.signatures.mSignatures) 10710 != PackageManager.SIGNATURE_MATCH) { 10711 throw new SecurityException( 10712 "Caller does not have same cert as old installer package " 10713 + targetPackageSetting.installerPackageName); 10714 } 10715 } 10716 } 10717 10718 // Okay! 10719 targetPackageSetting.installerPackageName = installerPackageName; 10720 scheduleWriteSettingsLocked(); 10721 } 10722 } 10723 10724 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10725 // Queue up an async operation since the package installation may take a little while. 10726 mHandler.post(new Runnable() { 10727 public void run() { 10728 mHandler.removeCallbacks(this); 10729 // Result object to be returned 10730 PackageInstalledInfo res = new PackageInstalledInfo(); 10731 res.returnCode = currentStatus; 10732 res.uid = -1; 10733 res.pkg = null; 10734 res.removedInfo = new PackageRemovedInfo(); 10735 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10736 args.doPreInstall(res.returnCode); 10737 synchronized (mInstallLock) { 10738 installPackageTracedLI(args, res); 10739 } 10740 args.doPostInstall(res.returnCode, res.uid); 10741 } 10742 10743 // A restore should be performed at this point if (a) the install 10744 // succeeded, (b) the operation is not an update, and (c) the new 10745 // package has not opted out of backup participation. 10746 final boolean update = res.removedInfo.removedPackage != null; 10747 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10748 boolean doRestore = !update 10749 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10750 10751 // Set up the post-install work request bookkeeping. This will be used 10752 // and cleaned up by the post-install event handling regardless of whether 10753 // there's a restore pass performed. Token values are >= 1. 10754 int token; 10755 if (mNextInstallToken < 0) mNextInstallToken = 1; 10756 token = mNextInstallToken++; 10757 10758 PostInstallData data = new PostInstallData(args, res); 10759 mRunningInstalls.put(token, data); 10760 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10761 10762 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10763 // Pass responsibility to the Backup Manager. It will perform a 10764 // restore if appropriate, then pass responsibility back to the 10765 // Package Manager to run the post-install observer callbacks 10766 // and broadcasts. 10767 IBackupManager bm = IBackupManager.Stub.asInterface( 10768 ServiceManager.getService(Context.BACKUP_SERVICE)); 10769 if (bm != null) { 10770 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10771 + " to BM for possible restore"); 10772 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10773 try { 10774 // TODO: http://b/22388012 10775 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10776 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10777 } else { 10778 doRestore = false; 10779 } 10780 } catch (RemoteException e) { 10781 // can't happen; the backup manager is local 10782 } catch (Exception e) { 10783 Slog.e(TAG, "Exception trying to enqueue restore", e); 10784 doRestore = false; 10785 } 10786 } else { 10787 Slog.e(TAG, "Backup Manager not found!"); 10788 doRestore = false; 10789 } 10790 } 10791 10792 if (!doRestore) { 10793 // No restore possible, or the Backup Manager was mysteriously not 10794 // available -- just fire the post-install work request directly. 10795 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10796 10797 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10798 10799 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10800 mHandler.sendMessage(msg); 10801 } 10802 } 10803 }); 10804 } 10805 10806 private abstract class HandlerParams { 10807 private static final int MAX_RETRIES = 4; 10808 10809 /** 10810 * Number of times startCopy() has been attempted and had a non-fatal 10811 * error. 10812 */ 10813 private int mRetries = 0; 10814 10815 /** User handle for the user requesting the information or installation. */ 10816 private final UserHandle mUser; 10817 String traceMethod; 10818 int traceCookie; 10819 10820 HandlerParams(UserHandle user) { 10821 mUser = user; 10822 } 10823 10824 UserHandle getUser() { 10825 return mUser; 10826 } 10827 10828 HandlerParams setTraceMethod(String traceMethod) { 10829 this.traceMethod = traceMethod; 10830 return this; 10831 } 10832 10833 HandlerParams setTraceCookie(int traceCookie) { 10834 this.traceCookie = traceCookie; 10835 return this; 10836 } 10837 10838 final boolean startCopy() { 10839 boolean res; 10840 try { 10841 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10842 10843 if (++mRetries > MAX_RETRIES) { 10844 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10845 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10846 handleServiceError(); 10847 return false; 10848 } else { 10849 handleStartCopy(); 10850 res = true; 10851 } 10852 } catch (RemoteException e) { 10853 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10854 mHandler.sendEmptyMessage(MCS_RECONNECT); 10855 res = false; 10856 } 10857 handleReturnCode(); 10858 return res; 10859 } 10860 10861 final void serviceError() { 10862 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10863 handleServiceError(); 10864 handleReturnCode(); 10865 } 10866 10867 abstract void handleStartCopy() throws RemoteException; 10868 abstract void handleServiceError(); 10869 abstract void handleReturnCode(); 10870 } 10871 10872 class MeasureParams extends HandlerParams { 10873 private final PackageStats mStats; 10874 private boolean mSuccess; 10875 10876 private final IPackageStatsObserver mObserver; 10877 10878 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10879 super(new UserHandle(stats.userHandle)); 10880 mObserver = observer; 10881 mStats = stats; 10882 } 10883 10884 @Override 10885 public String toString() { 10886 return "MeasureParams{" 10887 + Integer.toHexString(System.identityHashCode(this)) 10888 + " " + mStats.packageName + "}"; 10889 } 10890 10891 @Override 10892 void handleStartCopy() throws RemoteException { 10893 synchronized (mInstallLock) { 10894 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10895 } 10896 10897 if (mSuccess) { 10898 final boolean mounted; 10899 if (Environment.isExternalStorageEmulated()) { 10900 mounted = true; 10901 } else { 10902 final String status = Environment.getExternalStorageState(); 10903 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10904 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10905 } 10906 10907 if (mounted) { 10908 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10909 10910 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10911 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10912 10913 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10914 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10915 10916 // Always subtract cache size, since it's a subdirectory 10917 mStats.externalDataSize -= mStats.externalCacheSize; 10918 10919 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10920 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10921 10922 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10923 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10924 } 10925 } 10926 } 10927 10928 @Override 10929 void handleReturnCode() { 10930 if (mObserver != null) { 10931 try { 10932 mObserver.onGetStatsCompleted(mStats, mSuccess); 10933 } catch (RemoteException e) { 10934 Slog.i(TAG, "Observer no longer exists."); 10935 } 10936 } 10937 } 10938 10939 @Override 10940 void handleServiceError() { 10941 Slog.e(TAG, "Could not measure application " + mStats.packageName 10942 + " external storage"); 10943 } 10944 } 10945 10946 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10947 throws RemoteException { 10948 long result = 0; 10949 for (File path : paths) { 10950 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10951 } 10952 return result; 10953 } 10954 10955 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10956 for (File path : paths) { 10957 try { 10958 mcs.clearDirectory(path.getAbsolutePath()); 10959 } catch (RemoteException e) { 10960 } 10961 } 10962 } 10963 10964 static class OriginInfo { 10965 /** 10966 * Location where install is coming from, before it has been 10967 * copied/renamed into place. This could be a single monolithic APK 10968 * file, or a cluster directory. This location may be untrusted. 10969 */ 10970 final File file; 10971 final String cid; 10972 10973 /** 10974 * Flag indicating that {@link #file} or {@link #cid} has already been 10975 * staged, meaning downstream users don't need to defensively copy the 10976 * contents. 10977 */ 10978 final boolean staged; 10979 10980 /** 10981 * Flag indicating that {@link #file} or {@link #cid} is an already 10982 * installed app that is being moved. 10983 */ 10984 final boolean existing; 10985 10986 final String resolvedPath; 10987 final File resolvedFile; 10988 10989 static OriginInfo fromNothing() { 10990 return new OriginInfo(null, null, false, false); 10991 } 10992 10993 static OriginInfo fromUntrustedFile(File file) { 10994 return new OriginInfo(file, null, false, false); 10995 } 10996 10997 static OriginInfo fromExistingFile(File file) { 10998 return new OriginInfo(file, null, false, true); 10999 } 11000 11001 static OriginInfo fromStagedFile(File file) { 11002 return new OriginInfo(file, null, true, false); 11003 } 11004 11005 static OriginInfo fromStagedContainer(String cid) { 11006 return new OriginInfo(null, cid, true, false); 11007 } 11008 11009 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 11010 this.file = file; 11011 this.cid = cid; 11012 this.staged = staged; 11013 this.existing = existing; 11014 11015 if (cid != null) { 11016 resolvedPath = PackageHelper.getSdDir(cid); 11017 resolvedFile = new File(resolvedPath); 11018 } else if (file != null) { 11019 resolvedPath = file.getAbsolutePath(); 11020 resolvedFile = file; 11021 } else { 11022 resolvedPath = null; 11023 resolvedFile = null; 11024 } 11025 } 11026 } 11027 11028 static class MoveInfo { 11029 final int moveId; 11030 final String fromUuid; 11031 final String toUuid; 11032 final String packageName; 11033 final String dataAppName; 11034 final int appId; 11035 final String seinfo; 11036 final int targetSdkVersion; 11037 11038 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 11039 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 11040 this.moveId = moveId; 11041 this.fromUuid = fromUuid; 11042 this.toUuid = toUuid; 11043 this.packageName = packageName; 11044 this.dataAppName = dataAppName; 11045 this.appId = appId; 11046 this.seinfo = seinfo; 11047 this.targetSdkVersion = targetSdkVersion; 11048 } 11049 } 11050 11051 class InstallParams extends HandlerParams { 11052 final OriginInfo origin; 11053 final MoveInfo move; 11054 final IPackageInstallObserver2 observer; 11055 int installFlags; 11056 final String installerPackageName; 11057 final String volumeUuid; 11058 final VerificationParams verificationParams; 11059 private InstallArgs mArgs; 11060 private int mRet; 11061 final String packageAbiOverride; 11062 final String[] grantedRuntimePermissions; 11063 11064 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11065 int installFlags, String installerPackageName, String volumeUuid, 11066 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 11067 String[] grantedPermissions) { 11068 super(user); 11069 this.origin = origin; 11070 this.move = move; 11071 this.observer = observer; 11072 this.installFlags = installFlags; 11073 this.installerPackageName = installerPackageName; 11074 this.volumeUuid = volumeUuid; 11075 this.verificationParams = verificationParams; 11076 this.packageAbiOverride = packageAbiOverride; 11077 this.grantedRuntimePermissions = grantedPermissions; 11078 } 11079 11080 @Override 11081 public String toString() { 11082 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11083 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11084 } 11085 11086 private int installLocationPolicy(PackageInfoLite pkgLite) { 11087 String packageName = pkgLite.packageName; 11088 int installLocation = pkgLite.installLocation; 11089 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11090 // reader 11091 synchronized (mPackages) { 11092 PackageParser.Package pkg = mPackages.get(packageName); 11093 if (pkg != null) { 11094 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11095 // Check for downgrading. 11096 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 11097 try { 11098 checkDowngrade(pkg, pkgLite); 11099 } catch (PackageManagerException e) { 11100 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11101 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11102 } 11103 } 11104 // Check for updated system application. 11105 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11106 if (onSd) { 11107 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11108 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11109 } 11110 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11111 } else { 11112 if (onSd) { 11113 // Install flag overrides everything. 11114 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11115 } 11116 // If current upgrade specifies particular preference 11117 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11118 // Application explicitly specified internal. 11119 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11120 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11121 // App explictly prefers external. Let policy decide 11122 } else { 11123 // Prefer previous location 11124 if (isExternal(pkg)) { 11125 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11126 } 11127 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11128 } 11129 } 11130 } else { 11131 // Invalid install. Return error code 11132 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11133 } 11134 } 11135 } 11136 // All the special cases have been taken care of. 11137 // Return result based on recommended install location. 11138 if (onSd) { 11139 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11140 } 11141 return pkgLite.recommendedInstallLocation; 11142 } 11143 11144 /* 11145 * Invoke remote method to get package information and install 11146 * location values. Override install location based on default 11147 * policy if needed and then create install arguments based 11148 * on the install location. 11149 */ 11150 public void handleStartCopy() throws RemoteException { 11151 int ret = PackageManager.INSTALL_SUCCEEDED; 11152 11153 // If we're already staged, we've firmly committed to an install location 11154 if (origin.staged) { 11155 if (origin.file != null) { 11156 installFlags |= PackageManager.INSTALL_INTERNAL; 11157 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11158 } else if (origin.cid != null) { 11159 installFlags |= PackageManager.INSTALL_EXTERNAL; 11160 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11161 } else { 11162 throw new IllegalStateException("Invalid stage location"); 11163 } 11164 } 11165 11166 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11167 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11168 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11169 PackageInfoLite pkgLite = null; 11170 11171 if (onInt && onSd) { 11172 // Check if both bits are set. 11173 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11174 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11175 } else if (onSd && ephemeral) { 11176 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11177 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11178 } else { 11179 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11180 packageAbiOverride); 11181 11182 if (DEBUG_EPHEMERAL && ephemeral) { 11183 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11184 } 11185 11186 /* 11187 * If we have too little free space, try to free cache 11188 * before giving up. 11189 */ 11190 if (!origin.staged && pkgLite.recommendedInstallLocation 11191 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11192 // TODO: focus freeing disk space on the target device 11193 final StorageManager storage = StorageManager.from(mContext); 11194 final long lowThreshold = storage.getStorageLowBytes( 11195 Environment.getDataDirectory()); 11196 11197 final long sizeBytes = mContainerService.calculateInstalledSize( 11198 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11199 11200 try { 11201 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11202 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11203 installFlags, packageAbiOverride); 11204 } catch (InstallerException e) { 11205 Slog.w(TAG, "Failed to free cache", e); 11206 } 11207 11208 /* 11209 * The cache free must have deleted the file we 11210 * downloaded to install. 11211 * 11212 * TODO: fix the "freeCache" call to not delete 11213 * the file we care about. 11214 */ 11215 if (pkgLite.recommendedInstallLocation 11216 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11217 pkgLite.recommendedInstallLocation 11218 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11219 } 11220 } 11221 } 11222 11223 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11224 int loc = pkgLite.recommendedInstallLocation; 11225 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11226 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11227 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11228 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11229 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11230 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11231 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11232 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11233 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11234 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11235 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11236 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11237 } else { 11238 // Override with defaults if needed. 11239 loc = installLocationPolicy(pkgLite); 11240 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11241 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11242 } else if (!onSd && !onInt) { 11243 // Override install location with flags 11244 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11245 // Set the flag to install on external media. 11246 installFlags |= PackageManager.INSTALL_EXTERNAL; 11247 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11248 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11249 if (DEBUG_EPHEMERAL) { 11250 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11251 } 11252 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11253 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11254 |PackageManager.INSTALL_INTERNAL); 11255 } else { 11256 // Make sure the flag for installing on external 11257 // media is unset 11258 installFlags |= PackageManager.INSTALL_INTERNAL; 11259 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11260 } 11261 } 11262 } 11263 } 11264 11265 final InstallArgs args = createInstallArgs(this); 11266 mArgs = args; 11267 11268 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11269 // TODO: http://b/22976637 11270 // Apps installed for "all" users use the device owner to verify the app 11271 UserHandle verifierUser = getUser(); 11272 if (verifierUser == UserHandle.ALL) { 11273 verifierUser = UserHandle.SYSTEM; 11274 } 11275 11276 /* 11277 * Determine if we have any installed package verifiers. If we 11278 * do, then we'll defer to them to verify the packages. 11279 */ 11280 final int requiredUid = mRequiredVerifierPackage == null ? -1 11281 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11282 verifierUser.getIdentifier()); 11283 if (!origin.existing && requiredUid != -1 11284 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11285 final Intent verification = new Intent( 11286 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11287 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11288 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11289 PACKAGE_MIME_TYPE); 11290 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11291 11292 // Query all live verifiers based on current user state 11293 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11294 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11295 11296 if (DEBUG_VERIFY) { 11297 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11298 + verification.toString() + " with " + pkgLite.verifiers.length 11299 + " optional verifiers"); 11300 } 11301 11302 final int verificationId = mPendingVerificationToken++; 11303 11304 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11305 11306 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11307 installerPackageName); 11308 11309 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11310 installFlags); 11311 11312 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11313 pkgLite.packageName); 11314 11315 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11316 pkgLite.versionCode); 11317 11318 if (verificationParams != null) { 11319 if (verificationParams.getVerificationURI() != null) { 11320 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11321 verificationParams.getVerificationURI()); 11322 } 11323 if (verificationParams.getOriginatingURI() != null) { 11324 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11325 verificationParams.getOriginatingURI()); 11326 } 11327 if (verificationParams.getReferrer() != null) { 11328 verification.putExtra(Intent.EXTRA_REFERRER, 11329 verificationParams.getReferrer()); 11330 } 11331 if (verificationParams.getOriginatingUid() >= 0) { 11332 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11333 verificationParams.getOriginatingUid()); 11334 } 11335 if (verificationParams.getInstallerUid() >= 0) { 11336 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11337 verificationParams.getInstallerUid()); 11338 } 11339 } 11340 11341 final PackageVerificationState verificationState = new PackageVerificationState( 11342 requiredUid, args); 11343 11344 mPendingVerification.append(verificationId, verificationState); 11345 11346 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11347 receivers, verificationState); 11348 11349 /* 11350 * If any sufficient verifiers were listed in the package 11351 * manifest, attempt to ask them. 11352 */ 11353 if (sufficientVerifiers != null) { 11354 final int N = sufficientVerifiers.size(); 11355 if (N == 0) { 11356 Slog.i(TAG, "Additional verifiers required, but none installed."); 11357 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11358 } else { 11359 for (int i = 0; i < N; i++) { 11360 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11361 11362 final Intent sufficientIntent = new Intent(verification); 11363 sufficientIntent.setComponent(verifierComponent); 11364 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11365 } 11366 } 11367 } 11368 11369 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11370 mRequiredVerifierPackage, receivers); 11371 if (ret == PackageManager.INSTALL_SUCCEEDED 11372 && mRequiredVerifierPackage != null) { 11373 Trace.asyncTraceBegin( 11374 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11375 /* 11376 * Send the intent to the required verification agent, 11377 * but only start the verification timeout after the 11378 * target BroadcastReceivers have run. 11379 */ 11380 verification.setComponent(requiredVerifierComponent); 11381 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11382 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11383 new BroadcastReceiver() { 11384 @Override 11385 public void onReceive(Context context, Intent intent) { 11386 final Message msg = mHandler 11387 .obtainMessage(CHECK_PENDING_VERIFICATION); 11388 msg.arg1 = verificationId; 11389 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11390 } 11391 }, null, 0, null, null); 11392 11393 /* 11394 * We don't want the copy to proceed until verification 11395 * succeeds, so null out this field. 11396 */ 11397 mArgs = null; 11398 } 11399 } else { 11400 /* 11401 * No package verification is enabled, so immediately start 11402 * the remote call to initiate copy using temporary file. 11403 */ 11404 ret = args.copyApk(mContainerService, true); 11405 } 11406 } 11407 11408 mRet = ret; 11409 } 11410 11411 @Override 11412 void handleReturnCode() { 11413 // If mArgs is null, then MCS couldn't be reached. When it 11414 // reconnects, it will try again to install. At that point, this 11415 // will succeed. 11416 if (mArgs != null) { 11417 processPendingInstall(mArgs, mRet); 11418 } 11419 } 11420 11421 @Override 11422 void handleServiceError() { 11423 mArgs = createInstallArgs(this); 11424 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11425 } 11426 11427 public boolean isForwardLocked() { 11428 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11429 } 11430 } 11431 11432 /** 11433 * Used during creation of InstallArgs 11434 * 11435 * @param installFlags package installation flags 11436 * @return true if should be installed on external storage 11437 */ 11438 private static boolean installOnExternalAsec(int installFlags) { 11439 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11440 return false; 11441 } 11442 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11443 return true; 11444 } 11445 return false; 11446 } 11447 11448 /** 11449 * Used during creation of InstallArgs 11450 * 11451 * @param installFlags package installation flags 11452 * @return true if should be installed as forward locked 11453 */ 11454 private static boolean installForwardLocked(int installFlags) { 11455 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11456 } 11457 11458 private InstallArgs createInstallArgs(InstallParams params) { 11459 if (params.move != null) { 11460 return new MoveInstallArgs(params); 11461 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11462 return new AsecInstallArgs(params); 11463 } else { 11464 return new FileInstallArgs(params); 11465 } 11466 } 11467 11468 /** 11469 * Create args that describe an existing installed package. Typically used 11470 * when cleaning up old installs, or used as a move source. 11471 */ 11472 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11473 String resourcePath, String[] instructionSets) { 11474 final boolean isInAsec; 11475 if (installOnExternalAsec(installFlags)) { 11476 /* Apps on SD card are always in ASEC containers. */ 11477 isInAsec = true; 11478 } else if (installForwardLocked(installFlags) 11479 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11480 /* 11481 * Forward-locked apps are only in ASEC containers if they're the 11482 * new style 11483 */ 11484 isInAsec = true; 11485 } else { 11486 isInAsec = false; 11487 } 11488 11489 if (isInAsec) { 11490 return new AsecInstallArgs(codePath, instructionSets, 11491 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11492 } else { 11493 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11494 } 11495 } 11496 11497 static abstract class InstallArgs { 11498 /** @see InstallParams#origin */ 11499 final OriginInfo origin; 11500 /** @see InstallParams#move */ 11501 final MoveInfo move; 11502 11503 final IPackageInstallObserver2 observer; 11504 // Always refers to PackageManager flags only 11505 final int installFlags; 11506 final String installerPackageName; 11507 final String volumeUuid; 11508 final UserHandle user; 11509 final String abiOverride; 11510 final String[] installGrantPermissions; 11511 /** If non-null, drop an async trace when the install completes */ 11512 final String traceMethod; 11513 final int traceCookie; 11514 11515 // The list of instruction sets supported by this app. This is currently 11516 // only used during the rmdex() phase to clean up resources. We can get rid of this 11517 // if we move dex files under the common app path. 11518 /* nullable */ String[] instructionSets; 11519 11520 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11521 int installFlags, String installerPackageName, String volumeUuid, 11522 UserHandle user, String[] instructionSets, 11523 String abiOverride, String[] installGrantPermissions, 11524 String traceMethod, int traceCookie) { 11525 this.origin = origin; 11526 this.move = move; 11527 this.installFlags = installFlags; 11528 this.observer = observer; 11529 this.installerPackageName = installerPackageName; 11530 this.volumeUuid = volumeUuid; 11531 this.user = user; 11532 this.instructionSets = instructionSets; 11533 this.abiOverride = abiOverride; 11534 this.installGrantPermissions = installGrantPermissions; 11535 this.traceMethod = traceMethod; 11536 this.traceCookie = traceCookie; 11537 } 11538 11539 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11540 abstract int doPreInstall(int status); 11541 11542 /** 11543 * Rename package into final resting place. All paths on the given 11544 * scanned package should be updated to reflect the rename. 11545 */ 11546 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11547 abstract int doPostInstall(int status, int uid); 11548 11549 /** @see PackageSettingBase#codePathString */ 11550 abstract String getCodePath(); 11551 /** @see PackageSettingBase#resourcePathString */ 11552 abstract String getResourcePath(); 11553 11554 // Need installer lock especially for dex file removal. 11555 abstract void cleanUpResourcesLI(); 11556 abstract boolean doPostDeleteLI(boolean delete); 11557 11558 /** 11559 * Called before the source arguments are copied. This is used mostly 11560 * for MoveParams when it needs to read the source file to put it in the 11561 * destination. 11562 */ 11563 int doPreCopy() { 11564 return PackageManager.INSTALL_SUCCEEDED; 11565 } 11566 11567 /** 11568 * Called after the source arguments are copied. This is used mostly for 11569 * MoveParams when it needs to read the source file to put it in the 11570 * destination. 11571 * 11572 * @return 11573 */ 11574 int doPostCopy(int uid) { 11575 return PackageManager.INSTALL_SUCCEEDED; 11576 } 11577 11578 protected boolean isFwdLocked() { 11579 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11580 } 11581 11582 protected boolean isExternalAsec() { 11583 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11584 } 11585 11586 protected boolean isEphemeral() { 11587 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11588 } 11589 11590 UserHandle getUser() { 11591 return user; 11592 } 11593 } 11594 11595 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11596 if (!allCodePaths.isEmpty()) { 11597 if (instructionSets == null) { 11598 throw new IllegalStateException("instructionSet == null"); 11599 } 11600 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11601 for (String codePath : allCodePaths) { 11602 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11603 try { 11604 mInstaller.rmdex(codePath, dexCodeInstructionSet); 11605 } catch (InstallerException ignored) { 11606 } 11607 } 11608 } 11609 } 11610 } 11611 11612 /** 11613 * Logic to handle installation of non-ASEC applications, including copying 11614 * and renaming logic. 11615 */ 11616 class FileInstallArgs extends InstallArgs { 11617 private File codeFile; 11618 private File resourceFile; 11619 11620 // Example topology: 11621 // /data/app/com.example/base.apk 11622 // /data/app/com.example/split_foo.apk 11623 // /data/app/com.example/lib/arm/libfoo.so 11624 // /data/app/com.example/lib/arm64/libfoo.so 11625 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11626 11627 /** New install */ 11628 FileInstallArgs(InstallParams params) { 11629 super(params.origin, params.move, params.observer, params.installFlags, 11630 params.installerPackageName, params.volumeUuid, 11631 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11632 params.grantedRuntimePermissions, 11633 params.traceMethod, params.traceCookie); 11634 if (isFwdLocked()) { 11635 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11636 } 11637 } 11638 11639 /** Existing install */ 11640 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11641 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 11642 null, null, null, 0); 11643 this.codeFile = (codePath != null) ? new File(codePath) : null; 11644 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11645 } 11646 11647 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11648 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11649 try { 11650 return doCopyApk(imcs, temp); 11651 } finally { 11652 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11653 } 11654 } 11655 11656 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11657 if (origin.staged) { 11658 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11659 codeFile = origin.file; 11660 resourceFile = origin.file; 11661 return PackageManager.INSTALL_SUCCEEDED; 11662 } 11663 11664 try { 11665 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11666 final File tempDir = 11667 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 11668 codeFile = tempDir; 11669 resourceFile = tempDir; 11670 } catch (IOException e) { 11671 Slog.w(TAG, "Failed to create copy file: " + e); 11672 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11673 } 11674 11675 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11676 @Override 11677 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11678 if (!FileUtils.isValidExtFilename(name)) { 11679 throw new IllegalArgumentException("Invalid filename: " + name); 11680 } 11681 try { 11682 final File file = new File(codeFile, name); 11683 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11684 O_RDWR | O_CREAT, 0644); 11685 Os.chmod(file.getAbsolutePath(), 0644); 11686 return new ParcelFileDescriptor(fd); 11687 } catch (ErrnoException e) { 11688 throw new RemoteException("Failed to open: " + e.getMessage()); 11689 } 11690 } 11691 }; 11692 11693 int ret = PackageManager.INSTALL_SUCCEEDED; 11694 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11695 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11696 Slog.e(TAG, "Failed to copy package"); 11697 return ret; 11698 } 11699 11700 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11701 NativeLibraryHelper.Handle handle = null; 11702 try { 11703 handle = NativeLibraryHelper.Handle.create(codeFile); 11704 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11705 abiOverride); 11706 } catch (IOException e) { 11707 Slog.e(TAG, "Copying native libraries failed", e); 11708 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11709 } finally { 11710 IoUtils.closeQuietly(handle); 11711 } 11712 11713 return ret; 11714 } 11715 11716 int doPreInstall(int status) { 11717 if (status != PackageManager.INSTALL_SUCCEEDED) { 11718 cleanUp(); 11719 } 11720 return status; 11721 } 11722 11723 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11724 if (status != PackageManager.INSTALL_SUCCEEDED) { 11725 cleanUp(); 11726 return false; 11727 } 11728 11729 final File targetDir = codeFile.getParentFile(); 11730 final File beforeCodeFile = codeFile; 11731 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11732 11733 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11734 try { 11735 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11736 } catch (ErrnoException e) { 11737 Slog.w(TAG, "Failed to rename", e); 11738 return false; 11739 } 11740 11741 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11742 Slog.w(TAG, "Failed to restorecon"); 11743 return false; 11744 } 11745 11746 // Reflect the rename internally 11747 codeFile = afterCodeFile; 11748 resourceFile = afterCodeFile; 11749 11750 // Reflect the rename in scanned details 11751 pkg.codePath = afterCodeFile.getAbsolutePath(); 11752 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11753 pkg.baseCodePath); 11754 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11755 pkg.splitCodePaths); 11756 11757 // Reflect the rename in app info 11758 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11759 pkg.applicationInfo.setCodePath(pkg.codePath); 11760 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11761 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11762 pkg.applicationInfo.setResourcePath(pkg.codePath); 11763 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11764 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11765 11766 return true; 11767 } 11768 11769 int doPostInstall(int status, int uid) { 11770 if (status != PackageManager.INSTALL_SUCCEEDED) { 11771 cleanUp(); 11772 } 11773 return status; 11774 } 11775 11776 @Override 11777 String getCodePath() { 11778 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11779 } 11780 11781 @Override 11782 String getResourcePath() { 11783 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11784 } 11785 11786 private boolean cleanUp() { 11787 if (codeFile == null || !codeFile.exists()) { 11788 return false; 11789 } 11790 11791 removeCodePathLI(codeFile); 11792 11793 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11794 resourceFile.delete(); 11795 } 11796 11797 return true; 11798 } 11799 11800 void cleanUpResourcesLI() { 11801 // Try enumerating all code paths before deleting 11802 List<String> allCodePaths = Collections.EMPTY_LIST; 11803 if (codeFile != null && codeFile.exists()) { 11804 try { 11805 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11806 allCodePaths = pkg.getAllCodePaths(); 11807 } catch (PackageParserException e) { 11808 // Ignored; we tried our best 11809 } 11810 } 11811 11812 cleanUp(); 11813 removeDexFiles(allCodePaths, instructionSets); 11814 } 11815 11816 boolean doPostDeleteLI(boolean delete) { 11817 // XXX err, shouldn't we respect the delete flag? 11818 cleanUpResourcesLI(); 11819 return true; 11820 } 11821 } 11822 11823 private boolean isAsecExternal(String cid) { 11824 final String asecPath = PackageHelper.getSdFilesystem(cid); 11825 return !asecPath.startsWith(mAsecInternalPath); 11826 } 11827 11828 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11829 PackageManagerException { 11830 if (copyRet < 0) { 11831 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11832 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11833 throw new PackageManagerException(copyRet, message); 11834 } 11835 } 11836 } 11837 11838 /** 11839 * Extract the MountService "container ID" from the full code path of an 11840 * .apk. 11841 */ 11842 static String cidFromCodePath(String fullCodePath) { 11843 int eidx = fullCodePath.lastIndexOf("/"); 11844 String subStr1 = fullCodePath.substring(0, eidx); 11845 int sidx = subStr1.lastIndexOf("/"); 11846 return subStr1.substring(sidx+1, eidx); 11847 } 11848 11849 /** 11850 * Logic to handle installation of ASEC applications, including copying and 11851 * renaming logic. 11852 */ 11853 class AsecInstallArgs extends InstallArgs { 11854 static final String RES_FILE_NAME = "pkg.apk"; 11855 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11856 11857 String cid; 11858 String packagePath; 11859 String resourcePath; 11860 11861 /** New install */ 11862 AsecInstallArgs(InstallParams params) { 11863 super(params.origin, params.move, params.observer, params.installFlags, 11864 params.installerPackageName, params.volumeUuid, 11865 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11866 params.grantedRuntimePermissions, 11867 params.traceMethod, params.traceCookie); 11868 } 11869 11870 /** Existing install */ 11871 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11872 boolean isExternal, boolean isForwardLocked) { 11873 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11874 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11875 instructionSets, null, null, null, 0); 11876 // Hackily pretend we're still looking at a full code path 11877 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11878 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11879 } 11880 11881 // Extract cid from fullCodePath 11882 int eidx = fullCodePath.lastIndexOf("/"); 11883 String subStr1 = fullCodePath.substring(0, eidx); 11884 int sidx = subStr1.lastIndexOf("/"); 11885 cid = subStr1.substring(sidx+1, eidx); 11886 setMountPath(subStr1); 11887 } 11888 11889 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11890 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11891 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11892 instructionSets, null, null, null, 0); 11893 this.cid = cid; 11894 setMountPath(PackageHelper.getSdDir(cid)); 11895 } 11896 11897 void createCopyFile() { 11898 cid = mInstallerService.allocateExternalStageCidLegacy(); 11899 } 11900 11901 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11902 if (origin.staged && origin.cid != null) { 11903 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11904 cid = origin.cid; 11905 setMountPath(PackageHelper.getSdDir(cid)); 11906 return PackageManager.INSTALL_SUCCEEDED; 11907 } 11908 11909 if (temp) { 11910 createCopyFile(); 11911 } else { 11912 /* 11913 * Pre-emptively destroy the container since it's destroyed if 11914 * copying fails due to it existing anyway. 11915 */ 11916 PackageHelper.destroySdDir(cid); 11917 } 11918 11919 final String newMountPath = imcs.copyPackageToContainer( 11920 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11921 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11922 11923 if (newMountPath != null) { 11924 setMountPath(newMountPath); 11925 return PackageManager.INSTALL_SUCCEEDED; 11926 } else { 11927 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11928 } 11929 } 11930 11931 @Override 11932 String getCodePath() { 11933 return packagePath; 11934 } 11935 11936 @Override 11937 String getResourcePath() { 11938 return resourcePath; 11939 } 11940 11941 int doPreInstall(int status) { 11942 if (status != PackageManager.INSTALL_SUCCEEDED) { 11943 // Destroy container 11944 PackageHelper.destroySdDir(cid); 11945 } else { 11946 boolean mounted = PackageHelper.isContainerMounted(cid); 11947 if (!mounted) { 11948 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11949 Process.SYSTEM_UID); 11950 if (newMountPath != null) { 11951 setMountPath(newMountPath); 11952 } else { 11953 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11954 } 11955 } 11956 } 11957 return status; 11958 } 11959 11960 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11961 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11962 String newMountPath = null; 11963 if (PackageHelper.isContainerMounted(cid)) { 11964 // Unmount the container 11965 if (!PackageHelper.unMountSdDir(cid)) { 11966 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11967 return false; 11968 } 11969 } 11970 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11971 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11972 " which might be stale. Will try to clean up."); 11973 // Clean up the stale container and proceed to recreate. 11974 if (!PackageHelper.destroySdDir(newCacheId)) { 11975 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11976 return false; 11977 } 11978 // Successfully cleaned up stale container. Try to rename again. 11979 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11980 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11981 + " inspite of cleaning it up."); 11982 return false; 11983 } 11984 } 11985 if (!PackageHelper.isContainerMounted(newCacheId)) { 11986 Slog.w(TAG, "Mounting container " + newCacheId); 11987 newMountPath = PackageHelper.mountSdDir(newCacheId, 11988 getEncryptKey(), Process.SYSTEM_UID); 11989 } else { 11990 newMountPath = PackageHelper.getSdDir(newCacheId); 11991 } 11992 if (newMountPath == null) { 11993 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11994 return false; 11995 } 11996 Log.i(TAG, "Succesfully renamed " + cid + 11997 " to " + newCacheId + 11998 " at new path: " + newMountPath); 11999 cid = newCacheId; 12000 12001 final File beforeCodeFile = new File(packagePath); 12002 setMountPath(newMountPath); 12003 final File afterCodeFile = new File(packagePath); 12004 12005 // Reflect the rename in scanned details 12006 pkg.codePath = afterCodeFile.getAbsolutePath(); 12007 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 12008 pkg.baseCodePath); 12009 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 12010 pkg.splitCodePaths); 12011 12012 // Reflect the rename in app info 12013 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 12014 pkg.applicationInfo.setCodePath(pkg.codePath); 12015 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 12016 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 12017 pkg.applicationInfo.setResourcePath(pkg.codePath); 12018 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 12019 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 12020 12021 return true; 12022 } 12023 12024 private void setMountPath(String mountPath) { 12025 final File mountFile = new File(mountPath); 12026 12027 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 12028 if (monolithicFile.exists()) { 12029 packagePath = monolithicFile.getAbsolutePath(); 12030 if (isFwdLocked()) { 12031 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 12032 } else { 12033 resourcePath = packagePath; 12034 } 12035 } else { 12036 packagePath = mountFile.getAbsolutePath(); 12037 resourcePath = packagePath; 12038 } 12039 } 12040 12041 int doPostInstall(int status, int uid) { 12042 if (status != PackageManager.INSTALL_SUCCEEDED) { 12043 cleanUp(); 12044 } else { 12045 final int groupOwner; 12046 final String protectedFile; 12047 if (isFwdLocked()) { 12048 groupOwner = UserHandle.getSharedAppGid(uid); 12049 protectedFile = RES_FILE_NAME; 12050 } else { 12051 groupOwner = -1; 12052 protectedFile = null; 12053 } 12054 12055 if (uid < Process.FIRST_APPLICATION_UID 12056 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 12057 Slog.e(TAG, "Failed to finalize " + cid); 12058 PackageHelper.destroySdDir(cid); 12059 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12060 } 12061 12062 boolean mounted = PackageHelper.isContainerMounted(cid); 12063 if (!mounted) { 12064 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12065 } 12066 } 12067 return status; 12068 } 12069 12070 private void cleanUp() { 12071 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12072 12073 // Destroy secure container 12074 PackageHelper.destroySdDir(cid); 12075 } 12076 12077 private List<String> getAllCodePaths() { 12078 final File codeFile = new File(getCodePath()); 12079 if (codeFile != null && codeFile.exists()) { 12080 try { 12081 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12082 return pkg.getAllCodePaths(); 12083 } catch (PackageParserException e) { 12084 // Ignored; we tried our best 12085 } 12086 } 12087 return Collections.EMPTY_LIST; 12088 } 12089 12090 void cleanUpResourcesLI() { 12091 // Enumerate all code paths before deleting 12092 cleanUpResourcesLI(getAllCodePaths()); 12093 } 12094 12095 private void cleanUpResourcesLI(List<String> allCodePaths) { 12096 cleanUp(); 12097 removeDexFiles(allCodePaths, instructionSets); 12098 } 12099 12100 String getPackageName() { 12101 return getAsecPackageName(cid); 12102 } 12103 12104 boolean doPostDeleteLI(boolean delete) { 12105 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12106 final List<String> allCodePaths = getAllCodePaths(); 12107 boolean mounted = PackageHelper.isContainerMounted(cid); 12108 if (mounted) { 12109 // Unmount first 12110 if (PackageHelper.unMountSdDir(cid)) { 12111 mounted = false; 12112 } 12113 } 12114 if (!mounted && delete) { 12115 cleanUpResourcesLI(allCodePaths); 12116 } 12117 return !mounted; 12118 } 12119 12120 @Override 12121 int doPreCopy() { 12122 if (isFwdLocked()) { 12123 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12124 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12125 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12126 } 12127 } 12128 12129 return PackageManager.INSTALL_SUCCEEDED; 12130 } 12131 12132 @Override 12133 int doPostCopy(int uid) { 12134 if (isFwdLocked()) { 12135 if (uid < Process.FIRST_APPLICATION_UID 12136 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12137 RES_FILE_NAME)) { 12138 Slog.e(TAG, "Failed to finalize " + cid); 12139 PackageHelper.destroySdDir(cid); 12140 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12141 } 12142 } 12143 12144 return PackageManager.INSTALL_SUCCEEDED; 12145 } 12146 } 12147 12148 /** 12149 * Logic to handle movement of existing installed applications. 12150 */ 12151 class MoveInstallArgs extends InstallArgs { 12152 private File codeFile; 12153 private File resourceFile; 12154 12155 /** New install */ 12156 MoveInstallArgs(InstallParams params) { 12157 super(params.origin, params.move, params.observer, params.installFlags, 12158 params.installerPackageName, params.volumeUuid, 12159 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12160 params.grantedRuntimePermissions, 12161 params.traceMethod, params.traceCookie); 12162 } 12163 12164 int copyApk(IMediaContainerService imcs, boolean temp) { 12165 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12166 + move.fromUuid + " to " + move.toUuid); 12167 synchronized (mInstaller) { 12168 try { 12169 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12170 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12171 } catch (InstallerException e) { 12172 Slog.w(TAG, "Failed to move app", e); 12173 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12174 } 12175 } 12176 12177 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12178 resourceFile = codeFile; 12179 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12180 12181 return PackageManager.INSTALL_SUCCEEDED; 12182 } 12183 12184 int doPreInstall(int status) { 12185 if (status != PackageManager.INSTALL_SUCCEEDED) { 12186 cleanUp(move.toUuid); 12187 } 12188 return status; 12189 } 12190 12191 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12192 if (status != PackageManager.INSTALL_SUCCEEDED) { 12193 cleanUp(move.toUuid); 12194 return false; 12195 } 12196 12197 // Reflect the move in app info 12198 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 12199 pkg.applicationInfo.setCodePath(pkg.codePath); 12200 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 12201 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 12202 pkg.applicationInfo.setResourcePath(pkg.codePath); 12203 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 12204 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 12205 12206 return true; 12207 } 12208 12209 int doPostInstall(int status, int uid) { 12210 if (status == PackageManager.INSTALL_SUCCEEDED) { 12211 cleanUp(move.fromUuid); 12212 } else { 12213 cleanUp(move.toUuid); 12214 } 12215 return status; 12216 } 12217 12218 @Override 12219 String getCodePath() { 12220 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12221 } 12222 12223 @Override 12224 String getResourcePath() { 12225 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12226 } 12227 12228 private boolean cleanUp(String volumeUuid) { 12229 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12230 move.dataAppName); 12231 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12232 synchronized (mInstallLock) { 12233 // Clean up both app data and code 12234 removeDataDirsLI(volumeUuid, move.packageName); 12235 removeCodePathLI(codeFile); 12236 } 12237 return true; 12238 } 12239 12240 void cleanUpResourcesLI() { 12241 throw new UnsupportedOperationException(); 12242 } 12243 12244 boolean doPostDeleteLI(boolean delete) { 12245 throw new UnsupportedOperationException(); 12246 } 12247 } 12248 12249 static String getAsecPackageName(String packageCid) { 12250 int idx = packageCid.lastIndexOf("-"); 12251 if (idx == -1) { 12252 return packageCid; 12253 } 12254 return packageCid.substring(0, idx); 12255 } 12256 12257 // Utility method used to create code paths based on package name and available index. 12258 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12259 String idxStr = ""; 12260 int idx = 1; 12261 // Fall back to default value of idx=1 if prefix is not 12262 // part of oldCodePath 12263 if (oldCodePath != null) { 12264 String subStr = oldCodePath; 12265 // Drop the suffix right away 12266 if (suffix != null && subStr.endsWith(suffix)) { 12267 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12268 } 12269 // If oldCodePath already contains prefix find out the 12270 // ending index to either increment or decrement. 12271 int sidx = subStr.lastIndexOf(prefix); 12272 if (sidx != -1) { 12273 subStr = subStr.substring(sidx + prefix.length()); 12274 if (subStr != null) { 12275 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12276 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12277 } 12278 try { 12279 idx = Integer.parseInt(subStr); 12280 if (idx <= 1) { 12281 idx++; 12282 } else { 12283 idx--; 12284 } 12285 } catch(NumberFormatException e) { 12286 } 12287 } 12288 } 12289 } 12290 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12291 return prefix + idxStr; 12292 } 12293 12294 private File getNextCodePath(File targetDir, String packageName) { 12295 int suffix = 1; 12296 File result; 12297 do { 12298 result = new File(targetDir, packageName + "-" + suffix); 12299 suffix++; 12300 } while (result.exists()); 12301 return result; 12302 } 12303 12304 // Utility method that returns the relative package path with respect 12305 // to the installation directory. Like say for /data/data/com.test-1.apk 12306 // string com.test-1 is returned. 12307 static String deriveCodePathName(String codePath) { 12308 if (codePath == null) { 12309 return null; 12310 } 12311 final File codeFile = new File(codePath); 12312 final String name = codeFile.getName(); 12313 if (codeFile.isDirectory()) { 12314 return name; 12315 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12316 final int lastDot = name.lastIndexOf('.'); 12317 return name.substring(0, lastDot); 12318 } else { 12319 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12320 return null; 12321 } 12322 } 12323 12324 static class PackageInstalledInfo { 12325 String name; 12326 int uid; 12327 // The set of users that originally had this package installed. 12328 int[] origUsers; 12329 // The set of users that now have this package installed. 12330 int[] newUsers; 12331 PackageParser.Package pkg; 12332 int returnCode; 12333 String returnMsg; 12334 PackageRemovedInfo removedInfo; 12335 12336 public void setError(int code, String msg) { 12337 returnCode = code; 12338 returnMsg = msg; 12339 Slog.w(TAG, msg); 12340 } 12341 12342 public void setError(String msg, PackageParserException e) { 12343 returnCode = e.error; 12344 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12345 Slog.w(TAG, msg, e); 12346 } 12347 12348 public void setError(String msg, PackageManagerException e) { 12349 returnCode = e.error; 12350 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12351 Slog.w(TAG, msg, e); 12352 } 12353 12354 // In some error cases we want to convey more info back to the observer 12355 String origPackage; 12356 String origPermission; 12357 } 12358 12359 /* 12360 * Install a non-existing package. 12361 */ 12362 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12363 UserHandle user, String installerPackageName, String volumeUuid, 12364 PackageInstalledInfo res) { 12365 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12366 12367 // Remember this for later, in case we need to rollback this install 12368 String pkgName = pkg.packageName; 12369 12370 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12371 // TODO: b/23350563 12372 final boolean dataDirExists = Environment 12373 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12374 12375 synchronized(mPackages) { 12376 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12377 // A package with the same name is already installed, though 12378 // it has been renamed to an older name. The package we 12379 // are trying to install should be installed as an update to 12380 // the existing one, but that has not been requested, so bail. 12381 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12382 + " without first uninstalling package running as " 12383 + mSettings.mRenamedPackages.get(pkgName)); 12384 return; 12385 } 12386 if (mPackages.containsKey(pkgName)) { 12387 // Don't allow installation over an existing package with the same name. 12388 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12389 + " without first uninstalling."); 12390 return; 12391 } 12392 } 12393 12394 try { 12395 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12396 System.currentTimeMillis(), user); 12397 12398 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12399 prepareAppDataAfterInstall(newPackage); 12400 12401 // delete the partially installed application. the data directory will have to be 12402 // restored if it was already existing 12403 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12404 // remove package from internal structures. Note that we want deletePackageX to 12405 // delete the package data and cache directories that it created in 12406 // scanPackageLocked, unless those directories existed before we even tried to 12407 // install. 12408 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12409 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12410 res.removedInfo, true); 12411 } 12412 12413 } catch (PackageManagerException e) { 12414 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12415 } 12416 12417 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12418 } 12419 12420 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12421 // Can't rotate keys during boot or if sharedUser. 12422 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12423 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12424 return false; 12425 } 12426 // app is using upgradeKeySets; make sure all are valid 12427 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12428 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12429 for (int i = 0; i < upgradeKeySets.length; i++) { 12430 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12431 Slog.wtf(TAG, "Package " 12432 + (oldPs.name != null ? oldPs.name : "<null>") 12433 + " contains upgrade-key-set reference to unknown key-set: " 12434 + upgradeKeySets[i] 12435 + " reverting to signatures check."); 12436 return false; 12437 } 12438 } 12439 return true; 12440 } 12441 12442 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12443 // Upgrade keysets are being used. Determine if new package has a superset of the 12444 // required keys. 12445 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12446 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12447 for (int i = 0; i < upgradeKeySets.length; i++) { 12448 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12449 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12450 return true; 12451 } 12452 } 12453 return false; 12454 } 12455 12456 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12457 UserHandle user, String installerPackageName, String volumeUuid, 12458 PackageInstalledInfo res) { 12459 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12460 12461 final PackageParser.Package oldPackage; 12462 final String pkgName = pkg.packageName; 12463 final int[] allUsers; 12464 final boolean[] perUserInstalled; 12465 12466 // First find the old package info and check signatures 12467 synchronized(mPackages) { 12468 oldPackage = mPackages.get(pkgName); 12469 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12470 if (isEphemeral && !oldIsEphemeral) { 12471 // can't downgrade from full to ephemeral 12472 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12473 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12474 return; 12475 } 12476 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12477 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12478 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12479 if(!checkUpgradeKeySetLP(ps, pkg)) { 12480 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12481 "New package not signed by keys specified by upgrade-keysets: " 12482 + pkgName); 12483 return; 12484 } 12485 } else { 12486 // default to original signature matching 12487 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12488 != PackageManager.SIGNATURE_MATCH) { 12489 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12490 "New package has a different signature: " + pkgName); 12491 return; 12492 } 12493 } 12494 12495 // In case of rollback, remember per-user/profile install state 12496 allUsers = sUserManager.getUserIds(); 12497 perUserInstalled = new boolean[allUsers.length]; 12498 for (int i = 0; i < allUsers.length; i++) { 12499 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12500 } 12501 } 12502 12503 boolean sysPkg = (isSystemApp(oldPackage)); 12504 if (sysPkg) { 12505 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12506 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12507 } else { 12508 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12509 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12510 } 12511 } 12512 12513 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12514 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12515 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12516 String volumeUuid, PackageInstalledInfo res) { 12517 String pkgName = deletedPackage.packageName; 12518 boolean deletedPkg = true; 12519 boolean updatedSettings = false; 12520 12521 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12522 + deletedPackage); 12523 long origUpdateTime; 12524 if (pkg.mExtras != null) { 12525 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12526 } else { 12527 origUpdateTime = 0; 12528 } 12529 12530 // First delete the existing package while retaining the data directory 12531 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12532 res.removedInfo, true)) { 12533 // If the existing package wasn't successfully deleted 12534 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12535 deletedPkg = false; 12536 } else { 12537 // Successfully deleted the old package; proceed with replace. 12538 12539 // If deleted package lived in a container, give users a chance to 12540 // relinquish resources before killing. 12541 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12542 if (DEBUG_INSTALL) { 12543 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12544 } 12545 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12546 final ArrayList<String> pkgList = new ArrayList<String>(1); 12547 pkgList.add(deletedPackage.applicationInfo.packageName); 12548 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12549 } 12550 12551 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12552 try { 12553 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12554 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12555 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12556 perUserInstalled, res, user); 12557 prepareAppDataAfterInstall(newPackage); 12558 updatedSettings = true; 12559 } catch (PackageManagerException e) { 12560 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12561 } 12562 } 12563 12564 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12565 // remove package from internal structures. Note that we want deletePackageX to 12566 // delete the package data and cache directories that it created in 12567 // scanPackageLocked, unless those directories existed before we even tried to 12568 // install. 12569 if(updatedSettings) { 12570 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12571 deletePackageLI( 12572 pkgName, null, true, allUsers, perUserInstalled, 12573 PackageManager.DELETE_KEEP_DATA, 12574 res.removedInfo, true); 12575 } 12576 // Since we failed to install the new package we need to restore the old 12577 // package that we deleted. 12578 if (deletedPkg) { 12579 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12580 File restoreFile = new File(deletedPackage.codePath); 12581 // Parse old package 12582 boolean oldExternal = isExternal(deletedPackage); 12583 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12584 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12585 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12586 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12587 try { 12588 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12589 null); 12590 } catch (PackageManagerException e) { 12591 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12592 + e.getMessage()); 12593 return; 12594 } 12595 // Restore of old package succeeded. Update permissions. 12596 // writer 12597 synchronized (mPackages) { 12598 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12599 UPDATE_PERMISSIONS_ALL); 12600 // can downgrade to reader 12601 mSettings.writeLPr(); 12602 } 12603 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12604 } 12605 } 12606 } 12607 12608 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12609 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12610 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12611 String volumeUuid, PackageInstalledInfo res) { 12612 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12613 + ", old=" + deletedPackage); 12614 boolean disabledSystem = false; 12615 boolean updatedSettings = false; 12616 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12617 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12618 != 0) { 12619 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12620 } 12621 String packageName = deletedPackage.packageName; 12622 if (packageName == null) { 12623 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12624 "Attempt to delete null packageName."); 12625 return; 12626 } 12627 PackageParser.Package oldPkg; 12628 PackageSetting oldPkgSetting; 12629 // reader 12630 synchronized (mPackages) { 12631 oldPkg = mPackages.get(packageName); 12632 oldPkgSetting = mSettings.mPackages.get(packageName); 12633 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12634 (oldPkgSetting == null)) { 12635 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12636 "Couldn't find package " + packageName + " information"); 12637 return; 12638 } 12639 } 12640 12641 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12642 12643 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12644 res.removedInfo.removedPackage = packageName; 12645 // Remove existing system package 12646 removePackageLI(oldPkgSetting, true); 12647 // writer 12648 synchronized (mPackages) { 12649 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12650 if (!disabledSystem && deletedPackage != null) { 12651 // We didn't need to disable the .apk as a current system package, 12652 // which means we are replacing another update that is already 12653 // installed. We need to make sure to delete the older one's .apk. 12654 res.removedInfo.args = createInstallArgsForExisting(0, 12655 deletedPackage.applicationInfo.getCodePath(), 12656 deletedPackage.applicationInfo.getResourcePath(), 12657 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12658 } else { 12659 res.removedInfo.args = null; 12660 } 12661 } 12662 12663 // Successfully disabled the old package. Now proceed with re-installation 12664 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12665 12666 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12667 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12668 12669 PackageParser.Package newPackage = null; 12670 try { 12671 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12672 if (newPackage.mExtras != null) { 12673 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12674 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12675 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12676 12677 // is the update attempting to change shared user? that isn't going to work... 12678 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12679 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12680 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12681 + " to " + newPkgSetting.sharedUser); 12682 updatedSettings = true; 12683 } 12684 } 12685 12686 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12687 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12688 perUserInstalled, res, user); 12689 prepareAppDataAfterInstall(newPackage); 12690 updatedSettings = true; 12691 } 12692 12693 } catch (PackageManagerException e) { 12694 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12695 } 12696 12697 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12698 // Re installation failed. Restore old information 12699 // Remove new pkg information 12700 if (newPackage != null) { 12701 removeInstalledPackageLI(newPackage, true); 12702 } 12703 // Add back the old system package 12704 try { 12705 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12706 } catch (PackageManagerException e) { 12707 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12708 } 12709 // Restore the old system information in Settings 12710 synchronized (mPackages) { 12711 if (disabledSystem) { 12712 mSettings.enableSystemPackageLPw(packageName); 12713 } 12714 if (updatedSettings) { 12715 mSettings.setInstallerPackageName(packageName, 12716 oldPkgSetting.installerPackageName); 12717 } 12718 mSettings.writeLPr(); 12719 } 12720 } 12721 } 12722 12723 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12724 // Collect all used permissions in the UID 12725 ArraySet<String> usedPermissions = new ArraySet<>(); 12726 final int packageCount = su.packages.size(); 12727 for (int i = 0; i < packageCount; i++) { 12728 PackageSetting ps = su.packages.valueAt(i); 12729 if (ps.pkg == null) { 12730 continue; 12731 } 12732 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12733 for (int j = 0; j < requestedPermCount; j++) { 12734 String permission = ps.pkg.requestedPermissions.get(j); 12735 BasePermission bp = mSettings.mPermissions.get(permission); 12736 if (bp != null) { 12737 usedPermissions.add(permission); 12738 } 12739 } 12740 } 12741 12742 PermissionsState permissionsState = su.getPermissionsState(); 12743 // Prune install permissions 12744 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12745 final int installPermCount = installPermStates.size(); 12746 for (int i = installPermCount - 1; i >= 0; i--) { 12747 PermissionState permissionState = installPermStates.get(i); 12748 if (!usedPermissions.contains(permissionState.getName())) { 12749 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12750 if (bp != null) { 12751 permissionsState.revokeInstallPermission(bp); 12752 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12753 PackageManager.MASK_PERMISSION_FLAGS, 0); 12754 } 12755 } 12756 } 12757 12758 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12759 12760 // Prune runtime permissions 12761 for (int userId : allUserIds) { 12762 List<PermissionState> runtimePermStates = permissionsState 12763 .getRuntimePermissionStates(userId); 12764 final int runtimePermCount = runtimePermStates.size(); 12765 for (int i = runtimePermCount - 1; i >= 0; i--) { 12766 PermissionState permissionState = runtimePermStates.get(i); 12767 if (!usedPermissions.contains(permissionState.getName())) { 12768 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12769 if (bp != null) { 12770 permissionsState.revokeRuntimePermission(bp, userId); 12771 permissionsState.updatePermissionFlags(bp, userId, 12772 PackageManager.MASK_PERMISSION_FLAGS, 0); 12773 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12774 runtimePermissionChangedUserIds, userId); 12775 } 12776 } 12777 } 12778 } 12779 12780 return runtimePermissionChangedUserIds; 12781 } 12782 12783 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12784 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12785 UserHandle user) { 12786 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12787 12788 String pkgName = newPackage.packageName; 12789 synchronized (mPackages) { 12790 //write settings. the installStatus will be incomplete at this stage. 12791 //note that the new package setting would have already been 12792 //added to mPackages. It hasn't been persisted yet. 12793 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12794 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12795 mSettings.writeLPr(); 12796 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12797 } 12798 12799 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12800 synchronized (mPackages) { 12801 updatePermissionsLPw(newPackage.packageName, newPackage, 12802 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12803 ? UPDATE_PERMISSIONS_ALL : 0)); 12804 // For system-bundled packages, we assume that installing an upgraded version 12805 // of the package implies that the user actually wants to run that new code, 12806 // so we enable the package. 12807 PackageSetting ps = mSettings.mPackages.get(pkgName); 12808 if (ps != null) { 12809 if (isSystemApp(newPackage)) { 12810 // NB: implicit assumption that system package upgrades apply to all users 12811 if (DEBUG_INSTALL) { 12812 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12813 } 12814 if (res.origUsers != null) { 12815 for (int userHandle : res.origUsers) { 12816 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12817 userHandle, installerPackageName); 12818 } 12819 } 12820 // Also convey the prior install/uninstall state 12821 if (allUsers != null && perUserInstalled != null) { 12822 for (int i = 0; i < allUsers.length; i++) { 12823 if (DEBUG_INSTALL) { 12824 Slog.d(TAG, " user " + allUsers[i] 12825 + " => " + perUserInstalled[i]); 12826 } 12827 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12828 } 12829 // these install state changes will be persisted in the 12830 // upcoming call to mSettings.writeLPr(). 12831 } 12832 } 12833 // It's implied that when a user requests installation, they want the app to be 12834 // installed and enabled. 12835 int userId = user.getIdentifier(); 12836 if (userId != UserHandle.USER_ALL) { 12837 ps.setInstalled(true, userId); 12838 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12839 } 12840 } 12841 res.name = pkgName; 12842 res.uid = newPackage.applicationInfo.uid; 12843 res.pkg = newPackage; 12844 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12845 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12846 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12847 //to update install status 12848 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12849 mSettings.writeLPr(); 12850 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12851 } 12852 12853 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12854 } 12855 12856 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12857 try { 12858 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12859 installPackageLI(args, res); 12860 } finally { 12861 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12862 } 12863 } 12864 12865 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12866 final int installFlags = args.installFlags; 12867 final String installerPackageName = args.installerPackageName; 12868 final String volumeUuid = args.volumeUuid; 12869 final File tmpPackageFile = new File(args.getCodePath()); 12870 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12871 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12872 || (args.volumeUuid != null)); 12873 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 12874 boolean replace = false; 12875 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12876 if (args.move != null) { 12877 // moving a complete application; perfom an initial scan on the new install location 12878 scanFlags |= SCAN_INITIAL; 12879 } 12880 // Result object to be returned 12881 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12882 12883 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12884 12885 // Sanity check 12886 if (ephemeral && (forwardLocked || onExternal)) { 12887 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 12888 + " external=" + onExternal); 12889 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12890 return; 12891 } 12892 12893 // Retrieve PackageSettings and parse package 12894 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12895 | PackageParser.PARSE_ENFORCE_CODE 12896 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12897 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12898 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 12899 PackageParser pp = new PackageParser(); 12900 pp.setSeparateProcesses(mSeparateProcesses); 12901 pp.setDisplayMetrics(mMetrics); 12902 12903 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12904 final PackageParser.Package pkg; 12905 try { 12906 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12907 } catch (PackageParserException e) { 12908 res.setError("Failed parse during installPackageLI", e); 12909 return; 12910 } finally { 12911 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12912 } 12913 12914 // Mark that we have an install time CPU ABI override. 12915 pkg.cpuAbiOverride = args.abiOverride; 12916 12917 String pkgName = res.name = pkg.packageName; 12918 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12919 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12920 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12921 return; 12922 } 12923 } 12924 12925 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12926 try { 12927 pp.collectCertificates(pkg, parseFlags); 12928 } catch (PackageParserException e) { 12929 res.setError("Failed collect during installPackageLI", e); 12930 return; 12931 } finally { 12932 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12933 } 12934 12935 // Get rid of all references to package scan path via parser. 12936 pp = null; 12937 String oldCodePath = null; 12938 boolean systemApp = false; 12939 synchronized (mPackages) { 12940 // Check if installing already existing package 12941 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12942 String oldName = mSettings.mRenamedPackages.get(pkgName); 12943 if (pkg.mOriginalPackages != null 12944 && pkg.mOriginalPackages.contains(oldName) 12945 && mPackages.containsKey(oldName)) { 12946 // This package is derived from an original package, 12947 // and this device has been updating from that original 12948 // name. We must continue using the original name, so 12949 // rename the new package here. 12950 pkg.setPackageName(oldName); 12951 pkgName = pkg.packageName; 12952 replace = true; 12953 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12954 + oldName + " pkgName=" + pkgName); 12955 } else if (mPackages.containsKey(pkgName)) { 12956 // This package, under its official name, already exists 12957 // on the device; we should replace it. 12958 replace = true; 12959 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12960 } 12961 12962 // Prevent apps opting out from runtime permissions 12963 if (replace) { 12964 PackageParser.Package oldPackage = mPackages.get(pkgName); 12965 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12966 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12967 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12968 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12969 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12970 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12971 + " doesn't support runtime permissions but the old" 12972 + " target SDK " + oldTargetSdk + " does."); 12973 return; 12974 } 12975 } 12976 } 12977 12978 PackageSetting ps = mSettings.mPackages.get(pkgName); 12979 if (ps != null) { 12980 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12981 12982 // Quick sanity check that we're signed correctly if updating; 12983 // we'll check this again later when scanning, but we want to 12984 // bail early here before tripping over redefined permissions. 12985 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12986 if (!checkUpgradeKeySetLP(ps, pkg)) { 12987 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12988 + pkg.packageName + " upgrade keys do not match the " 12989 + "previously installed version"); 12990 return; 12991 } 12992 } else { 12993 try { 12994 verifySignaturesLP(ps, pkg); 12995 } catch (PackageManagerException e) { 12996 res.setError(e.error, e.getMessage()); 12997 return; 12998 } 12999 } 13000 13001 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 13002 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 13003 systemApp = (ps.pkg.applicationInfo.flags & 13004 ApplicationInfo.FLAG_SYSTEM) != 0; 13005 } 13006 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13007 } 13008 13009 // Check whether the newly-scanned package wants to define an already-defined perm 13010 int N = pkg.permissions.size(); 13011 for (int i = N-1; i >= 0; i--) { 13012 PackageParser.Permission perm = pkg.permissions.get(i); 13013 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 13014 if (bp != null) { 13015 // If the defining package is signed with our cert, it's okay. This 13016 // also includes the "updating the same package" case, of course. 13017 // "updating same package" could also involve key-rotation. 13018 final boolean sigsOk; 13019 if (bp.sourcePackage.equals(pkg.packageName) 13020 && (bp.packageSetting instanceof PackageSetting) 13021 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 13022 scanFlags))) { 13023 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 13024 } else { 13025 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 13026 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 13027 } 13028 if (!sigsOk) { 13029 // If the owning package is the system itself, we log but allow 13030 // install to proceed; we fail the install on all other permission 13031 // redefinitions. 13032 if (!bp.sourcePackage.equals("android")) { 13033 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 13034 + pkg.packageName + " attempting to redeclare permission " 13035 + perm.info.name + " already owned by " + bp.sourcePackage); 13036 res.origPermission = perm.info.name; 13037 res.origPackage = bp.sourcePackage; 13038 return; 13039 } else { 13040 Slog.w(TAG, "Package " + pkg.packageName 13041 + " attempting to redeclare system permission " 13042 + perm.info.name + "; ignoring new declaration"); 13043 pkg.permissions.remove(i); 13044 } 13045 } 13046 } 13047 } 13048 13049 } 13050 13051 if (systemApp) { 13052 if (onExternal) { 13053 // Abort update; system app can't be replaced with app on sdcard 13054 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 13055 "Cannot install updates to system apps on sdcard"); 13056 return; 13057 } else if (ephemeral) { 13058 // Abort update; system app can't be replaced with an ephemeral app 13059 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 13060 "Cannot update a system app with an ephemeral app"); 13061 return; 13062 } 13063 } 13064 13065 if (args.move != null) { 13066 // We did an in-place move, so dex is ready to roll 13067 scanFlags |= SCAN_NO_DEX; 13068 scanFlags |= SCAN_MOVE; 13069 13070 synchronized (mPackages) { 13071 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13072 if (ps == null) { 13073 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 13074 "Missing settings for moved package " + pkgName); 13075 } 13076 13077 // We moved the entire application as-is, so bring over the 13078 // previously derived ABI information. 13079 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13080 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13081 } 13082 13083 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13084 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13085 scanFlags |= SCAN_NO_DEX; 13086 13087 try { 13088 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 13089 true /* extract libs */); 13090 } catch (PackageManagerException pme) { 13091 Slog.e(TAG, "Error deriving application ABI", pme); 13092 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13093 return; 13094 } 13095 13096 // Extract package to save the VM unzipping the APK in memory during 13097 // launch. Only do this if profile-guided compilation is enabled because 13098 // otherwise BackgroundDexOptService will not dexopt the package later. 13099 if (mUseJitProfiles) { 13100 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 13101 // Do not run PackageDexOptimizer through the local performDexOpt 13102 // method because `pkg` is not in `mPackages` yet. 13103 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 13104 false /* useProfiles */, true /* extractOnly */); 13105 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13106 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 13107 String msg = "Extracking package failed for " + pkgName; 13108 res.setError(INSTALL_FAILED_DEXOPT, msg); 13109 return; 13110 } 13111 } 13112 } 13113 13114 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13115 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13116 return; 13117 } 13118 13119 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13120 13121 if (replace) { 13122 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13123 installerPackageName, volumeUuid, res); 13124 } else { 13125 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13126 args.user, installerPackageName, volumeUuid, res); 13127 } 13128 synchronized (mPackages) { 13129 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13130 if (ps != null) { 13131 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13132 } 13133 } 13134 } 13135 13136 private void startIntentFilterVerifications(int userId, boolean replacing, 13137 PackageParser.Package pkg) { 13138 if (mIntentFilterVerifierComponent == null) { 13139 Slog.w(TAG, "No IntentFilter verification will not be done as " 13140 + "there is no IntentFilterVerifier available!"); 13141 return; 13142 } 13143 13144 final int verifierUid = getPackageUid( 13145 mIntentFilterVerifierComponent.getPackageName(), 13146 MATCH_DEBUG_TRIAGED_MISSING, 13147 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13148 13149 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 13150 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13151 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13152 mHandler.sendMessage(msg); 13153 } 13154 13155 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13156 PackageParser.Package pkg) { 13157 int size = pkg.activities.size(); 13158 if (size == 0) { 13159 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13160 "No activity, so no need to verify any IntentFilter!"); 13161 return; 13162 } 13163 13164 final boolean hasDomainURLs = hasDomainURLs(pkg); 13165 if (!hasDomainURLs) { 13166 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13167 "No domain URLs, so no need to verify any IntentFilter!"); 13168 return; 13169 } 13170 13171 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13172 + " if any IntentFilter from the " + size 13173 + " Activities needs verification ..."); 13174 13175 int count = 0; 13176 final String packageName = pkg.packageName; 13177 13178 synchronized (mPackages) { 13179 // If this is a new install and we see that we've already run verification for this 13180 // package, we have nothing to do: it means the state was restored from backup. 13181 if (!replacing) { 13182 IntentFilterVerificationInfo ivi = 13183 mSettings.getIntentFilterVerificationLPr(packageName); 13184 if (ivi != null) { 13185 if (DEBUG_DOMAIN_VERIFICATION) { 13186 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13187 + ivi.getStatusString()); 13188 } 13189 return; 13190 } 13191 } 13192 13193 // If any filters need to be verified, then all need to be. 13194 boolean needToVerify = false; 13195 for (PackageParser.Activity a : pkg.activities) { 13196 for (ActivityIntentInfo filter : a.intents) { 13197 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13198 if (DEBUG_DOMAIN_VERIFICATION) { 13199 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13200 } 13201 needToVerify = true; 13202 break; 13203 } 13204 } 13205 } 13206 13207 if (needToVerify) { 13208 final int verificationId = mIntentFilterVerificationToken++; 13209 for (PackageParser.Activity a : pkg.activities) { 13210 for (ActivityIntentInfo filter : a.intents) { 13211 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13212 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13213 "Verification needed for IntentFilter:" + filter.toString()); 13214 mIntentFilterVerifier.addOneIntentFilterVerification( 13215 verifierUid, userId, verificationId, filter, packageName); 13216 count++; 13217 } 13218 } 13219 } 13220 } 13221 } 13222 13223 if (count > 0) { 13224 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13225 + " IntentFilter verification" + (count > 1 ? "s" : "") 13226 + " for userId:" + userId); 13227 mIntentFilterVerifier.startVerifications(userId); 13228 } else { 13229 if (DEBUG_DOMAIN_VERIFICATION) { 13230 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13231 } 13232 } 13233 } 13234 13235 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13236 final ComponentName cn = filter.activity.getComponentName(); 13237 final String packageName = cn.getPackageName(); 13238 13239 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13240 packageName); 13241 if (ivi == null) { 13242 return true; 13243 } 13244 int status = ivi.getStatus(); 13245 switch (status) { 13246 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13247 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13248 return true; 13249 13250 default: 13251 // Nothing to do 13252 return false; 13253 } 13254 } 13255 13256 private static boolean isMultiArch(ApplicationInfo info) { 13257 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13258 } 13259 13260 private static boolean isExternal(PackageParser.Package pkg) { 13261 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13262 } 13263 13264 private static boolean isExternal(PackageSetting ps) { 13265 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13266 } 13267 13268 private static boolean isEphemeral(PackageParser.Package pkg) { 13269 return pkg.applicationInfo.isEphemeralApp(); 13270 } 13271 13272 private static boolean isEphemeral(PackageSetting ps) { 13273 return ps.pkg != null && isEphemeral(ps.pkg); 13274 } 13275 13276 private static boolean isSystemApp(PackageParser.Package pkg) { 13277 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13278 } 13279 13280 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13281 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13282 } 13283 13284 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13285 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13286 } 13287 13288 private static boolean isSystemApp(PackageSetting ps) { 13289 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13290 } 13291 13292 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13293 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13294 } 13295 13296 private int packageFlagsToInstallFlags(PackageSetting ps) { 13297 int installFlags = 0; 13298 if (isEphemeral(ps)) { 13299 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13300 } 13301 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13302 // This existing package was an external ASEC install when we have 13303 // the external flag without a UUID 13304 installFlags |= PackageManager.INSTALL_EXTERNAL; 13305 } 13306 if (ps.isForwardLocked()) { 13307 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13308 } 13309 return installFlags; 13310 } 13311 13312 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13313 if (isExternal(pkg)) { 13314 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13315 return StorageManager.UUID_PRIMARY_PHYSICAL; 13316 } else { 13317 return pkg.volumeUuid; 13318 } 13319 } else { 13320 return StorageManager.UUID_PRIVATE_INTERNAL; 13321 } 13322 } 13323 13324 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13325 if (isExternal(pkg)) { 13326 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13327 return mSettings.getExternalVersion(); 13328 } else { 13329 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13330 } 13331 } else { 13332 return mSettings.getInternalVersion(); 13333 } 13334 } 13335 13336 private void deleteTempPackageFiles() { 13337 final FilenameFilter filter = new FilenameFilter() { 13338 public boolean accept(File dir, String name) { 13339 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13340 } 13341 }; 13342 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13343 file.delete(); 13344 } 13345 } 13346 13347 @Override 13348 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13349 int flags) { 13350 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13351 flags); 13352 } 13353 13354 @Override 13355 public void deletePackage(final String packageName, 13356 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13357 mContext.enforceCallingOrSelfPermission( 13358 android.Manifest.permission.DELETE_PACKAGES, null); 13359 Preconditions.checkNotNull(packageName); 13360 Preconditions.checkNotNull(observer); 13361 final int uid = Binder.getCallingUid(); 13362 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13363 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13364 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13365 mContext.enforceCallingOrSelfPermission( 13366 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13367 "deletePackage for user " + userId); 13368 } 13369 13370 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13371 try { 13372 observer.onPackageDeleted(packageName, 13373 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13374 } catch (RemoteException re) { 13375 } 13376 return; 13377 } 13378 13379 for (int currentUserId : users) { 13380 if (getBlockUninstallForUser(packageName, currentUserId)) { 13381 try { 13382 observer.onPackageDeleted(packageName, 13383 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13384 } catch (RemoteException re) { 13385 } 13386 return; 13387 } 13388 } 13389 13390 if (DEBUG_REMOVE) { 13391 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13392 } 13393 // Queue up an async operation since the package deletion may take a little while. 13394 mHandler.post(new Runnable() { 13395 public void run() { 13396 mHandler.removeCallbacks(this); 13397 final int returnCode = deletePackageX(packageName, userId, flags); 13398 try { 13399 observer.onPackageDeleted(packageName, returnCode, null); 13400 } catch (RemoteException e) { 13401 Log.i(TAG, "Observer no longer exists."); 13402 } //end catch 13403 } //end run 13404 }); 13405 } 13406 13407 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13408 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13409 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13410 try { 13411 if (dpm != null) { 13412 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13413 /* callingUserOnly =*/ false); 13414 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13415 : deviceOwnerComponentName.getPackageName(); 13416 // Does the package contains the device owner? 13417 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13418 // this check is probably not needed, since DO should be registered as a device 13419 // admin on some user too. (Original bug for this: b/17657954) 13420 if (packageName.equals(deviceOwnerPackageName)) { 13421 return true; 13422 } 13423 // Does it contain a device admin for any user? 13424 int[] users; 13425 if (userId == UserHandle.USER_ALL) { 13426 users = sUserManager.getUserIds(); 13427 } else { 13428 users = new int[]{userId}; 13429 } 13430 for (int i = 0; i < users.length; ++i) { 13431 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13432 return true; 13433 } 13434 } 13435 } 13436 } catch (RemoteException e) { 13437 } 13438 return false; 13439 } 13440 13441 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13442 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13443 } 13444 13445 /** 13446 * This method is an internal method that could be get invoked either 13447 * to delete an installed package or to clean up a failed installation. 13448 * After deleting an installed package, a broadcast is sent to notify any 13449 * listeners that the package has been installed. For cleaning up a failed 13450 * installation, the broadcast is not necessary since the package's 13451 * installation wouldn't have sent the initial broadcast either 13452 * The key steps in deleting a package are 13453 * deleting the package information in internal structures like mPackages, 13454 * deleting the packages base directories through installd 13455 * updating mSettings to reflect current status 13456 * persisting settings for later use 13457 * sending a broadcast if necessary 13458 */ 13459 private int deletePackageX(String packageName, int userId, int flags) { 13460 final PackageRemovedInfo info = new PackageRemovedInfo(); 13461 final boolean res; 13462 13463 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13464 ? UserHandle.ALL : new UserHandle(userId); 13465 13466 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13467 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13468 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13469 } 13470 13471 boolean removedForAllUsers = false; 13472 boolean systemUpdate = false; 13473 13474 PackageParser.Package uninstalledPkg; 13475 13476 // for the uninstall-updates case and restricted profiles, remember the per- 13477 // userhandle installed state 13478 int[] allUsers; 13479 boolean[] perUserInstalled; 13480 synchronized (mPackages) { 13481 uninstalledPkg = mPackages.get(packageName); 13482 PackageSetting ps = mSettings.mPackages.get(packageName); 13483 allUsers = sUserManager.getUserIds(); 13484 perUserInstalled = new boolean[allUsers.length]; 13485 for (int i = 0; i < allUsers.length; i++) { 13486 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13487 } 13488 } 13489 13490 synchronized (mInstallLock) { 13491 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13492 res = deletePackageLI(packageName, removeForUser, 13493 true, allUsers, perUserInstalled, 13494 flags | REMOVE_CHATTY, info, true); 13495 systemUpdate = info.isRemovedPackageSystemUpdate; 13496 synchronized (mPackages) { 13497 if (res) { 13498 if (!systemUpdate && mPackages.get(packageName) == null) { 13499 removedForAllUsers = true; 13500 } 13501 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg); 13502 } 13503 } 13504 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13505 + " removedForAllUsers=" + removedForAllUsers); 13506 } 13507 13508 if (res) { 13509 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13510 13511 // If the removed package was a system update, the old system package 13512 // was re-enabled; we need to broadcast this information 13513 if (systemUpdate) { 13514 Bundle extras = new Bundle(1); 13515 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13516 ? info.removedAppId : info.uid); 13517 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13518 13519 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13520 extras, 0, null, null, null); 13521 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13522 extras, 0, null, null, null); 13523 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13524 null, 0, packageName, null, null); 13525 } 13526 } 13527 // Force a gc here. 13528 Runtime.getRuntime().gc(); 13529 // Delete the resources here after sending the broadcast to let 13530 // other processes clean up before deleting resources. 13531 if (info.args != null) { 13532 synchronized (mInstallLock) { 13533 info.args.doPostDeleteLI(true); 13534 } 13535 } 13536 13537 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13538 } 13539 13540 class PackageRemovedInfo { 13541 String removedPackage; 13542 int uid = -1; 13543 int removedAppId = -1; 13544 int[] removedUsers = null; 13545 boolean isRemovedPackageSystemUpdate = false; 13546 // Clean up resources deleted packages. 13547 InstallArgs args = null; 13548 13549 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13550 Bundle extras = new Bundle(1); 13551 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13552 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13553 if (replacing) { 13554 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13555 } 13556 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13557 if (removedPackage != null) { 13558 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13559 extras, 0, null, null, removedUsers); 13560 if (fullRemove && !replacing) { 13561 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13562 extras, 0, null, null, removedUsers); 13563 } 13564 } 13565 if (removedAppId >= 0) { 13566 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 13567 removedUsers); 13568 } 13569 } 13570 } 13571 13572 /* 13573 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13574 * flag is not set, the data directory is removed as well. 13575 * make sure this flag is set for partially installed apps. If not its meaningless to 13576 * delete a partially installed application. 13577 */ 13578 private void removePackageDataLI(PackageSetting ps, 13579 int[] allUserHandles, boolean[] perUserInstalled, 13580 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13581 String packageName = ps.name; 13582 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13583 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13584 // Retrieve object to delete permissions for shared user later on 13585 final PackageSetting deletedPs; 13586 // reader 13587 synchronized (mPackages) { 13588 deletedPs = mSettings.mPackages.get(packageName); 13589 if (outInfo != null) { 13590 outInfo.removedPackage = packageName; 13591 outInfo.removedUsers = deletedPs != null 13592 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13593 : null; 13594 } 13595 } 13596 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13597 removeDataDirsLI(ps.volumeUuid, packageName); 13598 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13599 } 13600 // writer 13601 synchronized (mPackages) { 13602 if (deletedPs != null) { 13603 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13604 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13605 clearDefaultBrowserIfNeeded(packageName); 13606 if (outInfo != null) { 13607 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13608 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13609 } 13610 updatePermissionsLPw(deletedPs.name, null, 0); 13611 if (deletedPs.sharedUser != null) { 13612 // Remove permissions associated with package. Since runtime 13613 // permissions are per user we have to kill the removed package 13614 // or packages running under the shared user of the removed 13615 // package if revoking the permissions requested only by the removed 13616 // package is successful and this causes a change in gids. 13617 for (int userId : UserManagerService.getInstance().getUserIds()) { 13618 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13619 userId); 13620 if (userIdToKill == UserHandle.USER_ALL 13621 || userIdToKill >= UserHandle.USER_SYSTEM) { 13622 // If gids changed for this user, kill all affected packages. 13623 mHandler.post(new Runnable() { 13624 @Override 13625 public void run() { 13626 // This has to happen with no lock held. 13627 killApplication(deletedPs.name, deletedPs.appId, 13628 KILL_APP_REASON_GIDS_CHANGED); 13629 } 13630 }); 13631 break; 13632 } 13633 } 13634 } 13635 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13636 } 13637 // make sure to preserve per-user disabled state if this removal was just 13638 // a downgrade of a system app to the factory package 13639 if (allUserHandles != null && perUserInstalled != null) { 13640 if (DEBUG_REMOVE) { 13641 Slog.d(TAG, "Propagating install state across downgrade"); 13642 } 13643 for (int i = 0; i < allUserHandles.length; i++) { 13644 if (DEBUG_REMOVE) { 13645 Slog.d(TAG, " user " + allUserHandles[i] 13646 + " => " + perUserInstalled[i]); 13647 } 13648 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13649 } 13650 } 13651 } 13652 // can downgrade to reader 13653 if (writeSettings) { 13654 // Save settings now 13655 mSettings.writeLPr(); 13656 } 13657 } 13658 if (outInfo != null) { 13659 // A user ID was deleted here. Go through all users and remove it 13660 // from KeyStore. 13661 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13662 } 13663 } 13664 13665 static boolean locationIsPrivileged(File path) { 13666 try { 13667 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13668 .getCanonicalPath(); 13669 return path.getCanonicalPath().startsWith(privilegedAppDir); 13670 } catch (IOException e) { 13671 Slog.e(TAG, "Unable to access code path " + path); 13672 } 13673 return false; 13674 } 13675 13676 /* 13677 * Tries to delete system package. 13678 */ 13679 private boolean deleteSystemPackageLI(PackageSetting newPs, 13680 int[] allUserHandles, boolean[] perUserInstalled, 13681 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13682 final boolean applyUserRestrictions 13683 = (allUserHandles != null) && (perUserInstalled != null); 13684 PackageSetting disabledPs = null; 13685 // Confirm if the system package has been updated 13686 // An updated system app can be deleted. This will also have to restore 13687 // the system pkg from system partition 13688 // reader 13689 synchronized (mPackages) { 13690 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13691 } 13692 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13693 + " disabledPs=" + disabledPs); 13694 if (disabledPs == null) { 13695 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13696 return false; 13697 } else if (DEBUG_REMOVE) { 13698 Slog.d(TAG, "Deleting system pkg from data partition"); 13699 } 13700 if (DEBUG_REMOVE) { 13701 if (applyUserRestrictions) { 13702 Slog.d(TAG, "Remembering install states:"); 13703 for (int i = 0; i < allUserHandles.length; i++) { 13704 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13705 } 13706 } 13707 } 13708 // Delete the updated package 13709 outInfo.isRemovedPackageSystemUpdate = true; 13710 if (disabledPs.versionCode < newPs.versionCode) { 13711 // Delete data for downgrades 13712 flags &= ~PackageManager.DELETE_KEEP_DATA; 13713 } else { 13714 // Preserve data by setting flag 13715 flags |= PackageManager.DELETE_KEEP_DATA; 13716 } 13717 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13718 allUserHandles, perUserInstalled, outInfo, writeSettings); 13719 if (!ret) { 13720 return false; 13721 } 13722 // writer 13723 synchronized (mPackages) { 13724 // Reinstate the old system package 13725 mSettings.enableSystemPackageLPw(newPs.name); 13726 // Remove any native libraries from the upgraded package. 13727 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13728 } 13729 // Install the system package 13730 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13731 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13732 if (locationIsPrivileged(disabledPs.codePath)) { 13733 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13734 } 13735 13736 final PackageParser.Package newPkg; 13737 try { 13738 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13739 } catch (PackageManagerException e) { 13740 Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage()); 13741 return false; 13742 } 13743 13744 prepareAppDataAfterInstall(newPkg); 13745 13746 // writer 13747 synchronized (mPackages) { 13748 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13749 13750 // Propagate the permissions state as we do not want to drop on the floor 13751 // runtime permissions. The update permissions method below will take 13752 // care of removing obsolete permissions and grant install permissions. 13753 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13754 updatePermissionsLPw(newPkg.packageName, newPkg, 13755 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13756 13757 if (applyUserRestrictions) { 13758 if (DEBUG_REMOVE) { 13759 Slog.d(TAG, "Propagating install state across reinstall"); 13760 } 13761 for (int i = 0; i < allUserHandles.length; i++) { 13762 if (DEBUG_REMOVE) { 13763 Slog.d(TAG, " user " + allUserHandles[i] 13764 + " => " + perUserInstalled[i]); 13765 } 13766 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13767 13768 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13769 } 13770 // Regardless of writeSettings we need to ensure that this restriction 13771 // state propagation is persisted 13772 mSettings.writeAllUsersPackageRestrictionsLPr(); 13773 } 13774 // can downgrade to reader here 13775 if (writeSettings) { 13776 mSettings.writeLPr(); 13777 } 13778 } 13779 return true; 13780 } 13781 13782 private boolean deleteInstalledPackageLI(PackageSetting ps, 13783 boolean deleteCodeAndResources, int flags, 13784 int[] allUserHandles, boolean[] perUserInstalled, 13785 PackageRemovedInfo outInfo, boolean writeSettings) { 13786 if (outInfo != null) { 13787 outInfo.uid = ps.appId; 13788 } 13789 13790 // Delete package data from internal structures and also remove data if flag is set 13791 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13792 13793 // Delete application code and resources 13794 if (deleteCodeAndResources && (outInfo != null)) { 13795 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13796 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13797 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13798 } 13799 return true; 13800 } 13801 13802 @Override 13803 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13804 int userId) { 13805 mContext.enforceCallingOrSelfPermission( 13806 android.Manifest.permission.DELETE_PACKAGES, null); 13807 synchronized (mPackages) { 13808 PackageSetting ps = mSettings.mPackages.get(packageName); 13809 if (ps == null) { 13810 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13811 return false; 13812 } 13813 if (!ps.getInstalled(userId)) { 13814 // Can't block uninstall for an app that is not installed or enabled. 13815 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13816 return false; 13817 } 13818 ps.setBlockUninstall(blockUninstall, userId); 13819 mSettings.writePackageRestrictionsLPr(userId); 13820 } 13821 return true; 13822 } 13823 13824 @Override 13825 public boolean getBlockUninstallForUser(String packageName, int userId) { 13826 synchronized (mPackages) { 13827 PackageSetting ps = mSettings.mPackages.get(packageName); 13828 if (ps == null) { 13829 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13830 return false; 13831 } 13832 return ps.getBlockUninstall(userId); 13833 } 13834 } 13835 13836 @Override 13837 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 13838 int callingUid = Binder.getCallingUid(); 13839 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 13840 throw new SecurityException( 13841 "setRequiredForSystemUser can only be run by the system or root"); 13842 } 13843 synchronized (mPackages) { 13844 PackageSetting ps = mSettings.mPackages.get(packageName); 13845 if (ps == null) { 13846 Log.w(TAG, "Package doesn't exist: " + packageName); 13847 return false; 13848 } 13849 if (systemUserApp) { 13850 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13851 } else { 13852 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13853 } 13854 mSettings.writeLPr(); 13855 } 13856 return true; 13857 } 13858 13859 /* 13860 * This method handles package deletion in general 13861 */ 13862 private boolean deletePackageLI(String packageName, UserHandle user, 13863 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13864 int flags, PackageRemovedInfo outInfo, 13865 boolean writeSettings) { 13866 if (packageName == null) { 13867 Slog.w(TAG, "Attempt to delete null packageName."); 13868 return false; 13869 } 13870 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13871 PackageSetting ps; 13872 boolean dataOnly = false; 13873 int removeUser = -1; 13874 int appId = -1; 13875 synchronized (mPackages) { 13876 ps = mSettings.mPackages.get(packageName); 13877 if (ps == null) { 13878 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13879 return false; 13880 } 13881 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13882 && user.getIdentifier() != UserHandle.USER_ALL) { 13883 // The caller is asking that the package only be deleted for a single 13884 // user. To do this, we just mark its uninstalled state and delete 13885 // its data. If this is a system app, we only allow this to happen if 13886 // they have set the special DELETE_SYSTEM_APP which requests different 13887 // semantics than normal for uninstalling system apps. 13888 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13889 final int userId = user.getIdentifier(); 13890 ps.setUserState(userId, 13891 COMPONENT_ENABLED_STATE_DEFAULT, 13892 false, //installed 13893 true, //stopped 13894 true, //notLaunched 13895 false, //hidden 13896 false, //suspended 13897 null, null, null, 13898 false, // blockUninstall 13899 ps.readUserState(userId).domainVerificationStatus, 0); 13900 if (!isSystemApp(ps)) { 13901 // Do not uninstall the APK if an app should be cached 13902 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 13903 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 13904 // Other user still have this package installed, so all 13905 // we need to do is clear this user's data and save that 13906 // it is uninstalled. 13907 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13908 removeUser = user.getIdentifier(); 13909 appId = ps.appId; 13910 scheduleWritePackageRestrictionsLocked(removeUser); 13911 } else { 13912 // We need to set it back to 'installed' so the uninstall 13913 // broadcasts will be sent correctly. 13914 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13915 ps.setInstalled(true, user.getIdentifier()); 13916 } 13917 } else { 13918 // This is a system app, so we assume that the 13919 // other users still have this package installed, so all 13920 // we need to do is clear this user's data and save that 13921 // it is uninstalled. 13922 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13923 removeUser = user.getIdentifier(); 13924 appId = ps.appId; 13925 scheduleWritePackageRestrictionsLocked(removeUser); 13926 } 13927 } 13928 } 13929 13930 if (removeUser >= 0) { 13931 // From above, we determined that we are deleting this only 13932 // for a single user. Continue the work here. 13933 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13934 if (outInfo != null) { 13935 outInfo.removedPackage = packageName; 13936 outInfo.removedAppId = appId; 13937 outInfo.removedUsers = new int[] {removeUser}; 13938 } 13939 // TODO: triage flags as part of 26466827 13940 final int installerFlags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 13941 try { 13942 mInstaller.destroyAppData(ps.volumeUuid, packageName, removeUser, installerFlags); 13943 } catch (InstallerException e) { 13944 Slog.w(TAG, "Failed to delete app data", e); 13945 } 13946 removeKeystoreDataIfNeeded(removeUser, appId); 13947 schedulePackageCleaning(packageName, removeUser, false); 13948 synchronized (mPackages) { 13949 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13950 scheduleWritePackageRestrictionsLocked(removeUser); 13951 } 13952 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13953 } 13954 return true; 13955 } 13956 13957 if (dataOnly) { 13958 // Delete application data first 13959 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13960 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13961 return true; 13962 } 13963 13964 boolean ret = false; 13965 if (isSystemApp(ps)) { 13966 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 13967 // When an updated system application is deleted we delete the existing resources as well and 13968 // fall back to existing code in system partition 13969 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13970 flags, outInfo, writeSettings); 13971 } else { 13972 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 13973 // Kill application pre-emptively especially for apps on sd. 13974 killApplication(packageName, ps.appId, "uninstall pkg"); 13975 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13976 allUserHandles, perUserInstalled, 13977 outInfo, writeSettings); 13978 } 13979 13980 return ret; 13981 } 13982 13983 private final static class ClearStorageConnection implements ServiceConnection { 13984 IMediaContainerService mContainerService; 13985 13986 @Override 13987 public void onServiceConnected(ComponentName name, IBinder service) { 13988 synchronized (this) { 13989 mContainerService = IMediaContainerService.Stub.asInterface(service); 13990 notifyAll(); 13991 } 13992 } 13993 13994 @Override 13995 public void onServiceDisconnected(ComponentName name) { 13996 } 13997 } 13998 13999 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 14000 final boolean mounted; 14001 if (Environment.isExternalStorageEmulated()) { 14002 mounted = true; 14003 } else { 14004 final String status = Environment.getExternalStorageState(); 14005 14006 mounted = status.equals(Environment.MEDIA_MOUNTED) 14007 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 14008 } 14009 14010 if (!mounted) { 14011 return; 14012 } 14013 14014 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 14015 int[] users; 14016 if (userId == UserHandle.USER_ALL) { 14017 users = sUserManager.getUserIds(); 14018 } else { 14019 users = new int[] { userId }; 14020 } 14021 final ClearStorageConnection conn = new ClearStorageConnection(); 14022 if (mContext.bindServiceAsUser( 14023 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 14024 try { 14025 for (int curUser : users) { 14026 long timeout = SystemClock.uptimeMillis() + 5000; 14027 synchronized (conn) { 14028 long now = SystemClock.uptimeMillis(); 14029 while (conn.mContainerService == null && now < timeout) { 14030 try { 14031 conn.wait(timeout - now); 14032 } catch (InterruptedException e) { 14033 } 14034 } 14035 } 14036 if (conn.mContainerService == null) { 14037 return; 14038 } 14039 14040 final UserEnvironment userEnv = new UserEnvironment(curUser); 14041 clearDirectory(conn.mContainerService, 14042 userEnv.buildExternalStorageAppCacheDirs(packageName)); 14043 if (allData) { 14044 clearDirectory(conn.mContainerService, 14045 userEnv.buildExternalStorageAppDataDirs(packageName)); 14046 clearDirectory(conn.mContainerService, 14047 userEnv.buildExternalStorageAppMediaDirs(packageName)); 14048 } 14049 } 14050 } finally { 14051 mContext.unbindService(conn); 14052 } 14053 } 14054 } 14055 14056 @Override 14057 public void clearApplicationUserData(final String packageName, 14058 final IPackageDataObserver observer, final int userId) { 14059 mContext.enforceCallingOrSelfPermission( 14060 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 14061 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 14062 // Queue up an async operation since the package deletion may take a little while. 14063 mHandler.post(new Runnable() { 14064 public void run() { 14065 mHandler.removeCallbacks(this); 14066 final boolean succeeded; 14067 synchronized (mInstallLock) { 14068 succeeded = clearApplicationUserDataLI(packageName, userId); 14069 } 14070 clearExternalStorageDataSync(packageName, userId, true); 14071 if (succeeded) { 14072 // invoke DeviceStorageMonitor's update method to clear any notifications 14073 DeviceStorageMonitorInternal 14074 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14075 if (dsm != null) { 14076 dsm.checkMemory(); 14077 } 14078 } 14079 if(observer != null) { 14080 try { 14081 observer.onRemoveCompleted(packageName, succeeded); 14082 } catch (RemoteException e) { 14083 Log.i(TAG, "Observer no longer exists."); 14084 } 14085 } //end if observer 14086 } //end run 14087 }); 14088 } 14089 14090 private boolean clearApplicationUserDataLI(String packageName, int userId) { 14091 if (packageName == null) { 14092 Slog.w(TAG, "Attempt to delete null packageName."); 14093 return false; 14094 } 14095 14096 // Try finding details about the requested package 14097 PackageParser.Package pkg; 14098 synchronized (mPackages) { 14099 pkg = mPackages.get(packageName); 14100 if (pkg == null) { 14101 final PackageSetting ps = mSettings.mPackages.get(packageName); 14102 if (ps != null) { 14103 pkg = ps.pkg; 14104 } 14105 } 14106 14107 if (pkg == null) { 14108 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14109 return false; 14110 } 14111 14112 PackageSetting ps = (PackageSetting) pkg.mExtras; 14113 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14114 } 14115 14116 // Always delete data directories for package, even if we found no other 14117 // record of app. This helps users recover from UID mismatches without 14118 // resorting to a full data wipe. 14119 // TODO: triage flags as part of 26466827 14120 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14121 try { 14122 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 14123 } catch (InstallerException e) { 14124 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 14125 return false; 14126 } 14127 14128 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14129 removeKeystoreDataIfNeeded(userId, appId); 14130 14131 // Create a native library symlink only if we have native libraries 14132 // and if the native libraries are 32 bit libraries. We do not provide 14133 // this symlink for 64 bit libraries. 14134 if (pkg.applicationInfo.primaryCpuAbi != null && 14135 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 14136 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 14137 try { 14138 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 14139 nativeLibPath, userId); 14140 } catch (InstallerException e) { 14141 Slog.w(TAG, "Failed linking native library dir", e); 14142 return false; 14143 } 14144 } 14145 14146 return true; 14147 } 14148 14149 /** 14150 * Reverts user permission state changes (permissions and flags) in 14151 * all packages for a given user. 14152 * 14153 * @param userId The device user for which to do a reset. 14154 */ 14155 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 14156 final int packageCount = mPackages.size(); 14157 for (int i = 0; i < packageCount; i++) { 14158 PackageParser.Package pkg = mPackages.valueAt(i); 14159 PackageSetting ps = (PackageSetting) pkg.mExtras; 14160 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14161 } 14162 } 14163 14164 /** 14165 * Reverts user permission state changes (permissions and flags). 14166 * 14167 * @param ps The package for which to reset. 14168 * @param userId The device user for which to do a reset. 14169 */ 14170 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 14171 final PackageSetting ps, final int userId) { 14172 if (ps.pkg == null) { 14173 return; 14174 } 14175 14176 // These are flags that can change base on user actions. 14177 final int userSettableMask = FLAG_PERMISSION_USER_SET 14178 | FLAG_PERMISSION_USER_FIXED 14179 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 14180 | FLAG_PERMISSION_REVIEW_REQUIRED; 14181 14182 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 14183 | FLAG_PERMISSION_POLICY_FIXED; 14184 14185 boolean writeInstallPermissions = false; 14186 boolean writeRuntimePermissions = false; 14187 14188 final int permissionCount = ps.pkg.requestedPermissions.size(); 14189 for (int i = 0; i < permissionCount; i++) { 14190 String permission = ps.pkg.requestedPermissions.get(i); 14191 14192 BasePermission bp = mSettings.mPermissions.get(permission); 14193 if (bp == null) { 14194 continue; 14195 } 14196 14197 // If shared user we just reset the state to which only this app contributed. 14198 if (ps.sharedUser != null) { 14199 boolean used = false; 14200 final int packageCount = ps.sharedUser.packages.size(); 14201 for (int j = 0; j < packageCount; j++) { 14202 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 14203 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 14204 && pkg.pkg.requestedPermissions.contains(permission)) { 14205 used = true; 14206 break; 14207 } 14208 } 14209 if (used) { 14210 continue; 14211 } 14212 } 14213 14214 PermissionsState permissionsState = ps.getPermissionsState(); 14215 14216 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 14217 14218 // Always clear the user settable flags. 14219 final boolean hasInstallState = permissionsState.getInstallPermissionState( 14220 bp.name) != null; 14221 // If permission review is enabled and this is a legacy app, mark the 14222 // permission as requiring a review as this is the initial state. 14223 int flags = 0; 14224 if (Build.PERMISSIONS_REVIEW_REQUIRED 14225 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 14226 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 14227 } 14228 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 14229 if (hasInstallState) { 14230 writeInstallPermissions = true; 14231 } else { 14232 writeRuntimePermissions = true; 14233 } 14234 } 14235 14236 // Below is only runtime permission handling. 14237 if (!bp.isRuntime()) { 14238 continue; 14239 } 14240 14241 // Never clobber system or policy. 14242 if ((oldFlags & policyOrSystemFlags) != 0) { 14243 continue; 14244 } 14245 14246 // If this permission was granted by default, make sure it is. 14247 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 14248 if (permissionsState.grantRuntimePermission(bp, userId) 14249 != PERMISSION_OPERATION_FAILURE) { 14250 writeRuntimePermissions = true; 14251 } 14252 // If permission review is enabled the permissions for a legacy apps 14253 // are represented as constantly granted runtime ones, so don't revoke. 14254 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 14255 // Otherwise, reset the permission. 14256 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 14257 switch (revokeResult) { 14258 case PERMISSION_OPERATION_SUCCESS: { 14259 writeRuntimePermissions = true; 14260 } break; 14261 14262 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 14263 writeRuntimePermissions = true; 14264 final int appId = ps.appId; 14265 mHandler.post(new Runnable() { 14266 @Override 14267 public void run() { 14268 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 14269 } 14270 }); 14271 } break; 14272 } 14273 } 14274 } 14275 14276 // Synchronously write as we are taking permissions away. 14277 if (writeRuntimePermissions) { 14278 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 14279 } 14280 14281 // Synchronously write as we are taking permissions away. 14282 if (writeInstallPermissions) { 14283 mSettings.writeLPr(); 14284 } 14285 } 14286 14287 /** 14288 * Remove entries from the keystore daemon. Will only remove it if the 14289 * {@code appId} is valid. 14290 */ 14291 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 14292 if (appId < 0) { 14293 return; 14294 } 14295 14296 final KeyStore keyStore = KeyStore.getInstance(); 14297 if (keyStore != null) { 14298 if (userId == UserHandle.USER_ALL) { 14299 for (final int individual : sUserManager.getUserIds()) { 14300 keyStore.clearUid(UserHandle.getUid(individual, appId)); 14301 } 14302 } else { 14303 keyStore.clearUid(UserHandle.getUid(userId, appId)); 14304 } 14305 } else { 14306 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 14307 } 14308 } 14309 14310 @Override 14311 public void deleteApplicationCacheFiles(final String packageName, 14312 final IPackageDataObserver observer) { 14313 mContext.enforceCallingOrSelfPermission( 14314 android.Manifest.permission.DELETE_CACHE_FILES, null); 14315 // Queue up an async operation since the package deletion may take a little while. 14316 final int userId = UserHandle.getCallingUserId(); 14317 mHandler.post(new Runnable() { 14318 public void run() { 14319 mHandler.removeCallbacks(this); 14320 final boolean succeded; 14321 synchronized (mInstallLock) { 14322 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14323 } 14324 clearExternalStorageDataSync(packageName, userId, false); 14325 if (observer != null) { 14326 try { 14327 observer.onRemoveCompleted(packageName, succeded); 14328 } catch (RemoteException e) { 14329 Log.i(TAG, "Observer no longer exists."); 14330 } 14331 } //end if observer 14332 } //end run 14333 }); 14334 } 14335 14336 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14337 if (packageName == null) { 14338 Slog.w(TAG, "Attempt to delete null packageName."); 14339 return false; 14340 } 14341 PackageParser.Package p; 14342 synchronized (mPackages) { 14343 p = mPackages.get(packageName); 14344 } 14345 if (p == null) { 14346 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14347 return false; 14348 } 14349 final ApplicationInfo applicationInfo = p.applicationInfo; 14350 if (applicationInfo == null) { 14351 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14352 return false; 14353 } 14354 // TODO: triage flags as part of 26466827 14355 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14356 try { 14357 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 14358 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 14359 } catch (InstallerException e) { 14360 Slog.w(TAG, "Couldn't remove cache files for package " 14361 + packageName + " u" + userId, e); 14362 return false; 14363 } 14364 return true; 14365 } 14366 14367 @Override 14368 public void getPackageSizeInfo(final String packageName, int userHandle, 14369 final IPackageStatsObserver observer) { 14370 mContext.enforceCallingOrSelfPermission( 14371 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14372 if (packageName == null) { 14373 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14374 } 14375 14376 PackageStats stats = new PackageStats(packageName, userHandle); 14377 14378 /* 14379 * Queue up an async operation since the package measurement may take a 14380 * little while. 14381 */ 14382 Message msg = mHandler.obtainMessage(INIT_COPY); 14383 msg.obj = new MeasureParams(stats, observer); 14384 mHandler.sendMessage(msg); 14385 } 14386 14387 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14388 PackageStats pStats) { 14389 if (packageName == null) { 14390 Slog.w(TAG, "Attempt to get size of null packageName."); 14391 return false; 14392 } 14393 PackageParser.Package p; 14394 boolean dataOnly = false; 14395 String libDirRoot = null; 14396 String asecPath = null; 14397 PackageSetting ps = null; 14398 synchronized (mPackages) { 14399 p = mPackages.get(packageName); 14400 ps = mSettings.mPackages.get(packageName); 14401 if(p == null) { 14402 dataOnly = true; 14403 if((ps == null) || (ps.pkg == null)) { 14404 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14405 return false; 14406 } 14407 p = ps.pkg; 14408 } 14409 if (ps != null) { 14410 libDirRoot = ps.legacyNativeLibraryPathString; 14411 } 14412 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14413 final long token = Binder.clearCallingIdentity(); 14414 try { 14415 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14416 if (secureContainerId != null) { 14417 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14418 } 14419 } finally { 14420 Binder.restoreCallingIdentity(token); 14421 } 14422 } 14423 } 14424 String publicSrcDir = null; 14425 if(!dataOnly) { 14426 final ApplicationInfo applicationInfo = p.applicationInfo; 14427 if (applicationInfo == null) { 14428 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14429 return false; 14430 } 14431 if (p.isForwardLocked()) { 14432 publicSrcDir = applicationInfo.getBaseResourcePath(); 14433 } 14434 } 14435 // TODO: extend to measure size of split APKs 14436 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14437 // not just the first level. 14438 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14439 // just the primary. 14440 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14441 14442 String apkPath; 14443 File packageDir = new File(p.codePath); 14444 14445 if (packageDir.isDirectory() && p.canHaveOatDir()) { 14446 apkPath = packageDir.getAbsolutePath(); 14447 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 14448 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 14449 libDirRoot = null; 14450 } 14451 } else { 14452 apkPath = p.baseCodePath; 14453 } 14454 14455 // TODO: triage flags as part of 26466827 14456 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14457 try { 14458 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 14459 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14460 } catch (InstallerException e) { 14461 return false; 14462 } 14463 14464 // Fix-up for forward-locked applications in ASEC containers. 14465 if (!isExternal(p)) { 14466 pStats.codeSize += pStats.externalCodeSize; 14467 pStats.externalCodeSize = 0L; 14468 } 14469 14470 return true; 14471 } 14472 14473 14474 @Override 14475 public void addPackageToPreferred(String packageName) { 14476 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14477 } 14478 14479 @Override 14480 public void removePackageFromPreferred(String packageName) { 14481 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14482 } 14483 14484 @Override 14485 public List<PackageInfo> getPreferredPackages(int flags) { 14486 return new ArrayList<PackageInfo>(); 14487 } 14488 14489 private int getUidTargetSdkVersionLockedLPr(int uid) { 14490 Object obj = mSettings.getUserIdLPr(uid); 14491 if (obj instanceof SharedUserSetting) { 14492 final SharedUserSetting sus = (SharedUserSetting) obj; 14493 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14494 final Iterator<PackageSetting> it = sus.packages.iterator(); 14495 while (it.hasNext()) { 14496 final PackageSetting ps = it.next(); 14497 if (ps.pkg != null) { 14498 int v = ps.pkg.applicationInfo.targetSdkVersion; 14499 if (v < vers) vers = v; 14500 } 14501 } 14502 return vers; 14503 } else if (obj instanceof PackageSetting) { 14504 final PackageSetting ps = (PackageSetting) obj; 14505 if (ps.pkg != null) { 14506 return ps.pkg.applicationInfo.targetSdkVersion; 14507 } 14508 } 14509 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14510 } 14511 14512 @Override 14513 public void addPreferredActivity(IntentFilter filter, int match, 14514 ComponentName[] set, ComponentName activity, int userId) { 14515 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14516 "Adding preferred"); 14517 } 14518 14519 private void addPreferredActivityInternal(IntentFilter filter, int match, 14520 ComponentName[] set, ComponentName activity, boolean always, int userId, 14521 String opname) { 14522 // writer 14523 int callingUid = Binder.getCallingUid(); 14524 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14525 if (filter.countActions() == 0) { 14526 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14527 return; 14528 } 14529 synchronized (mPackages) { 14530 if (mContext.checkCallingOrSelfPermission( 14531 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14532 != PackageManager.PERMISSION_GRANTED) { 14533 if (getUidTargetSdkVersionLockedLPr(callingUid) 14534 < Build.VERSION_CODES.FROYO) { 14535 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14536 + callingUid); 14537 return; 14538 } 14539 mContext.enforceCallingOrSelfPermission( 14540 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14541 } 14542 14543 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14544 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14545 + userId + ":"); 14546 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14547 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14548 scheduleWritePackageRestrictionsLocked(userId); 14549 } 14550 } 14551 14552 @Override 14553 public void replacePreferredActivity(IntentFilter filter, int match, 14554 ComponentName[] set, ComponentName activity, int userId) { 14555 if (filter.countActions() != 1) { 14556 throw new IllegalArgumentException( 14557 "replacePreferredActivity expects filter to have only 1 action."); 14558 } 14559 if (filter.countDataAuthorities() != 0 14560 || filter.countDataPaths() != 0 14561 || filter.countDataSchemes() > 1 14562 || filter.countDataTypes() != 0) { 14563 throw new IllegalArgumentException( 14564 "replacePreferredActivity expects filter to have no data authorities, " + 14565 "paths, or types; and at most one scheme."); 14566 } 14567 14568 final int callingUid = Binder.getCallingUid(); 14569 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14570 synchronized (mPackages) { 14571 if (mContext.checkCallingOrSelfPermission( 14572 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14573 != PackageManager.PERMISSION_GRANTED) { 14574 if (getUidTargetSdkVersionLockedLPr(callingUid) 14575 < Build.VERSION_CODES.FROYO) { 14576 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14577 + Binder.getCallingUid()); 14578 return; 14579 } 14580 mContext.enforceCallingOrSelfPermission( 14581 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14582 } 14583 14584 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14585 if (pir != null) { 14586 // Get all of the existing entries that exactly match this filter. 14587 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14588 if (existing != null && existing.size() == 1) { 14589 PreferredActivity cur = existing.get(0); 14590 if (DEBUG_PREFERRED) { 14591 Slog.i(TAG, "Checking replace of preferred:"); 14592 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14593 if (!cur.mPref.mAlways) { 14594 Slog.i(TAG, " -- CUR; not mAlways!"); 14595 } else { 14596 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14597 Slog.i(TAG, " -- CUR: mSet=" 14598 + Arrays.toString(cur.mPref.mSetComponents)); 14599 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14600 Slog.i(TAG, " -- NEW: mMatch=" 14601 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14602 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14603 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14604 } 14605 } 14606 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14607 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14608 && cur.mPref.sameSet(set)) { 14609 // Setting the preferred activity to what it happens to be already 14610 if (DEBUG_PREFERRED) { 14611 Slog.i(TAG, "Replacing with same preferred activity " 14612 + cur.mPref.mShortComponent + " for user " 14613 + userId + ":"); 14614 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14615 } 14616 return; 14617 } 14618 } 14619 14620 if (existing != null) { 14621 if (DEBUG_PREFERRED) { 14622 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14623 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14624 } 14625 for (int i = 0; i < existing.size(); i++) { 14626 PreferredActivity pa = existing.get(i); 14627 if (DEBUG_PREFERRED) { 14628 Slog.i(TAG, "Removing existing preferred activity " 14629 + pa.mPref.mComponent + ":"); 14630 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14631 } 14632 pir.removeFilter(pa); 14633 } 14634 } 14635 } 14636 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14637 "Replacing preferred"); 14638 } 14639 } 14640 14641 @Override 14642 public void clearPackagePreferredActivities(String packageName) { 14643 final int uid = Binder.getCallingUid(); 14644 // writer 14645 synchronized (mPackages) { 14646 PackageParser.Package pkg = mPackages.get(packageName); 14647 if (pkg == null || pkg.applicationInfo.uid != uid) { 14648 if (mContext.checkCallingOrSelfPermission( 14649 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14650 != PackageManager.PERMISSION_GRANTED) { 14651 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14652 < Build.VERSION_CODES.FROYO) { 14653 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14654 + Binder.getCallingUid()); 14655 return; 14656 } 14657 mContext.enforceCallingOrSelfPermission( 14658 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14659 } 14660 } 14661 14662 int user = UserHandle.getCallingUserId(); 14663 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14664 scheduleWritePackageRestrictionsLocked(user); 14665 } 14666 } 14667 } 14668 14669 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14670 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14671 ArrayList<PreferredActivity> removed = null; 14672 boolean changed = false; 14673 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14674 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14675 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14676 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14677 continue; 14678 } 14679 Iterator<PreferredActivity> it = pir.filterIterator(); 14680 while (it.hasNext()) { 14681 PreferredActivity pa = it.next(); 14682 // Mark entry for removal only if it matches the package name 14683 // and the entry is of type "always". 14684 if (packageName == null || 14685 (pa.mPref.mComponent.getPackageName().equals(packageName) 14686 && pa.mPref.mAlways)) { 14687 if (removed == null) { 14688 removed = new ArrayList<PreferredActivity>(); 14689 } 14690 removed.add(pa); 14691 } 14692 } 14693 if (removed != null) { 14694 for (int j=0; j<removed.size(); j++) { 14695 PreferredActivity pa = removed.get(j); 14696 pir.removeFilter(pa); 14697 } 14698 changed = true; 14699 } 14700 } 14701 return changed; 14702 } 14703 14704 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14705 private void clearIntentFilterVerificationsLPw(int userId) { 14706 final int packageCount = mPackages.size(); 14707 for (int i = 0; i < packageCount; i++) { 14708 PackageParser.Package pkg = mPackages.valueAt(i); 14709 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14710 } 14711 } 14712 14713 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14714 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14715 if (userId == UserHandle.USER_ALL) { 14716 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14717 sUserManager.getUserIds())) { 14718 for (int oneUserId : sUserManager.getUserIds()) { 14719 scheduleWritePackageRestrictionsLocked(oneUserId); 14720 } 14721 } 14722 } else { 14723 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14724 scheduleWritePackageRestrictionsLocked(userId); 14725 } 14726 } 14727 } 14728 14729 void clearDefaultBrowserIfNeeded(String packageName) { 14730 for (int oneUserId : sUserManager.getUserIds()) { 14731 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14732 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14733 if (packageName.equals(defaultBrowserPackageName)) { 14734 setDefaultBrowserPackageName(null, oneUserId); 14735 } 14736 } 14737 } 14738 14739 @Override 14740 public void resetApplicationPreferences(int userId) { 14741 mContext.enforceCallingOrSelfPermission( 14742 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14743 // writer 14744 synchronized (mPackages) { 14745 final long identity = Binder.clearCallingIdentity(); 14746 try { 14747 clearPackagePreferredActivitiesLPw(null, userId); 14748 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14749 // TODO: We have to reset the default SMS and Phone. This requires 14750 // significant refactoring to keep all default apps in the package 14751 // manager (cleaner but more work) or have the services provide 14752 // callbacks to the package manager to request a default app reset. 14753 applyFactoryDefaultBrowserLPw(userId); 14754 clearIntentFilterVerificationsLPw(userId); 14755 primeDomainVerificationsLPw(userId); 14756 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14757 scheduleWritePackageRestrictionsLocked(userId); 14758 } finally { 14759 Binder.restoreCallingIdentity(identity); 14760 } 14761 } 14762 } 14763 14764 @Override 14765 public int getPreferredActivities(List<IntentFilter> outFilters, 14766 List<ComponentName> outActivities, String packageName) { 14767 14768 int num = 0; 14769 final int userId = UserHandle.getCallingUserId(); 14770 // reader 14771 synchronized (mPackages) { 14772 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14773 if (pir != null) { 14774 final Iterator<PreferredActivity> it = pir.filterIterator(); 14775 while (it.hasNext()) { 14776 final PreferredActivity pa = it.next(); 14777 if (packageName == null 14778 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14779 && pa.mPref.mAlways)) { 14780 if (outFilters != null) { 14781 outFilters.add(new IntentFilter(pa)); 14782 } 14783 if (outActivities != null) { 14784 outActivities.add(pa.mPref.mComponent); 14785 } 14786 } 14787 } 14788 } 14789 } 14790 14791 return num; 14792 } 14793 14794 @Override 14795 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14796 int userId) { 14797 int callingUid = Binder.getCallingUid(); 14798 if (callingUid != Process.SYSTEM_UID) { 14799 throw new SecurityException( 14800 "addPersistentPreferredActivity can only be run by the system"); 14801 } 14802 if (filter.countActions() == 0) { 14803 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14804 return; 14805 } 14806 synchronized (mPackages) { 14807 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14808 ":"); 14809 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14810 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14811 new PersistentPreferredActivity(filter, activity)); 14812 scheduleWritePackageRestrictionsLocked(userId); 14813 } 14814 } 14815 14816 @Override 14817 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14818 int callingUid = Binder.getCallingUid(); 14819 if (callingUid != Process.SYSTEM_UID) { 14820 throw new SecurityException( 14821 "clearPackagePersistentPreferredActivities can only be run by the system"); 14822 } 14823 ArrayList<PersistentPreferredActivity> removed = null; 14824 boolean changed = false; 14825 synchronized (mPackages) { 14826 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14827 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14828 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14829 .valueAt(i); 14830 if (userId != thisUserId) { 14831 continue; 14832 } 14833 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14834 while (it.hasNext()) { 14835 PersistentPreferredActivity ppa = it.next(); 14836 // Mark entry for removal only if it matches the package name. 14837 if (ppa.mComponent.getPackageName().equals(packageName)) { 14838 if (removed == null) { 14839 removed = new ArrayList<PersistentPreferredActivity>(); 14840 } 14841 removed.add(ppa); 14842 } 14843 } 14844 if (removed != null) { 14845 for (int j=0; j<removed.size(); j++) { 14846 PersistentPreferredActivity ppa = removed.get(j); 14847 ppir.removeFilter(ppa); 14848 } 14849 changed = true; 14850 } 14851 } 14852 14853 if (changed) { 14854 scheduleWritePackageRestrictionsLocked(userId); 14855 } 14856 } 14857 } 14858 14859 /** 14860 * Common machinery for picking apart a restored XML blob and passing 14861 * it to a caller-supplied functor to be applied to the running system. 14862 */ 14863 private void restoreFromXml(XmlPullParser parser, int userId, 14864 String expectedStartTag, BlobXmlRestorer functor) 14865 throws IOException, XmlPullParserException { 14866 int type; 14867 while ((type = parser.next()) != XmlPullParser.START_TAG 14868 && type != XmlPullParser.END_DOCUMENT) { 14869 } 14870 if (type != XmlPullParser.START_TAG) { 14871 // oops didn't find a start tag?! 14872 if (DEBUG_BACKUP) { 14873 Slog.e(TAG, "Didn't find start tag during restore"); 14874 } 14875 return; 14876 } 14877Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 14878 // this is supposed to be TAG_PREFERRED_BACKUP 14879 if (!expectedStartTag.equals(parser.getName())) { 14880 if (DEBUG_BACKUP) { 14881 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14882 } 14883 return; 14884 } 14885 14886 // skip interfering stuff, then we're aligned with the backing implementation 14887 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14888Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 14889 functor.apply(parser, userId); 14890 } 14891 14892 private interface BlobXmlRestorer { 14893 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14894 } 14895 14896 /** 14897 * Non-Binder method, support for the backup/restore mechanism: write the 14898 * full set of preferred activities in its canonical XML format. Returns the 14899 * XML output as a byte array, or null if there is none. 14900 */ 14901 @Override 14902 public byte[] getPreferredActivityBackup(int userId) { 14903 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14904 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14905 } 14906 14907 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14908 try { 14909 final XmlSerializer serializer = new FastXmlSerializer(); 14910 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14911 serializer.startDocument(null, true); 14912 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14913 14914 synchronized (mPackages) { 14915 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14916 } 14917 14918 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14919 serializer.endDocument(); 14920 serializer.flush(); 14921 } catch (Exception e) { 14922 if (DEBUG_BACKUP) { 14923 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14924 } 14925 return null; 14926 } 14927 14928 return dataStream.toByteArray(); 14929 } 14930 14931 @Override 14932 public void restorePreferredActivities(byte[] backup, int userId) { 14933 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14934 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14935 } 14936 14937 try { 14938 final XmlPullParser parser = Xml.newPullParser(); 14939 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14940 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14941 new BlobXmlRestorer() { 14942 @Override 14943 public void apply(XmlPullParser parser, int userId) 14944 throws XmlPullParserException, IOException { 14945 synchronized (mPackages) { 14946 mSettings.readPreferredActivitiesLPw(parser, userId); 14947 } 14948 } 14949 } ); 14950 } catch (Exception e) { 14951 if (DEBUG_BACKUP) { 14952 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14953 } 14954 } 14955 } 14956 14957 /** 14958 * Non-Binder method, support for the backup/restore mechanism: write the 14959 * default browser (etc) settings in its canonical XML format. Returns the default 14960 * browser XML representation as a byte array, or null if there is none. 14961 */ 14962 @Override 14963 public byte[] getDefaultAppsBackup(int userId) { 14964 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14965 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14966 } 14967 14968 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14969 try { 14970 final XmlSerializer serializer = new FastXmlSerializer(); 14971 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14972 serializer.startDocument(null, true); 14973 serializer.startTag(null, TAG_DEFAULT_APPS); 14974 14975 synchronized (mPackages) { 14976 mSettings.writeDefaultAppsLPr(serializer, userId); 14977 } 14978 14979 serializer.endTag(null, TAG_DEFAULT_APPS); 14980 serializer.endDocument(); 14981 serializer.flush(); 14982 } catch (Exception e) { 14983 if (DEBUG_BACKUP) { 14984 Slog.e(TAG, "Unable to write default apps for backup", e); 14985 } 14986 return null; 14987 } 14988 14989 return dataStream.toByteArray(); 14990 } 14991 14992 @Override 14993 public void restoreDefaultApps(byte[] backup, int userId) { 14994 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14995 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14996 } 14997 14998 try { 14999 final XmlPullParser parser = Xml.newPullParser(); 15000 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15001 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 15002 new BlobXmlRestorer() { 15003 @Override 15004 public void apply(XmlPullParser parser, int userId) 15005 throws XmlPullParserException, IOException { 15006 synchronized (mPackages) { 15007 mSettings.readDefaultAppsLPw(parser, userId); 15008 } 15009 } 15010 } ); 15011 } catch (Exception e) { 15012 if (DEBUG_BACKUP) { 15013 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 15014 } 15015 } 15016 } 15017 15018 @Override 15019 public byte[] getIntentFilterVerificationBackup(int userId) { 15020 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15021 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 15022 } 15023 15024 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15025 try { 15026 final XmlSerializer serializer = new FastXmlSerializer(); 15027 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15028 serializer.startDocument(null, true); 15029 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 15030 15031 synchronized (mPackages) { 15032 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 15033 } 15034 15035 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 15036 serializer.endDocument(); 15037 serializer.flush(); 15038 } catch (Exception e) { 15039 if (DEBUG_BACKUP) { 15040 Slog.e(TAG, "Unable to write default apps for backup", e); 15041 } 15042 return null; 15043 } 15044 15045 return dataStream.toByteArray(); 15046 } 15047 15048 @Override 15049 public void restoreIntentFilterVerification(byte[] backup, int userId) { 15050 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15051 throw new SecurityException("Only the system may call restorePreferredActivities()"); 15052 } 15053 15054 try { 15055 final XmlPullParser parser = Xml.newPullParser(); 15056 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15057 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 15058 new BlobXmlRestorer() { 15059 @Override 15060 public void apply(XmlPullParser parser, int userId) 15061 throws XmlPullParserException, IOException { 15062 synchronized (mPackages) { 15063 mSettings.readAllDomainVerificationsLPr(parser, userId); 15064 mSettings.writeLPr(); 15065 } 15066 } 15067 } ); 15068 } catch (Exception e) { 15069 if (DEBUG_BACKUP) { 15070 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15071 } 15072 } 15073 } 15074 15075 @Override 15076 public byte[] getPermissionGrantBackup(int userId) { 15077 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15078 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 15079 } 15080 15081 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15082 try { 15083 final XmlSerializer serializer = new FastXmlSerializer(); 15084 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15085 serializer.startDocument(null, true); 15086 serializer.startTag(null, TAG_PERMISSION_BACKUP); 15087 15088 synchronized (mPackages) { 15089 serializeRuntimePermissionGrantsLPr(serializer, userId); 15090 } 15091 15092 serializer.endTag(null, TAG_PERMISSION_BACKUP); 15093 serializer.endDocument(); 15094 serializer.flush(); 15095 } catch (Exception e) { 15096 if (DEBUG_BACKUP) { 15097 Slog.e(TAG, "Unable to write default apps for backup", e); 15098 } 15099 return null; 15100 } 15101 15102 return dataStream.toByteArray(); 15103 } 15104 15105 @Override 15106 public void restorePermissionGrants(byte[] backup, int userId) { 15107 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15108 throw new SecurityException("Only the system may call restorePermissionGrants()"); 15109 } 15110 15111 try { 15112 final XmlPullParser parser = Xml.newPullParser(); 15113 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15114 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 15115 new BlobXmlRestorer() { 15116 @Override 15117 public void apply(XmlPullParser parser, int userId) 15118 throws XmlPullParserException, IOException { 15119 synchronized (mPackages) { 15120 processRestoredPermissionGrantsLPr(parser, userId); 15121 } 15122 } 15123 } ); 15124 } catch (Exception e) { 15125 if (DEBUG_BACKUP) { 15126 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15127 } 15128 } 15129 } 15130 15131 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 15132 throws IOException { 15133 serializer.startTag(null, TAG_ALL_GRANTS); 15134 15135 final int N = mSettings.mPackages.size(); 15136 for (int i = 0; i < N; i++) { 15137 final PackageSetting ps = mSettings.mPackages.valueAt(i); 15138 boolean pkgGrantsKnown = false; 15139 15140 PermissionsState packagePerms = ps.getPermissionsState(); 15141 15142 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 15143 final int grantFlags = state.getFlags(); 15144 // only look at grants that are not system/policy fixed 15145 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 15146 final boolean isGranted = state.isGranted(); 15147 // And only back up the user-twiddled state bits 15148 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 15149 final String packageName = mSettings.mPackages.keyAt(i); 15150 if (!pkgGrantsKnown) { 15151 serializer.startTag(null, TAG_GRANT); 15152 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 15153 pkgGrantsKnown = true; 15154 } 15155 15156 final boolean userSet = 15157 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 15158 final boolean userFixed = 15159 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 15160 final boolean revoke = 15161 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 15162 15163 serializer.startTag(null, TAG_PERMISSION); 15164 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 15165 if (isGranted) { 15166 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 15167 } 15168 if (userSet) { 15169 serializer.attribute(null, ATTR_USER_SET, "true"); 15170 } 15171 if (userFixed) { 15172 serializer.attribute(null, ATTR_USER_FIXED, "true"); 15173 } 15174 if (revoke) { 15175 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 15176 } 15177 serializer.endTag(null, TAG_PERMISSION); 15178 } 15179 } 15180 } 15181 15182 if (pkgGrantsKnown) { 15183 serializer.endTag(null, TAG_GRANT); 15184 } 15185 } 15186 15187 serializer.endTag(null, TAG_ALL_GRANTS); 15188 } 15189 15190 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 15191 throws XmlPullParserException, IOException { 15192 String pkgName = null; 15193 int outerDepth = parser.getDepth(); 15194 int type; 15195 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 15196 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 15197 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 15198 continue; 15199 } 15200 15201 final String tagName = parser.getName(); 15202 if (tagName.equals(TAG_GRANT)) { 15203 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 15204 if (DEBUG_BACKUP) { 15205 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 15206 } 15207 } else if (tagName.equals(TAG_PERMISSION)) { 15208 15209 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 15210 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 15211 15212 int newFlagSet = 0; 15213 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 15214 newFlagSet |= FLAG_PERMISSION_USER_SET; 15215 } 15216 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 15217 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 15218 } 15219 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 15220 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 15221 } 15222 if (DEBUG_BACKUP) { 15223 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 15224 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 15225 } 15226 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15227 if (ps != null) { 15228 // Already installed so we apply the grant immediately 15229 if (DEBUG_BACKUP) { 15230 Slog.v(TAG, " + already installed; applying"); 15231 } 15232 PermissionsState perms = ps.getPermissionsState(); 15233 BasePermission bp = mSettings.mPermissions.get(permName); 15234 if (bp != null) { 15235 if (isGranted) { 15236 perms.grantRuntimePermission(bp, userId); 15237 } 15238 if (newFlagSet != 0) { 15239 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 15240 } 15241 } 15242 } else { 15243 // Need to wait for post-restore install to apply the grant 15244 if (DEBUG_BACKUP) { 15245 Slog.v(TAG, " - not yet installed; saving for later"); 15246 } 15247 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 15248 isGranted, newFlagSet, userId); 15249 } 15250 } else { 15251 PackageManagerService.reportSettingsProblem(Log.WARN, 15252 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 15253 XmlUtils.skipCurrentTag(parser); 15254 } 15255 } 15256 15257 scheduleWriteSettingsLocked(); 15258 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15259 } 15260 15261 @Override 15262 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 15263 int sourceUserId, int targetUserId, int flags) { 15264 mContext.enforceCallingOrSelfPermission( 15265 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15266 int callingUid = Binder.getCallingUid(); 15267 enforceOwnerRights(ownerPackage, callingUid); 15268 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15269 if (intentFilter.countActions() == 0) { 15270 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 15271 return; 15272 } 15273 synchronized (mPackages) { 15274 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 15275 ownerPackage, targetUserId, flags); 15276 CrossProfileIntentResolver resolver = 15277 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15278 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 15279 // We have all those whose filter is equal. Now checking if the rest is equal as well. 15280 if (existing != null) { 15281 int size = existing.size(); 15282 for (int i = 0; i < size; i++) { 15283 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 15284 return; 15285 } 15286 } 15287 } 15288 resolver.addFilter(newFilter); 15289 scheduleWritePackageRestrictionsLocked(sourceUserId); 15290 } 15291 } 15292 15293 @Override 15294 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 15295 mContext.enforceCallingOrSelfPermission( 15296 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15297 int callingUid = Binder.getCallingUid(); 15298 enforceOwnerRights(ownerPackage, callingUid); 15299 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15300 synchronized (mPackages) { 15301 CrossProfileIntentResolver resolver = 15302 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15303 ArraySet<CrossProfileIntentFilter> set = 15304 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 15305 for (CrossProfileIntentFilter filter : set) { 15306 if (filter.getOwnerPackage().equals(ownerPackage)) { 15307 resolver.removeFilter(filter); 15308 } 15309 } 15310 scheduleWritePackageRestrictionsLocked(sourceUserId); 15311 } 15312 } 15313 15314 // Enforcing that callingUid is owning pkg on userId 15315 private void enforceOwnerRights(String pkg, int callingUid) { 15316 // The system owns everything. 15317 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 15318 return; 15319 } 15320 int callingUserId = UserHandle.getUserId(callingUid); 15321 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 15322 if (pi == null) { 15323 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 15324 + callingUserId); 15325 } 15326 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 15327 throw new SecurityException("Calling uid " + callingUid 15328 + " does not own package " + pkg); 15329 } 15330 } 15331 15332 @Override 15333 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 15334 Intent intent = new Intent(Intent.ACTION_MAIN); 15335 intent.addCategory(Intent.CATEGORY_HOME); 15336 15337 final int callingUserId = UserHandle.getCallingUserId(); 15338 List<ResolveInfo> list = queryIntentActivities(intent, null, 15339 PackageManager.GET_META_DATA, callingUserId); 15340 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 15341 true, false, false, callingUserId); 15342 15343 allHomeCandidates.clear(); 15344 if (list != null) { 15345 for (ResolveInfo ri : list) { 15346 allHomeCandidates.add(ri); 15347 } 15348 } 15349 return (preferred == null || preferred.activityInfo == null) 15350 ? null 15351 : new ComponentName(preferred.activityInfo.packageName, 15352 preferred.activityInfo.name); 15353 } 15354 15355 @Override 15356 public void setApplicationEnabledSetting(String appPackageName, 15357 int newState, int flags, int userId, String callingPackage) { 15358 if (!sUserManager.exists(userId)) return; 15359 if (callingPackage == null) { 15360 callingPackage = Integer.toString(Binder.getCallingUid()); 15361 } 15362 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 15363 } 15364 15365 @Override 15366 public void setComponentEnabledSetting(ComponentName componentName, 15367 int newState, int flags, int userId) { 15368 if (!sUserManager.exists(userId)) return; 15369 setEnabledSetting(componentName.getPackageName(), 15370 componentName.getClassName(), newState, flags, userId, null); 15371 } 15372 15373 private void setEnabledSetting(final String packageName, String className, int newState, 15374 final int flags, int userId, String callingPackage) { 15375 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 15376 || newState == COMPONENT_ENABLED_STATE_ENABLED 15377 || newState == COMPONENT_ENABLED_STATE_DISABLED 15378 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 15379 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 15380 throw new IllegalArgumentException("Invalid new component state: " 15381 + newState); 15382 } 15383 PackageSetting pkgSetting; 15384 final int uid = Binder.getCallingUid(); 15385 final int permission = mContext.checkCallingOrSelfPermission( 15386 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15387 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 15388 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15389 boolean sendNow = false; 15390 boolean isApp = (className == null); 15391 String componentName = isApp ? packageName : className; 15392 int packageUid = -1; 15393 ArrayList<String> components; 15394 15395 // writer 15396 synchronized (mPackages) { 15397 pkgSetting = mSettings.mPackages.get(packageName); 15398 if (pkgSetting == null) { 15399 if (className == null) { 15400 throw new IllegalArgumentException("Unknown package: " + packageName); 15401 } 15402 throw new IllegalArgumentException( 15403 "Unknown component: " + packageName + "/" + className); 15404 } 15405 // Allow root and verify that userId is not being specified by a different user 15406 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 15407 throw new SecurityException( 15408 "Permission Denial: attempt to change component state from pid=" 15409 + Binder.getCallingPid() 15410 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 15411 } 15412 if (className == null) { 15413 // We're dealing with an application/package level state change 15414 if (pkgSetting.getEnabled(userId) == newState) { 15415 // Nothing to do 15416 return; 15417 } 15418 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 15419 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 15420 // Don't care about who enables an app. 15421 callingPackage = null; 15422 } 15423 pkgSetting.setEnabled(newState, userId, callingPackage); 15424 // pkgSetting.pkg.mSetEnabled = newState; 15425 } else { 15426 // We're dealing with a component level state change 15427 // First, verify that this is a valid class name. 15428 PackageParser.Package pkg = pkgSetting.pkg; 15429 if (pkg == null || !pkg.hasComponentClassName(className)) { 15430 if (pkg != null && 15431 pkg.applicationInfo.targetSdkVersion >= 15432 Build.VERSION_CODES.JELLY_BEAN) { 15433 throw new IllegalArgumentException("Component class " + className 15434 + " does not exist in " + packageName); 15435 } else { 15436 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 15437 + className + " does not exist in " + packageName); 15438 } 15439 } 15440 switch (newState) { 15441 case COMPONENT_ENABLED_STATE_ENABLED: 15442 if (!pkgSetting.enableComponentLPw(className, userId)) { 15443 return; 15444 } 15445 break; 15446 case COMPONENT_ENABLED_STATE_DISABLED: 15447 if (!pkgSetting.disableComponentLPw(className, userId)) { 15448 return; 15449 } 15450 break; 15451 case COMPONENT_ENABLED_STATE_DEFAULT: 15452 if (!pkgSetting.restoreComponentLPw(className, userId)) { 15453 return; 15454 } 15455 break; 15456 default: 15457 Slog.e(TAG, "Invalid new component state: " + newState); 15458 return; 15459 } 15460 } 15461 scheduleWritePackageRestrictionsLocked(userId); 15462 components = mPendingBroadcasts.get(userId, packageName); 15463 final boolean newPackage = components == null; 15464 if (newPackage) { 15465 components = new ArrayList<String>(); 15466 } 15467 if (!components.contains(componentName)) { 15468 components.add(componentName); 15469 } 15470 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 15471 sendNow = true; 15472 // Purge entry from pending broadcast list if another one exists already 15473 // since we are sending one right away. 15474 mPendingBroadcasts.remove(userId, packageName); 15475 } else { 15476 if (newPackage) { 15477 mPendingBroadcasts.put(userId, packageName, components); 15478 } 15479 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 15480 // Schedule a message 15481 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 15482 } 15483 } 15484 } 15485 15486 long callingId = Binder.clearCallingIdentity(); 15487 try { 15488 if (sendNow) { 15489 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 15490 sendPackageChangedBroadcast(packageName, 15491 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 15492 } 15493 } finally { 15494 Binder.restoreCallingIdentity(callingId); 15495 } 15496 } 15497 15498 private void sendPackageChangedBroadcast(String packageName, 15499 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 15500 if (DEBUG_INSTALL) 15501 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 15502 + componentNames); 15503 Bundle extras = new Bundle(4); 15504 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 15505 String nameList[] = new String[componentNames.size()]; 15506 componentNames.toArray(nameList); 15507 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 15508 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 15509 extras.putInt(Intent.EXTRA_UID, packageUid); 15510 // If this is not reporting a change of the overall package, then only send it 15511 // to registered receivers. We don't want to launch a swath of apps for every 15512 // little component state change. 15513 final int flags = !componentNames.contains(packageName) 15514 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 15515 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 15516 new int[] {UserHandle.getUserId(packageUid)}); 15517 } 15518 15519 @Override 15520 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 15521 if (!sUserManager.exists(userId)) return; 15522 final int uid = Binder.getCallingUid(); 15523 final int permission = mContext.checkCallingOrSelfPermission( 15524 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15525 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15526 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 15527 // writer 15528 synchronized (mPackages) { 15529 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 15530 allowedByPermission, uid, userId)) { 15531 scheduleWritePackageRestrictionsLocked(userId); 15532 } 15533 } 15534 } 15535 15536 @Override 15537 public String getInstallerPackageName(String packageName) { 15538 // reader 15539 synchronized (mPackages) { 15540 return mSettings.getInstallerPackageNameLPr(packageName); 15541 } 15542 } 15543 15544 @Override 15545 public int getApplicationEnabledSetting(String packageName, int userId) { 15546 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15547 int uid = Binder.getCallingUid(); 15548 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 15549 // reader 15550 synchronized (mPackages) { 15551 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 15552 } 15553 } 15554 15555 @Override 15556 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 15557 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15558 int uid = Binder.getCallingUid(); 15559 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 15560 // reader 15561 synchronized (mPackages) { 15562 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 15563 } 15564 } 15565 15566 @Override 15567 public void enterSafeMode() { 15568 enforceSystemOrRoot("Only the system can request entering safe mode"); 15569 15570 if (!mSystemReady) { 15571 mSafeMode = true; 15572 } 15573 } 15574 15575 @Override 15576 public void systemReady() { 15577 mSystemReady = true; 15578 15579 // Read the compatibilty setting when the system is ready. 15580 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 15581 mContext.getContentResolver(), 15582 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 15583 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 15584 if (DEBUG_SETTINGS) { 15585 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 15586 } 15587 15588 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 15589 15590 synchronized (mPackages) { 15591 // Verify that all of the preferred activity components actually 15592 // exist. It is possible for applications to be updated and at 15593 // that point remove a previously declared activity component that 15594 // had been set as a preferred activity. We try to clean this up 15595 // the next time we encounter that preferred activity, but it is 15596 // possible for the user flow to never be able to return to that 15597 // situation so here we do a sanity check to make sure we haven't 15598 // left any junk around. 15599 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 15600 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15601 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15602 removed.clear(); 15603 for (PreferredActivity pa : pir.filterSet()) { 15604 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 15605 removed.add(pa); 15606 } 15607 } 15608 if (removed.size() > 0) { 15609 for (int r=0; r<removed.size(); r++) { 15610 PreferredActivity pa = removed.get(r); 15611 Slog.w(TAG, "Removing dangling preferred activity: " 15612 + pa.mPref.mComponent); 15613 pir.removeFilter(pa); 15614 } 15615 mSettings.writePackageRestrictionsLPr( 15616 mSettings.mPreferredActivities.keyAt(i)); 15617 } 15618 } 15619 15620 for (int userId : UserManagerService.getInstance().getUserIds()) { 15621 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 15622 grantPermissionsUserIds = ArrayUtils.appendInt( 15623 grantPermissionsUserIds, userId); 15624 } 15625 } 15626 } 15627 sUserManager.systemReady(); 15628 15629 // If we upgraded grant all default permissions before kicking off. 15630 for (int userId : grantPermissionsUserIds) { 15631 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15632 } 15633 15634 // Kick off any messages waiting for system ready 15635 if (mPostSystemReadyMessages != null) { 15636 for (Message msg : mPostSystemReadyMessages) { 15637 msg.sendToTarget(); 15638 } 15639 mPostSystemReadyMessages = null; 15640 } 15641 15642 // Watch for external volumes that come and go over time 15643 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15644 storage.registerListener(mStorageListener); 15645 15646 mInstallerService.systemReady(); 15647 mPackageDexOptimizer.systemReady(); 15648 15649 MountServiceInternal mountServiceInternal = LocalServices.getService( 15650 MountServiceInternal.class); 15651 mountServiceInternal.addExternalStoragePolicy( 15652 new MountServiceInternal.ExternalStorageMountPolicy() { 15653 @Override 15654 public int getMountMode(int uid, String packageName) { 15655 if (Process.isIsolated(uid)) { 15656 return Zygote.MOUNT_EXTERNAL_NONE; 15657 } 15658 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15659 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15660 } 15661 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15662 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15663 } 15664 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15665 return Zygote.MOUNT_EXTERNAL_READ; 15666 } 15667 return Zygote.MOUNT_EXTERNAL_WRITE; 15668 } 15669 15670 @Override 15671 public boolean hasExternalStorage(int uid, String packageName) { 15672 return true; 15673 } 15674 }); 15675 } 15676 15677 @Override 15678 public boolean isSafeMode() { 15679 return mSafeMode; 15680 } 15681 15682 @Override 15683 public boolean hasSystemUidErrors() { 15684 return mHasSystemUidErrors; 15685 } 15686 15687 static String arrayToString(int[] array) { 15688 StringBuffer buf = new StringBuffer(128); 15689 buf.append('['); 15690 if (array != null) { 15691 for (int i=0; i<array.length; i++) { 15692 if (i > 0) buf.append(", "); 15693 buf.append(array[i]); 15694 } 15695 } 15696 buf.append(']'); 15697 return buf.toString(); 15698 } 15699 15700 static class DumpState { 15701 public static final int DUMP_LIBS = 1 << 0; 15702 public static final int DUMP_FEATURES = 1 << 1; 15703 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 15704 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 15705 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 15706 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 15707 public static final int DUMP_PERMISSIONS = 1 << 6; 15708 public static final int DUMP_PACKAGES = 1 << 7; 15709 public static final int DUMP_SHARED_USERS = 1 << 8; 15710 public static final int DUMP_MESSAGES = 1 << 9; 15711 public static final int DUMP_PROVIDERS = 1 << 10; 15712 public static final int DUMP_VERIFIERS = 1 << 11; 15713 public static final int DUMP_PREFERRED = 1 << 12; 15714 public static final int DUMP_PREFERRED_XML = 1 << 13; 15715 public static final int DUMP_KEYSETS = 1 << 14; 15716 public static final int DUMP_VERSION = 1 << 15; 15717 public static final int DUMP_INSTALLS = 1 << 16; 15718 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 15719 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 15720 15721 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15722 15723 private int mTypes; 15724 15725 private int mOptions; 15726 15727 private boolean mTitlePrinted; 15728 15729 private SharedUserSetting mSharedUser; 15730 15731 public boolean isDumping(int type) { 15732 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15733 return true; 15734 } 15735 15736 return (mTypes & type) != 0; 15737 } 15738 15739 public void setDump(int type) { 15740 mTypes |= type; 15741 } 15742 15743 public boolean isOptionEnabled(int option) { 15744 return (mOptions & option) != 0; 15745 } 15746 15747 public void setOptionEnabled(int option) { 15748 mOptions |= option; 15749 } 15750 15751 public boolean onTitlePrinted() { 15752 final boolean printed = mTitlePrinted; 15753 mTitlePrinted = true; 15754 return printed; 15755 } 15756 15757 public boolean getTitlePrinted() { 15758 return mTitlePrinted; 15759 } 15760 15761 public void setTitlePrinted(boolean enabled) { 15762 mTitlePrinted = enabled; 15763 } 15764 15765 public SharedUserSetting getSharedUser() { 15766 return mSharedUser; 15767 } 15768 15769 public void setSharedUser(SharedUserSetting user) { 15770 mSharedUser = user; 15771 } 15772 } 15773 15774 @Override 15775 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15776 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15777 (new PackageManagerShellCommand(this)).exec( 15778 this, in, out, err, args, resultReceiver); 15779 } 15780 15781 @Override 15782 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15783 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15784 != PackageManager.PERMISSION_GRANTED) { 15785 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15786 + Binder.getCallingPid() 15787 + ", uid=" + Binder.getCallingUid() 15788 + " without permission " 15789 + android.Manifest.permission.DUMP); 15790 return; 15791 } 15792 15793 DumpState dumpState = new DumpState(); 15794 boolean fullPreferred = false; 15795 boolean checkin = false; 15796 15797 String packageName = null; 15798 ArraySet<String> permissionNames = null; 15799 15800 int opti = 0; 15801 while (opti < args.length) { 15802 String opt = args[opti]; 15803 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15804 break; 15805 } 15806 opti++; 15807 15808 if ("-a".equals(opt)) { 15809 // Right now we only know how to print all. 15810 } else if ("-h".equals(opt)) { 15811 pw.println("Package manager dump options:"); 15812 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15813 pw.println(" --checkin: dump for a checkin"); 15814 pw.println(" -f: print details of intent filters"); 15815 pw.println(" -h: print this help"); 15816 pw.println(" cmd may be one of:"); 15817 pw.println(" l[ibraries]: list known shared libraries"); 15818 pw.println(" f[eatures]: list device features"); 15819 pw.println(" k[eysets]: print known keysets"); 15820 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 15821 pw.println(" perm[issions]: dump permissions"); 15822 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15823 pw.println(" pref[erred]: print preferred package settings"); 15824 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15825 pw.println(" prov[iders]: dump content providers"); 15826 pw.println(" p[ackages]: dump installed packages"); 15827 pw.println(" s[hared-users]: dump shared user IDs"); 15828 pw.println(" m[essages]: print collected runtime messages"); 15829 pw.println(" v[erifiers]: print package verifier info"); 15830 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15831 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15832 pw.println(" version: print database version info"); 15833 pw.println(" write: write current settings now"); 15834 pw.println(" installs: details about install sessions"); 15835 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15836 pw.println(" <package.name>: info about given package"); 15837 return; 15838 } else if ("--checkin".equals(opt)) { 15839 checkin = true; 15840 } else if ("-f".equals(opt)) { 15841 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15842 } else { 15843 pw.println("Unknown argument: " + opt + "; use -h for help"); 15844 } 15845 } 15846 15847 // Is the caller requesting to dump a particular piece of data? 15848 if (opti < args.length) { 15849 String cmd = args[opti]; 15850 opti++; 15851 // Is this a package name? 15852 if ("android".equals(cmd) || cmd.contains(".")) { 15853 packageName = cmd; 15854 // When dumping a single package, we always dump all of its 15855 // filter information since the amount of data will be reasonable. 15856 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15857 } else if ("check-permission".equals(cmd)) { 15858 if (opti >= args.length) { 15859 pw.println("Error: check-permission missing permission argument"); 15860 return; 15861 } 15862 String perm = args[opti]; 15863 opti++; 15864 if (opti >= args.length) { 15865 pw.println("Error: check-permission missing package argument"); 15866 return; 15867 } 15868 String pkg = args[opti]; 15869 opti++; 15870 int user = UserHandle.getUserId(Binder.getCallingUid()); 15871 if (opti < args.length) { 15872 try { 15873 user = Integer.parseInt(args[opti]); 15874 } catch (NumberFormatException e) { 15875 pw.println("Error: check-permission user argument is not a number: " 15876 + args[opti]); 15877 return; 15878 } 15879 } 15880 pw.println(checkPermission(perm, pkg, user)); 15881 return; 15882 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15883 dumpState.setDump(DumpState.DUMP_LIBS); 15884 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15885 dumpState.setDump(DumpState.DUMP_FEATURES); 15886 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15887 if (opti >= args.length) { 15888 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 15889 | DumpState.DUMP_SERVICE_RESOLVERS 15890 | DumpState.DUMP_RECEIVER_RESOLVERS 15891 | DumpState.DUMP_CONTENT_RESOLVERS); 15892 } else { 15893 while (opti < args.length) { 15894 String name = args[opti]; 15895 if ("a".equals(name) || "activity".equals(name)) { 15896 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 15897 } else if ("s".equals(name) || "service".equals(name)) { 15898 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 15899 } else if ("r".equals(name) || "receiver".equals(name)) { 15900 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 15901 } else if ("c".equals(name) || "content".equals(name)) { 15902 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 15903 } else { 15904 pw.println("Error: unknown resolver table type: " + name); 15905 return; 15906 } 15907 opti++; 15908 } 15909 } 15910 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15911 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15912 } else if ("permission".equals(cmd)) { 15913 if (opti >= args.length) { 15914 pw.println("Error: permission requires permission name"); 15915 return; 15916 } 15917 permissionNames = new ArraySet<>(); 15918 while (opti < args.length) { 15919 permissionNames.add(args[opti]); 15920 opti++; 15921 } 15922 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15923 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15924 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15925 dumpState.setDump(DumpState.DUMP_PREFERRED); 15926 } else if ("preferred-xml".equals(cmd)) { 15927 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15928 if (opti < args.length && "--full".equals(args[opti])) { 15929 fullPreferred = true; 15930 opti++; 15931 } 15932 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15933 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15934 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15935 dumpState.setDump(DumpState.DUMP_PACKAGES); 15936 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15937 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15938 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15939 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15940 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15941 dumpState.setDump(DumpState.DUMP_MESSAGES); 15942 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15943 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15944 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15945 || "intent-filter-verifiers".equals(cmd)) { 15946 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15947 } else if ("version".equals(cmd)) { 15948 dumpState.setDump(DumpState.DUMP_VERSION); 15949 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15950 dumpState.setDump(DumpState.DUMP_KEYSETS); 15951 } else if ("installs".equals(cmd)) { 15952 dumpState.setDump(DumpState.DUMP_INSTALLS); 15953 } else if ("write".equals(cmd)) { 15954 synchronized (mPackages) { 15955 mSettings.writeLPr(); 15956 pw.println("Settings written."); 15957 return; 15958 } 15959 } 15960 } 15961 15962 if (checkin) { 15963 pw.println("vers,1"); 15964 } 15965 15966 // reader 15967 synchronized (mPackages) { 15968 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15969 if (!checkin) { 15970 if (dumpState.onTitlePrinted()) 15971 pw.println(); 15972 pw.println("Database versions:"); 15973 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15974 } 15975 } 15976 15977 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15978 if (!checkin) { 15979 if (dumpState.onTitlePrinted()) 15980 pw.println(); 15981 pw.println("Verifiers:"); 15982 pw.print(" Required: "); 15983 pw.print(mRequiredVerifierPackage); 15984 pw.print(" (uid="); 15985 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15986 UserHandle.USER_SYSTEM)); 15987 pw.println(")"); 15988 } else if (mRequiredVerifierPackage != null) { 15989 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15990 pw.print(","); 15991 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15992 UserHandle.USER_SYSTEM)); 15993 } 15994 } 15995 15996 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15997 packageName == null) { 15998 if (mIntentFilterVerifierComponent != null) { 15999 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 16000 if (!checkin) { 16001 if (dumpState.onTitlePrinted()) 16002 pw.println(); 16003 pw.println("Intent Filter Verifier:"); 16004 pw.print(" Using: "); 16005 pw.print(verifierPackageName); 16006 pw.print(" (uid="); 16007 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 16008 UserHandle.USER_SYSTEM)); 16009 pw.println(")"); 16010 } else if (verifierPackageName != null) { 16011 pw.print("ifv,"); pw.print(verifierPackageName); 16012 pw.print(","); 16013 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 16014 UserHandle.USER_SYSTEM)); 16015 } 16016 } else { 16017 pw.println(); 16018 pw.println("No Intent Filter Verifier available!"); 16019 } 16020 } 16021 16022 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 16023 boolean printedHeader = false; 16024 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 16025 while (it.hasNext()) { 16026 String name = it.next(); 16027 SharedLibraryEntry ent = mSharedLibraries.get(name); 16028 if (!checkin) { 16029 if (!printedHeader) { 16030 if (dumpState.onTitlePrinted()) 16031 pw.println(); 16032 pw.println("Libraries:"); 16033 printedHeader = true; 16034 } 16035 pw.print(" "); 16036 } else { 16037 pw.print("lib,"); 16038 } 16039 pw.print(name); 16040 if (!checkin) { 16041 pw.print(" -> "); 16042 } 16043 if (ent.path != null) { 16044 if (!checkin) { 16045 pw.print("(jar) "); 16046 pw.print(ent.path); 16047 } else { 16048 pw.print(",jar,"); 16049 pw.print(ent.path); 16050 } 16051 } else { 16052 if (!checkin) { 16053 pw.print("(apk) "); 16054 pw.print(ent.apk); 16055 } else { 16056 pw.print(",apk,"); 16057 pw.print(ent.apk); 16058 } 16059 } 16060 pw.println(); 16061 } 16062 } 16063 16064 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 16065 if (dumpState.onTitlePrinted()) 16066 pw.println(); 16067 if (!checkin) { 16068 pw.println("Features:"); 16069 } 16070 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 16071 while (it.hasNext()) { 16072 String name = it.next(); 16073 if (!checkin) { 16074 pw.print(" "); 16075 } else { 16076 pw.print("feat,"); 16077 } 16078 pw.println(name); 16079 } 16080 } 16081 16082 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 16083 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 16084 : "Activity Resolver Table:", " ", packageName, 16085 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16086 dumpState.setTitlePrinted(true); 16087 } 16088 } 16089 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 16090 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 16091 : "Receiver Resolver Table:", " ", packageName, 16092 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16093 dumpState.setTitlePrinted(true); 16094 } 16095 } 16096 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 16097 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 16098 : "Service Resolver Table:", " ", packageName, 16099 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16100 dumpState.setTitlePrinted(true); 16101 } 16102 } 16103 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 16104 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 16105 : "Provider Resolver Table:", " ", packageName, 16106 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16107 dumpState.setTitlePrinted(true); 16108 } 16109 } 16110 16111 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 16112 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16113 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16114 int user = mSettings.mPreferredActivities.keyAt(i); 16115 if (pir.dump(pw, 16116 dumpState.getTitlePrinted() 16117 ? "\nPreferred Activities User " + user + ":" 16118 : "Preferred Activities User " + user + ":", " ", 16119 packageName, true, false)) { 16120 dumpState.setTitlePrinted(true); 16121 } 16122 } 16123 } 16124 16125 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 16126 pw.flush(); 16127 FileOutputStream fout = new FileOutputStream(fd); 16128 BufferedOutputStream str = new BufferedOutputStream(fout); 16129 XmlSerializer serializer = new FastXmlSerializer(); 16130 try { 16131 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 16132 serializer.startDocument(null, true); 16133 serializer.setFeature( 16134 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 16135 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 16136 serializer.endDocument(); 16137 serializer.flush(); 16138 } catch (IllegalArgumentException e) { 16139 pw.println("Failed writing: " + e); 16140 } catch (IllegalStateException e) { 16141 pw.println("Failed writing: " + e); 16142 } catch (IOException e) { 16143 pw.println("Failed writing: " + e); 16144 } 16145 } 16146 16147 if (!checkin 16148 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 16149 && packageName == null) { 16150 pw.println(); 16151 int count = mSettings.mPackages.size(); 16152 if (count == 0) { 16153 pw.println("No applications!"); 16154 pw.println(); 16155 } else { 16156 final String prefix = " "; 16157 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 16158 if (allPackageSettings.size() == 0) { 16159 pw.println("No domain preferred apps!"); 16160 pw.println(); 16161 } else { 16162 pw.println("App verification status:"); 16163 pw.println(); 16164 count = 0; 16165 for (PackageSetting ps : allPackageSettings) { 16166 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 16167 if (ivi == null || ivi.getPackageName() == null) continue; 16168 pw.println(prefix + "Package: " + ivi.getPackageName()); 16169 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 16170 pw.println(prefix + "Status: " + ivi.getStatusString()); 16171 pw.println(); 16172 count++; 16173 } 16174 if (count == 0) { 16175 pw.println(prefix + "No app verification established."); 16176 pw.println(); 16177 } 16178 for (int userId : sUserManager.getUserIds()) { 16179 pw.println("App linkages for user " + userId + ":"); 16180 pw.println(); 16181 count = 0; 16182 for (PackageSetting ps : allPackageSettings) { 16183 final long status = ps.getDomainVerificationStatusForUser(userId); 16184 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 16185 continue; 16186 } 16187 pw.println(prefix + "Package: " + ps.name); 16188 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 16189 String statusStr = IntentFilterVerificationInfo. 16190 getStatusStringFromValue(status); 16191 pw.println(prefix + "Status: " + statusStr); 16192 pw.println(); 16193 count++; 16194 } 16195 if (count == 0) { 16196 pw.println(prefix + "No configured app linkages."); 16197 pw.println(); 16198 } 16199 } 16200 } 16201 } 16202 } 16203 16204 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 16205 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 16206 if (packageName == null && permissionNames == null) { 16207 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 16208 if (iperm == 0) { 16209 if (dumpState.onTitlePrinted()) 16210 pw.println(); 16211 pw.println("AppOp Permissions:"); 16212 } 16213 pw.print(" AppOp Permission "); 16214 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 16215 pw.println(":"); 16216 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 16217 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 16218 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 16219 } 16220 } 16221 } 16222 } 16223 16224 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 16225 boolean printedSomething = false; 16226 for (PackageParser.Provider p : mProviders.mProviders.values()) { 16227 if (packageName != null && !packageName.equals(p.info.packageName)) { 16228 continue; 16229 } 16230 if (!printedSomething) { 16231 if (dumpState.onTitlePrinted()) 16232 pw.println(); 16233 pw.println("Registered ContentProviders:"); 16234 printedSomething = true; 16235 } 16236 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 16237 pw.print(" "); pw.println(p.toString()); 16238 } 16239 printedSomething = false; 16240 for (Map.Entry<String, PackageParser.Provider> entry : 16241 mProvidersByAuthority.entrySet()) { 16242 PackageParser.Provider p = entry.getValue(); 16243 if (packageName != null && !packageName.equals(p.info.packageName)) { 16244 continue; 16245 } 16246 if (!printedSomething) { 16247 if (dumpState.onTitlePrinted()) 16248 pw.println(); 16249 pw.println("ContentProvider Authorities:"); 16250 printedSomething = true; 16251 } 16252 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 16253 pw.print(" "); pw.println(p.toString()); 16254 if (p.info != null && p.info.applicationInfo != null) { 16255 final String appInfo = p.info.applicationInfo.toString(); 16256 pw.print(" applicationInfo="); pw.println(appInfo); 16257 } 16258 } 16259 } 16260 16261 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 16262 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 16263 } 16264 16265 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 16266 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 16267 } 16268 16269 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 16270 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 16271 } 16272 16273 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 16274 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 16275 } 16276 16277 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 16278 // XXX should handle packageName != null by dumping only install data that 16279 // the given package is involved with. 16280 if (dumpState.onTitlePrinted()) pw.println(); 16281 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 16282 } 16283 16284 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 16285 if (dumpState.onTitlePrinted()) pw.println(); 16286 mSettings.dumpReadMessagesLPr(pw, dumpState); 16287 16288 pw.println(); 16289 pw.println("Package warning messages:"); 16290 BufferedReader in = null; 16291 String line = null; 16292 try { 16293 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16294 while ((line = in.readLine()) != null) { 16295 if (line.contains("ignored: updated version")) continue; 16296 pw.println(line); 16297 } 16298 } catch (IOException ignored) { 16299 } finally { 16300 IoUtils.closeQuietly(in); 16301 } 16302 } 16303 16304 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 16305 BufferedReader in = null; 16306 String line = null; 16307 try { 16308 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16309 while ((line = in.readLine()) != null) { 16310 if (line.contains("ignored: updated version")) continue; 16311 pw.print("msg,"); 16312 pw.println(line); 16313 } 16314 } catch (IOException ignored) { 16315 } finally { 16316 IoUtils.closeQuietly(in); 16317 } 16318 } 16319 } 16320 } 16321 16322 private String dumpDomainString(String packageName) { 16323 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 16324 List<IntentFilter> filters = getAllIntentFilters(packageName); 16325 16326 ArraySet<String> result = new ArraySet<>(); 16327 if (iviList.size() > 0) { 16328 for (IntentFilterVerificationInfo ivi : iviList) { 16329 for (String host : ivi.getDomains()) { 16330 result.add(host); 16331 } 16332 } 16333 } 16334 if (filters != null && filters.size() > 0) { 16335 for (IntentFilter filter : filters) { 16336 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 16337 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 16338 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 16339 result.addAll(filter.getHostsList()); 16340 } 16341 } 16342 } 16343 16344 StringBuilder sb = new StringBuilder(result.size() * 16); 16345 for (String domain : result) { 16346 if (sb.length() > 0) sb.append(" "); 16347 sb.append(domain); 16348 } 16349 return sb.toString(); 16350 } 16351 16352 // ------- apps on sdcard specific code ------- 16353 static final boolean DEBUG_SD_INSTALL = false; 16354 16355 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 16356 16357 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 16358 16359 private boolean mMediaMounted = false; 16360 16361 static String getEncryptKey() { 16362 try { 16363 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 16364 SD_ENCRYPTION_KEYSTORE_NAME); 16365 if (sdEncKey == null) { 16366 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 16367 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 16368 if (sdEncKey == null) { 16369 Slog.e(TAG, "Failed to create encryption keys"); 16370 return null; 16371 } 16372 } 16373 return sdEncKey; 16374 } catch (NoSuchAlgorithmException nsae) { 16375 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 16376 return null; 16377 } catch (IOException ioe) { 16378 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 16379 return null; 16380 } 16381 } 16382 16383 /* 16384 * Update media status on PackageManager. 16385 */ 16386 @Override 16387 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 16388 int callingUid = Binder.getCallingUid(); 16389 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 16390 throw new SecurityException("Media status can only be updated by the system"); 16391 } 16392 // reader; this apparently protects mMediaMounted, but should probably 16393 // be a different lock in that case. 16394 synchronized (mPackages) { 16395 Log.i(TAG, "Updating external media status from " 16396 + (mMediaMounted ? "mounted" : "unmounted") + " to " 16397 + (mediaStatus ? "mounted" : "unmounted")); 16398 if (DEBUG_SD_INSTALL) 16399 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 16400 + ", mMediaMounted=" + mMediaMounted); 16401 if (mediaStatus == mMediaMounted) { 16402 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 16403 : 0, -1); 16404 mHandler.sendMessage(msg); 16405 return; 16406 } 16407 mMediaMounted = mediaStatus; 16408 } 16409 // Queue up an async operation since the package installation may take a 16410 // little while. 16411 mHandler.post(new Runnable() { 16412 public void run() { 16413 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 16414 } 16415 }); 16416 } 16417 16418 /** 16419 * Called by MountService when the initial ASECs to scan are available. 16420 * Should block until all the ASEC containers are finished being scanned. 16421 */ 16422 public void scanAvailableAsecs() { 16423 updateExternalMediaStatusInner(true, false, false); 16424 } 16425 16426 /* 16427 * Collect information of applications on external media, map them against 16428 * existing containers and update information based on current mount status. 16429 * Please note that we always have to report status if reportStatus has been 16430 * set to true especially when unloading packages. 16431 */ 16432 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 16433 boolean externalStorage) { 16434 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 16435 int[] uidArr = EmptyArray.INT; 16436 16437 final String[] list = PackageHelper.getSecureContainerList(); 16438 if (ArrayUtils.isEmpty(list)) { 16439 Log.i(TAG, "No secure containers found"); 16440 } else { 16441 // Process list of secure containers and categorize them 16442 // as active or stale based on their package internal state. 16443 16444 // reader 16445 synchronized (mPackages) { 16446 for (String cid : list) { 16447 // Leave stages untouched for now; installer service owns them 16448 if (PackageInstallerService.isStageName(cid)) continue; 16449 16450 if (DEBUG_SD_INSTALL) 16451 Log.i(TAG, "Processing container " + cid); 16452 String pkgName = getAsecPackageName(cid); 16453 if (pkgName == null) { 16454 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 16455 continue; 16456 } 16457 if (DEBUG_SD_INSTALL) 16458 Log.i(TAG, "Looking for pkg : " + pkgName); 16459 16460 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16461 if (ps == null) { 16462 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 16463 continue; 16464 } 16465 16466 /* 16467 * Skip packages that are not external if we're unmounting 16468 * external storage. 16469 */ 16470 if (externalStorage && !isMounted && !isExternal(ps)) { 16471 continue; 16472 } 16473 16474 final AsecInstallArgs args = new AsecInstallArgs(cid, 16475 getAppDexInstructionSets(ps), ps.isForwardLocked()); 16476 // The package status is changed only if the code path 16477 // matches between settings and the container id. 16478 if (ps.codePathString != null 16479 && ps.codePathString.startsWith(args.getCodePath())) { 16480 if (DEBUG_SD_INSTALL) { 16481 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 16482 + " at code path: " + ps.codePathString); 16483 } 16484 16485 // We do have a valid package installed on sdcard 16486 processCids.put(args, ps.codePathString); 16487 final int uid = ps.appId; 16488 if (uid != -1) { 16489 uidArr = ArrayUtils.appendInt(uidArr, uid); 16490 } 16491 } else { 16492 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 16493 + ps.codePathString); 16494 } 16495 } 16496 } 16497 16498 Arrays.sort(uidArr); 16499 } 16500 16501 // Process packages with valid entries. 16502 if (isMounted) { 16503 if (DEBUG_SD_INSTALL) 16504 Log.i(TAG, "Loading packages"); 16505 loadMediaPackages(processCids, uidArr, externalStorage); 16506 startCleaningPackages(); 16507 mInstallerService.onSecureContainersAvailable(); 16508 } else { 16509 if (DEBUG_SD_INSTALL) 16510 Log.i(TAG, "Unloading packages"); 16511 unloadMediaPackages(processCids, uidArr, reportStatus); 16512 } 16513 } 16514 16515 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16516 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 16517 final int size = infos.size(); 16518 final String[] packageNames = new String[size]; 16519 final int[] packageUids = new int[size]; 16520 for (int i = 0; i < size; i++) { 16521 final ApplicationInfo info = infos.get(i); 16522 packageNames[i] = info.packageName; 16523 packageUids[i] = info.uid; 16524 } 16525 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 16526 finishedReceiver); 16527 } 16528 16529 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16530 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16531 sendResourcesChangedBroadcast(mediaStatus, replacing, 16532 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 16533 } 16534 16535 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16536 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16537 int size = pkgList.length; 16538 if (size > 0) { 16539 // Send broadcasts here 16540 Bundle extras = new Bundle(); 16541 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 16542 if (uidArr != null) { 16543 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 16544 } 16545 if (replacing) { 16546 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 16547 } 16548 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 16549 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 16550 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 16551 } 16552 } 16553 16554 /* 16555 * Look at potentially valid container ids from processCids If package 16556 * information doesn't match the one on record or package scanning fails, 16557 * the cid is added to list of removeCids. We currently don't delete stale 16558 * containers. 16559 */ 16560 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 16561 boolean externalStorage) { 16562 ArrayList<String> pkgList = new ArrayList<String>(); 16563 Set<AsecInstallArgs> keys = processCids.keySet(); 16564 16565 for (AsecInstallArgs args : keys) { 16566 String codePath = processCids.get(args); 16567 if (DEBUG_SD_INSTALL) 16568 Log.i(TAG, "Loading container : " + args.cid); 16569 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16570 try { 16571 // Make sure there are no container errors first. 16572 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 16573 Slog.e(TAG, "Failed to mount cid : " + args.cid 16574 + " when installing from sdcard"); 16575 continue; 16576 } 16577 // Check code path here. 16578 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 16579 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 16580 + " does not match one in settings " + codePath); 16581 continue; 16582 } 16583 // Parse package 16584 int parseFlags = mDefParseFlags; 16585 if (args.isExternalAsec()) { 16586 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 16587 } 16588 if (args.isFwdLocked()) { 16589 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 16590 } 16591 16592 synchronized (mInstallLock) { 16593 PackageParser.Package pkg = null; 16594 try { 16595 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 16596 } catch (PackageManagerException e) { 16597 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 16598 } 16599 // Scan the package 16600 if (pkg != null) { 16601 /* 16602 * TODO why is the lock being held? doPostInstall is 16603 * called in other places without the lock. This needs 16604 * to be straightened out. 16605 */ 16606 // writer 16607 synchronized (mPackages) { 16608 retCode = PackageManager.INSTALL_SUCCEEDED; 16609 pkgList.add(pkg.packageName); 16610 // Post process args 16611 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 16612 pkg.applicationInfo.uid); 16613 } 16614 } else { 16615 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 16616 } 16617 } 16618 16619 } finally { 16620 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 16621 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 16622 } 16623 } 16624 } 16625 // writer 16626 synchronized (mPackages) { 16627 // If the platform SDK has changed since the last time we booted, 16628 // we need to re-grant app permission to catch any new ones that 16629 // appear. This is really a hack, and means that apps can in some 16630 // cases get permissions that the user didn't initially explicitly 16631 // allow... it would be nice to have some better way to handle 16632 // this situation. 16633 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 16634 : mSettings.getInternalVersion(); 16635 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 16636 : StorageManager.UUID_PRIVATE_INTERNAL; 16637 16638 int updateFlags = UPDATE_PERMISSIONS_ALL; 16639 if (ver.sdkVersion != mSdkVersion) { 16640 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16641 + mSdkVersion + "; regranting permissions for external"); 16642 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16643 } 16644 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16645 16646 // Yay, everything is now upgraded 16647 ver.forceCurrent(); 16648 16649 // can downgrade to reader 16650 // Persist settings 16651 mSettings.writeLPr(); 16652 } 16653 // Send a broadcast to let everyone know we are done processing 16654 if (pkgList.size() > 0) { 16655 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 16656 } 16657 } 16658 16659 /* 16660 * Utility method to unload a list of specified containers 16661 */ 16662 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 16663 // Just unmount all valid containers. 16664 for (AsecInstallArgs arg : cidArgs) { 16665 synchronized (mInstallLock) { 16666 arg.doPostDeleteLI(false); 16667 } 16668 } 16669 } 16670 16671 /* 16672 * Unload packages mounted on external media. This involves deleting package 16673 * data from internal structures, sending broadcasts about diabled packages, 16674 * gc'ing to free up references, unmounting all secure containers 16675 * corresponding to packages on external media, and posting a 16676 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 16677 * that we always have to post this message if status has been requested no 16678 * matter what. 16679 */ 16680 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 16681 final boolean reportStatus) { 16682 if (DEBUG_SD_INSTALL) 16683 Log.i(TAG, "unloading media packages"); 16684 ArrayList<String> pkgList = new ArrayList<String>(); 16685 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 16686 final Set<AsecInstallArgs> keys = processCids.keySet(); 16687 for (AsecInstallArgs args : keys) { 16688 String pkgName = args.getPackageName(); 16689 if (DEBUG_SD_INSTALL) 16690 Log.i(TAG, "Trying to unload pkg : " + pkgName); 16691 // Delete package internally 16692 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16693 synchronized (mInstallLock) { 16694 boolean res = deletePackageLI(pkgName, null, false, null, null, 16695 PackageManager.DELETE_KEEP_DATA, outInfo, false); 16696 if (res) { 16697 pkgList.add(pkgName); 16698 } else { 16699 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 16700 failedList.add(args); 16701 } 16702 } 16703 } 16704 16705 // reader 16706 synchronized (mPackages) { 16707 // We didn't update the settings after removing each package; 16708 // write them now for all packages. 16709 mSettings.writeLPr(); 16710 } 16711 16712 // We have to absolutely send UPDATED_MEDIA_STATUS only 16713 // after confirming that all the receivers processed the ordered 16714 // broadcast when packages get disabled, force a gc to clean things up. 16715 // and unload all the containers. 16716 if (pkgList.size() > 0) { 16717 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 16718 new IIntentReceiver.Stub() { 16719 public void performReceive(Intent intent, int resultCode, String data, 16720 Bundle extras, boolean ordered, boolean sticky, 16721 int sendingUser) throws RemoteException { 16722 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16723 reportStatus ? 1 : 0, 1, keys); 16724 mHandler.sendMessage(msg); 16725 } 16726 }); 16727 } else { 16728 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16729 keys); 16730 mHandler.sendMessage(msg); 16731 } 16732 } 16733 16734 private void loadPrivatePackages(final VolumeInfo vol) { 16735 mHandler.post(new Runnable() { 16736 @Override 16737 public void run() { 16738 loadPrivatePackagesInner(vol); 16739 } 16740 }); 16741 } 16742 16743 private void loadPrivatePackagesInner(VolumeInfo vol) { 16744 final String volumeUuid = vol.fsUuid; 16745 if (TextUtils.isEmpty(volumeUuid)) { 16746 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 16747 return; 16748 } 16749 16750 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16751 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16752 16753 final VersionInfo ver; 16754 final List<PackageSetting> packages; 16755 synchronized (mPackages) { 16756 ver = mSettings.findOrCreateVersion(volumeUuid); 16757 packages = mSettings.getVolumePackagesLPr(volumeUuid); 16758 } 16759 16760 // TODO: introduce a new concept similar to "frozen" to prevent these 16761 // apps from being launched until after data has been fully reconciled 16762 for (PackageSetting ps : packages) { 16763 synchronized (mInstallLock) { 16764 final PackageParser.Package pkg; 16765 try { 16766 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16767 loaded.add(pkg.applicationInfo); 16768 16769 } catch (PackageManagerException e) { 16770 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16771 } 16772 16773 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16774 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16775 } 16776 } 16777 } 16778 16779 // Reconcile app data for all started/unlocked users 16780 final UserManager um = mContext.getSystemService(UserManager.class); 16781 for (UserInfo user : um.getUsers()) { 16782 if (um.isUserUnlocked(user.id)) { 16783 reconcileAppsData(volumeUuid, user.id, 16784 Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE); 16785 } else if (um.isUserRunning(user.id)) { 16786 reconcileAppsData(volumeUuid, user.id, Installer.FLAG_DE_STORAGE); 16787 } else { 16788 continue; 16789 } 16790 } 16791 16792 synchronized (mPackages) { 16793 int updateFlags = UPDATE_PERMISSIONS_ALL; 16794 if (ver.sdkVersion != mSdkVersion) { 16795 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16796 + mSdkVersion + "; regranting permissions for " + volumeUuid); 16797 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16798 } 16799 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16800 16801 // Yay, everything is now upgraded 16802 ver.forceCurrent(); 16803 16804 mSettings.writeLPr(); 16805 } 16806 16807 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16808 sendResourcesChangedBroadcast(true, false, loaded, null); 16809 } 16810 16811 private void unloadPrivatePackages(final VolumeInfo vol) { 16812 mHandler.post(new Runnable() { 16813 @Override 16814 public void run() { 16815 unloadPrivatePackagesInner(vol); 16816 } 16817 }); 16818 } 16819 16820 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16821 final String volumeUuid = vol.fsUuid; 16822 if (TextUtils.isEmpty(volumeUuid)) { 16823 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 16824 return; 16825 } 16826 16827 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16828 synchronized (mInstallLock) { 16829 synchronized (mPackages) { 16830 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 16831 for (PackageSetting ps : packages) { 16832 if (ps.pkg == null) continue; 16833 16834 final ApplicationInfo info = ps.pkg.applicationInfo; 16835 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16836 if (deletePackageLI(ps.name, null, false, null, null, 16837 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16838 unloaded.add(info); 16839 } else { 16840 Slog.w(TAG, "Failed to unload " + ps.codePath); 16841 } 16842 } 16843 16844 mSettings.writeLPr(); 16845 } 16846 } 16847 16848 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16849 sendResourcesChangedBroadcast(false, false, unloaded, null); 16850 } 16851 16852 /** 16853 * Examine all users present on given mounted volume, and destroy data 16854 * belonging to users that are no longer valid, or whose user ID has been 16855 * recycled. 16856 */ 16857 private void reconcileUsers(String volumeUuid) { 16858 final File[] files = FileUtils 16859 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16860 for (File file : files) { 16861 if (!file.isDirectory()) continue; 16862 16863 final int userId; 16864 final UserInfo info; 16865 try { 16866 userId = Integer.parseInt(file.getName()); 16867 info = sUserManager.getUserInfo(userId); 16868 } catch (NumberFormatException e) { 16869 Slog.w(TAG, "Invalid user directory " + file); 16870 continue; 16871 } 16872 16873 boolean destroyUser = false; 16874 if (info == null) { 16875 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16876 + " because no matching user was found"); 16877 destroyUser = true; 16878 } else { 16879 try { 16880 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16881 } catch (IOException e) { 16882 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16883 + " because we failed to enforce serial number: " + e); 16884 destroyUser = true; 16885 } 16886 } 16887 16888 if (destroyUser) { 16889 synchronized (mInstallLock) { 16890 try { 16891 mInstaller.removeUserDataDirs(volumeUuid, userId); 16892 } catch (InstallerException e) { 16893 Slog.w(TAG, "Failed to clean up user dirs", e); 16894 } 16895 } 16896 } 16897 } 16898 16899 final StorageManager sm = mContext.getSystemService(StorageManager.class); 16900 final UserManager um = mContext.getSystemService(UserManager.class); 16901 for (UserInfo user : um.getUsers()) { 16902 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16903 if (userDir.exists()) continue; 16904 16905 try { 16906 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral()); 16907 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16908 } catch (IOException e) { 16909 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16910 } 16911 } 16912 } 16913 16914 private void assertPackageKnown(String volumeUuid, String packageName) 16915 throws PackageManagerException { 16916 synchronized (mPackages) { 16917 final PackageSetting ps = mSettings.mPackages.get(packageName); 16918 if (ps == null) { 16919 throw new PackageManagerException("Package " + packageName + " is unknown"); 16920 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16921 throw new PackageManagerException( 16922 "Package " + packageName + " found on unknown volume " + volumeUuid 16923 + "; expected volume " + ps.volumeUuid); 16924 } 16925 } 16926 } 16927 16928 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 16929 throws PackageManagerException { 16930 synchronized (mPackages) { 16931 final PackageSetting ps = mSettings.mPackages.get(packageName); 16932 if (ps == null) { 16933 throw new PackageManagerException("Package " + packageName + " is unknown"); 16934 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16935 throw new PackageManagerException( 16936 "Package " + packageName + " found on unknown volume " + volumeUuid 16937 + "; expected volume " + ps.volumeUuid); 16938 } else if (!ps.getInstalled(userId)) { 16939 throw new PackageManagerException( 16940 "Package " + packageName + " not installed for user " + userId); 16941 } 16942 } 16943 } 16944 16945 /** 16946 * Examine all apps present on given mounted volume, and destroy apps that 16947 * aren't expected, either due to uninstallation or reinstallation on 16948 * another volume. 16949 */ 16950 private void reconcileApps(String volumeUuid) { 16951 final File[] files = FileUtils 16952 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16953 for (File file : files) { 16954 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16955 && !PackageInstallerService.isStageName(file.getName()); 16956 if (!isPackage) { 16957 // Ignore entries which are not packages 16958 continue; 16959 } 16960 16961 try { 16962 final PackageLite pkg = PackageParser.parsePackageLite(file, 16963 PackageParser.PARSE_MUST_BE_APK); 16964 assertPackageKnown(volumeUuid, pkg.packageName); 16965 16966 } catch (PackageParserException | PackageManagerException e) { 16967 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16968 synchronized (mInstallLock) { 16969 removeCodePathLI(file); 16970 } 16971 } 16972 } 16973 } 16974 16975 /** 16976 * Reconcile all app data for the given user. 16977 * <p> 16978 * Verifies that directories exist and that ownership and labeling is 16979 * correct for all installed apps on all mounted volumes. 16980 */ 16981 void reconcileAppsData(int userId, @StorageFlags int flags) { 16982 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16983 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16984 final String volumeUuid = vol.getFsUuid(); 16985 reconcileAppsData(volumeUuid, userId, flags); 16986 } 16987 } 16988 16989 /** 16990 * Reconcile all app data on given mounted volume. 16991 * <p> 16992 * Destroys app data that isn't expected, either due to uninstallation or 16993 * reinstallation on another volume. 16994 * <p> 16995 * Verifies that directories exist and that ownership and labeling is 16996 * correct for all installed apps. 16997 */ 16998 private void reconcileAppsData(String volumeUuid, int userId, @StorageFlags int flags) { 16999 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 17000 + Integer.toHexString(flags)); 17001 17002 final File ceDir = Environment.getDataUserCredentialEncryptedDirectory(volumeUuid, userId); 17003 final File deDir = Environment.getDataUserDeviceEncryptedDirectory(volumeUuid, userId); 17004 17005 boolean restoreconNeeded = false; 17006 17007 // First look for stale data that doesn't belong, and check if things 17008 // have changed since we did our last restorecon 17009 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 17010 if (!isUserKeyUnlocked(userId)) { 17011 throw new RuntimeException( 17012 "Yikes, someone asked us to reconcile CE storage while " + userId 17013 + " was still locked; this would have caused massive data loss!"); 17014 } 17015 17016 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 17017 17018 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 17019 for (File file : files) { 17020 final String packageName = file.getName(); 17021 try { 17022 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 17023 } catch (PackageManagerException e) { 17024 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17025 synchronized (mInstallLock) { 17026 destroyAppDataLI(volumeUuid, packageName, userId, 17027 Installer.FLAG_CE_STORAGE); 17028 } 17029 } 17030 } 17031 } 17032 if ((flags & Installer.FLAG_DE_STORAGE) != 0) { 17033 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 17034 17035 final File[] files = FileUtils.listFilesOrEmpty(deDir); 17036 for (File file : files) { 17037 final String packageName = file.getName(); 17038 try { 17039 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 17040 } catch (PackageManagerException e) { 17041 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17042 synchronized (mInstallLock) { 17043 destroyAppDataLI(volumeUuid, packageName, userId, 17044 Installer.FLAG_DE_STORAGE); 17045 } 17046 } 17047 } 17048 } 17049 17050 // Ensure that data directories are ready to roll for all packages 17051 // installed for this volume and user 17052 final List<PackageSetting> packages; 17053 synchronized (mPackages) { 17054 packages = mSettings.getVolumePackagesLPr(volumeUuid); 17055 } 17056 int preparedCount = 0; 17057 for (PackageSetting ps : packages) { 17058 final String packageName = ps.name; 17059 if (ps.pkg == null) { 17060 Slog.w(TAG, "Odd, missing scanned package " + packageName); 17061 // TODO: might be due to legacy ASEC apps; we should circle back 17062 // and reconcile again once they're scanned 17063 continue; 17064 } 17065 17066 if (ps.getInstalled(userId)) { 17067 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 17068 preparedCount++; 17069 } 17070 } 17071 17072 if (restoreconNeeded) { 17073 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 17074 SELinuxMMAC.setRestoreconDone(ceDir); 17075 } 17076 if ((flags & Installer.FLAG_DE_STORAGE) != 0) { 17077 SELinuxMMAC.setRestoreconDone(deDir); 17078 } 17079 } 17080 17081 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 17082 + " packages; restoreconNeeded was " + restoreconNeeded); 17083 } 17084 17085 /** 17086 * Prepare app data for the given app just after it was installed or 17087 * upgraded. This method carefully only touches users that it's installed 17088 * for, and it forces a restorecon to handle any seinfo changes. 17089 * <p> 17090 * Verifies that directories exist and that ownership and labeling is 17091 * correct for all installed apps. If there is an ownership mismatch, it 17092 * will try recovering system apps by wiping data; third-party app data is 17093 * left intact. 17094 */ 17095 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 17096 final PackageSetting ps; 17097 synchronized (mPackages) { 17098 ps = mSettings.mPackages.get(pkg.packageName); 17099 } 17100 17101 final UserManager um = mContext.getSystemService(UserManager.class); 17102 for (UserInfo user : um.getUsers()) { 17103 final int flags; 17104 if (um.isUserUnlocked(user.id)) { 17105 flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE; 17106 } else if (um.isUserRunning(user.id)) { 17107 flags = Installer.FLAG_DE_STORAGE; 17108 } else { 17109 continue; 17110 } 17111 17112 if (ps.getInstalled(user.id)) { 17113 // Whenever an app changes, force a restorecon of its data 17114 // TODO: when user data is locked, mark that we're still dirty 17115 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 17116 } 17117 } 17118 } 17119 17120 /** 17121 * Prepare app data for the given app. 17122 * <p> 17123 * Verifies that directories exist and that ownership and labeling is 17124 * correct for all installed apps. If there is an ownership mismatch, this 17125 * will try recovering system apps by wiping data; third-party app data is 17126 * left intact. 17127 */ 17128 private void prepareAppData(String volumeUuid, int userId, @StorageFlags int flags, 17129 PackageParser.Package pkg, boolean restoreconNeeded) { 17130 if (DEBUG_APP_DATA) { 17131 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 17132 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 17133 } 17134 17135 final String packageName = pkg.packageName; 17136 final ApplicationInfo app = pkg.applicationInfo; 17137 final int appId = UserHandle.getAppId(app.uid); 17138 17139 Preconditions.checkNotNull(app.seinfo); 17140 17141 synchronized (mInstallLock) { 17142 try { 17143 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17144 appId, app.seinfo, app.targetSdkVersion); 17145 } catch (InstallerException e) { 17146 if (app.isSystemApp()) { 17147 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 17148 + ", but trying to recover: " + e); 17149 destroyAppDataLI(volumeUuid, packageName, userId, flags); 17150 try { 17151 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17152 appId, app.seinfo, app.targetSdkVersion); 17153 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 17154 } catch (InstallerException e2) { 17155 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 17156 } 17157 } else { 17158 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 17159 } 17160 } 17161 17162 if (restoreconNeeded) { 17163 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 17164 } 17165 17166 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 17167 // Create a native library symlink only if we have native libraries 17168 // and if the native libraries are 32 bit libraries. We do not provide 17169 // this symlink for 64 bit libraries. 17170 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 17171 final String nativeLibPath = app.nativeLibraryDir; 17172 try { 17173 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 17174 nativeLibPath, userId); 17175 } catch (InstallerException e) { 17176 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 17177 } 17178 } 17179 } 17180 } 17181 } 17182 17183 private void unfreezePackage(String packageName) { 17184 synchronized (mPackages) { 17185 final PackageSetting ps = mSettings.mPackages.get(packageName); 17186 if (ps != null) { 17187 ps.frozen = false; 17188 } 17189 } 17190 } 17191 17192 @Override 17193 public int movePackage(final String packageName, final String volumeUuid) { 17194 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17195 17196 final int moveId = mNextMoveId.getAndIncrement(); 17197 mHandler.post(new Runnable() { 17198 @Override 17199 public void run() { 17200 try { 17201 movePackageInternal(packageName, volumeUuid, moveId); 17202 } catch (PackageManagerException e) { 17203 Slog.w(TAG, "Failed to move " + packageName, e); 17204 mMoveCallbacks.notifyStatusChanged(moveId, 17205 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17206 } 17207 } 17208 }); 17209 return moveId; 17210 } 17211 17212 private void movePackageInternal(final String packageName, final String volumeUuid, 17213 final int moveId) throws PackageManagerException { 17214 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 17215 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17216 final PackageManager pm = mContext.getPackageManager(); 17217 17218 final boolean currentAsec; 17219 final String currentVolumeUuid; 17220 final File codeFile; 17221 final String installerPackageName; 17222 final String packageAbiOverride; 17223 final int appId; 17224 final String seinfo; 17225 final String label; 17226 final int targetSdkVersion; 17227 17228 // reader 17229 synchronized (mPackages) { 17230 final PackageParser.Package pkg = mPackages.get(packageName); 17231 final PackageSetting ps = mSettings.mPackages.get(packageName); 17232 if (pkg == null || ps == null) { 17233 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 17234 } 17235 17236 if (pkg.applicationInfo.isSystemApp()) { 17237 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 17238 "Cannot move system application"); 17239 } 17240 17241 if (pkg.applicationInfo.isExternalAsec()) { 17242 currentAsec = true; 17243 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 17244 } else if (pkg.applicationInfo.isForwardLocked()) { 17245 currentAsec = true; 17246 currentVolumeUuid = "forward_locked"; 17247 } else { 17248 currentAsec = false; 17249 currentVolumeUuid = ps.volumeUuid; 17250 17251 final File probe = new File(pkg.codePath); 17252 final File probeOat = new File(probe, "oat"); 17253 if (!probe.isDirectory() || !probeOat.isDirectory()) { 17254 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17255 "Move only supported for modern cluster style installs"); 17256 } 17257 } 17258 17259 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 17260 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17261 "Package already moved to " + volumeUuid); 17262 } 17263 17264 if (ps.frozen) { 17265 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 17266 "Failed to move already frozen package"); 17267 } 17268 ps.frozen = true; 17269 17270 codeFile = new File(pkg.codePath); 17271 installerPackageName = ps.installerPackageName; 17272 packageAbiOverride = ps.cpuAbiOverrideString; 17273 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 17274 seinfo = pkg.applicationInfo.seinfo; 17275 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 17276 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 17277 } 17278 17279 // Now that we're guarded by frozen state, kill app during move 17280 final long token = Binder.clearCallingIdentity(); 17281 try { 17282 killApplication(packageName, appId, "move pkg"); 17283 } finally { 17284 Binder.restoreCallingIdentity(token); 17285 } 17286 17287 final Bundle extras = new Bundle(); 17288 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 17289 extras.putString(Intent.EXTRA_TITLE, label); 17290 mMoveCallbacks.notifyCreated(moveId, extras); 17291 17292 int installFlags; 17293 final boolean moveCompleteApp; 17294 final File measurePath; 17295 17296 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 17297 installFlags = INSTALL_INTERNAL; 17298 moveCompleteApp = !currentAsec; 17299 measurePath = Environment.getDataAppDirectory(volumeUuid); 17300 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 17301 installFlags = INSTALL_EXTERNAL; 17302 moveCompleteApp = false; 17303 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 17304 } else { 17305 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 17306 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 17307 || !volume.isMountedWritable()) { 17308 unfreezePackage(packageName); 17309 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17310 "Move location not mounted private volume"); 17311 } 17312 17313 Preconditions.checkState(!currentAsec); 17314 17315 installFlags = INSTALL_INTERNAL; 17316 moveCompleteApp = true; 17317 measurePath = Environment.getDataAppDirectory(volumeUuid); 17318 } 17319 17320 final PackageStats stats = new PackageStats(null, -1); 17321 synchronized (mInstaller) { 17322 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 17323 unfreezePackage(packageName); 17324 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17325 "Failed to measure package size"); 17326 } 17327 } 17328 17329 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 17330 + stats.dataSize); 17331 17332 final long startFreeBytes = measurePath.getFreeSpace(); 17333 final long sizeBytes; 17334 if (moveCompleteApp) { 17335 sizeBytes = stats.codeSize + stats.dataSize; 17336 } else { 17337 sizeBytes = stats.codeSize; 17338 } 17339 17340 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 17341 unfreezePackage(packageName); 17342 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17343 "Not enough free space to move"); 17344 } 17345 17346 mMoveCallbacks.notifyStatusChanged(moveId, 10); 17347 17348 final CountDownLatch installedLatch = new CountDownLatch(1); 17349 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 17350 @Override 17351 public void onUserActionRequired(Intent intent) throws RemoteException { 17352 throw new IllegalStateException(); 17353 } 17354 17355 @Override 17356 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 17357 Bundle extras) throws RemoteException { 17358 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 17359 + PackageManager.installStatusToString(returnCode, msg)); 17360 17361 installedLatch.countDown(); 17362 17363 // Regardless of success or failure of the move operation, 17364 // always unfreeze the package 17365 unfreezePackage(packageName); 17366 17367 final int status = PackageManager.installStatusToPublicStatus(returnCode); 17368 switch (status) { 17369 case PackageInstaller.STATUS_SUCCESS: 17370 mMoveCallbacks.notifyStatusChanged(moveId, 17371 PackageManager.MOVE_SUCCEEDED); 17372 break; 17373 case PackageInstaller.STATUS_FAILURE_STORAGE: 17374 mMoveCallbacks.notifyStatusChanged(moveId, 17375 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 17376 break; 17377 default: 17378 mMoveCallbacks.notifyStatusChanged(moveId, 17379 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17380 break; 17381 } 17382 } 17383 }; 17384 17385 final MoveInfo move; 17386 if (moveCompleteApp) { 17387 // Kick off a thread to report progress estimates 17388 new Thread() { 17389 @Override 17390 public void run() { 17391 while (true) { 17392 try { 17393 if (installedLatch.await(1, TimeUnit.SECONDS)) { 17394 break; 17395 } 17396 } catch (InterruptedException ignored) { 17397 } 17398 17399 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 17400 final int progress = 10 + (int) MathUtils.constrain( 17401 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 17402 mMoveCallbacks.notifyStatusChanged(moveId, progress); 17403 } 17404 } 17405 }.start(); 17406 17407 final String dataAppName = codeFile.getName(); 17408 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 17409 dataAppName, appId, seinfo, targetSdkVersion); 17410 } else { 17411 move = null; 17412 } 17413 17414 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 17415 17416 final Message msg = mHandler.obtainMessage(INIT_COPY); 17417 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 17418 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 17419 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 17420 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 17421 msg.obj = params; 17422 17423 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 17424 System.identityHashCode(msg.obj)); 17425 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 17426 System.identityHashCode(msg.obj)); 17427 17428 mHandler.sendMessage(msg); 17429 } 17430 17431 @Override 17432 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 17433 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17434 17435 final int realMoveId = mNextMoveId.getAndIncrement(); 17436 final Bundle extras = new Bundle(); 17437 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 17438 mMoveCallbacks.notifyCreated(realMoveId, extras); 17439 17440 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 17441 @Override 17442 public void onCreated(int moveId, Bundle extras) { 17443 // Ignored 17444 } 17445 17446 @Override 17447 public void onStatusChanged(int moveId, int status, long estMillis) { 17448 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 17449 } 17450 }; 17451 17452 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17453 storage.setPrimaryStorageUuid(volumeUuid, callback); 17454 return realMoveId; 17455 } 17456 17457 @Override 17458 public int getMoveStatus(int moveId) { 17459 mContext.enforceCallingOrSelfPermission( 17460 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17461 return mMoveCallbacks.mLastStatus.get(moveId); 17462 } 17463 17464 @Override 17465 public void registerMoveCallback(IPackageMoveObserver callback) { 17466 mContext.enforceCallingOrSelfPermission( 17467 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17468 mMoveCallbacks.register(callback); 17469 } 17470 17471 @Override 17472 public void unregisterMoveCallback(IPackageMoveObserver callback) { 17473 mContext.enforceCallingOrSelfPermission( 17474 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17475 mMoveCallbacks.unregister(callback); 17476 } 17477 17478 @Override 17479 public boolean setInstallLocation(int loc) { 17480 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 17481 null); 17482 if (getInstallLocation() == loc) { 17483 return true; 17484 } 17485 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 17486 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 17487 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 17488 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 17489 return true; 17490 } 17491 return false; 17492 } 17493 17494 @Override 17495 public int getInstallLocation() { 17496 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 17497 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 17498 PackageHelper.APP_INSTALL_AUTO); 17499 } 17500 17501 /** Called by UserManagerService */ 17502 void cleanUpUser(UserManagerService userManager, int userHandle) { 17503 synchronized (mPackages) { 17504 mDirtyUsers.remove(userHandle); 17505 mUserNeedsBadging.delete(userHandle); 17506 mSettings.removeUserLPw(userHandle); 17507 mPendingBroadcasts.remove(userHandle); 17508 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 17509 } 17510 synchronized (mInstallLock) { 17511 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17512 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 17513 final String volumeUuid = vol.getFsUuid(); 17514 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 17515 try { 17516 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 17517 } catch (InstallerException e) { 17518 Slog.w(TAG, "Failed to remove user data", e); 17519 } 17520 } 17521 synchronized (mPackages) { 17522 removeUnusedPackagesLILPw(userManager, userHandle); 17523 } 17524 } 17525 } 17526 17527 /** 17528 * We're removing userHandle and would like to remove any downloaded packages 17529 * that are no longer in use by any other user. 17530 * @param userHandle the user being removed 17531 */ 17532 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 17533 final boolean DEBUG_CLEAN_APKS = false; 17534 int [] users = userManager.getUserIds(); 17535 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 17536 while (psit.hasNext()) { 17537 PackageSetting ps = psit.next(); 17538 if (ps.pkg == null) { 17539 continue; 17540 } 17541 final String packageName = ps.pkg.packageName; 17542 // Skip over if system app 17543 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 17544 continue; 17545 } 17546 if (DEBUG_CLEAN_APKS) { 17547 Slog.i(TAG, "Checking package " + packageName); 17548 } 17549 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 17550 if (keep) { 17551 if (DEBUG_CLEAN_APKS) { 17552 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 17553 } 17554 } else { 17555 for (int i = 0; i < users.length; i++) { 17556 if (users[i] != userHandle && ps.getInstalled(users[i])) { 17557 keep = true; 17558 if (DEBUG_CLEAN_APKS) { 17559 Slog.i(TAG, " Keeping package " + packageName + " for user " 17560 + users[i]); 17561 } 17562 break; 17563 } 17564 } 17565 } 17566 if (!keep) { 17567 if (DEBUG_CLEAN_APKS) { 17568 Slog.i(TAG, " Removing package " + packageName); 17569 } 17570 mHandler.post(new Runnable() { 17571 public void run() { 17572 deletePackageX(packageName, userHandle, 0); 17573 } //end run 17574 }); 17575 } 17576 } 17577 } 17578 17579 /** Called by UserManagerService */ 17580 void createNewUser(int userHandle) { 17581 synchronized (mInstallLock) { 17582 try { 17583 mInstaller.createUserConfig(userHandle); 17584 } catch (InstallerException e) { 17585 Slog.w(TAG, "Failed to create user config", e); 17586 } 17587 mSettings.createNewUserLI(this, mInstaller, userHandle); 17588 } 17589 synchronized (mPackages) { 17590 applyFactoryDefaultBrowserLPw(userHandle); 17591 primeDomainVerificationsLPw(userHandle); 17592 } 17593 } 17594 17595 void newUserCreated(final int userHandle) { 17596 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 17597 // If permission review for legacy apps is required, we represent 17598 // dagerous permissions for such apps as always granted runtime 17599 // permissions to keep per user flag state whether review is needed. 17600 // Hence, if a new user is added we have to propagate dangerous 17601 // permission grants for these legacy apps. 17602 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 17603 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 17604 | UPDATE_PERMISSIONS_REPLACE_ALL); 17605 } 17606 } 17607 17608 @Override 17609 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 17610 mContext.enforceCallingOrSelfPermission( 17611 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 17612 "Only package verification agents can read the verifier device identity"); 17613 17614 synchronized (mPackages) { 17615 return mSettings.getVerifierDeviceIdentityLPw(); 17616 } 17617 } 17618 17619 @Override 17620 public void setPermissionEnforced(String permission, boolean enforced) { 17621 // TODO: Now that we no longer change GID for storage, this should to away. 17622 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 17623 "setPermissionEnforced"); 17624 if (READ_EXTERNAL_STORAGE.equals(permission)) { 17625 synchronized (mPackages) { 17626 if (mSettings.mReadExternalStorageEnforced == null 17627 || mSettings.mReadExternalStorageEnforced != enforced) { 17628 mSettings.mReadExternalStorageEnforced = enforced; 17629 mSettings.writeLPr(); 17630 } 17631 } 17632 // kill any non-foreground processes so we restart them and 17633 // grant/revoke the GID. 17634 final IActivityManager am = ActivityManagerNative.getDefault(); 17635 if (am != null) { 17636 final long token = Binder.clearCallingIdentity(); 17637 try { 17638 am.killProcessesBelowForeground("setPermissionEnforcement"); 17639 } catch (RemoteException e) { 17640 } finally { 17641 Binder.restoreCallingIdentity(token); 17642 } 17643 } 17644 } else { 17645 throw new IllegalArgumentException("No selective enforcement for " + permission); 17646 } 17647 } 17648 17649 @Override 17650 @Deprecated 17651 public boolean isPermissionEnforced(String permission) { 17652 return true; 17653 } 17654 17655 @Override 17656 public boolean isStorageLow() { 17657 final long token = Binder.clearCallingIdentity(); 17658 try { 17659 final DeviceStorageMonitorInternal 17660 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 17661 if (dsm != null) { 17662 return dsm.isMemoryLow(); 17663 } else { 17664 return false; 17665 } 17666 } finally { 17667 Binder.restoreCallingIdentity(token); 17668 } 17669 } 17670 17671 @Override 17672 public IPackageInstaller getPackageInstaller() { 17673 return mInstallerService; 17674 } 17675 17676 private boolean userNeedsBadging(int userId) { 17677 int index = mUserNeedsBadging.indexOfKey(userId); 17678 if (index < 0) { 17679 final UserInfo userInfo; 17680 final long token = Binder.clearCallingIdentity(); 17681 try { 17682 userInfo = sUserManager.getUserInfo(userId); 17683 } finally { 17684 Binder.restoreCallingIdentity(token); 17685 } 17686 final boolean b; 17687 if (userInfo != null && userInfo.isManagedProfile()) { 17688 b = true; 17689 } else { 17690 b = false; 17691 } 17692 mUserNeedsBadging.put(userId, b); 17693 return b; 17694 } 17695 return mUserNeedsBadging.valueAt(index); 17696 } 17697 17698 @Override 17699 public KeySet getKeySetByAlias(String packageName, String alias) { 17700 if (packageName == null || alias == null) { 17701 return null; 17702 } 17703 synchronized(mPackages) { 17704 final PackageParser.Package pkg = mPackages.get(packageName); 17705 if (pkg == null) { 17706 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17707 throw new IllegalArgumentException("Unknown package: " + packageName); 17708 } 17709 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17710 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 17711 } 17712 } 17713 17714 @Override 17715 public KeySet getSigningKeySet(String packageName) { 17716 if (packageName == null) { 17717 return null; 17718 } 17719 synchronized(mPackages) { 17720 final PackageParser.Package pkg = mPackages.get(packageName); 17721 if (pkg == null) { 17722 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17723 throw new IllegalArgumentException("Unknown package: " + packageName); 17724 } 17725 if (pkg.applicationInfo.uid != Binder.getCallingUid() 17726 && Process.SYSTEM_UID != Binder.getCallingUid()) { 17727 throw new SecurityException("May not access signing KeySet of other apps."); 17728 } 17729 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17730 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 17731 } 17732 } 17733 17734 @Override 17735 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 17736 if (packageName == null || ks == null) { 17737 return false; 17738 } 17739 synchronized(mPackages) { 17740 final PackageParser.Package pkg = mPackages.get(packageName); 17741 if (pkg == null) { 17742 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17743 throw new IllegalArgumentException("Unknown package: " + packageName); 17744 } 17745 IBinder ksh = ks.getToken(); 17746 if (ksh instanceof KeySetHandle) { 17747 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17748 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 17749 } 17750 return false; 17751 } 17752 } 17753 17754 @Override 17755 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 17756 if (packageName == null || ks == null) { 17757 return false; 17758 } 17759 synchronized(mPackages) { 17760 final PackageParser.Package pkg = mPackages.get(packageName); 17761 if (pkg == null) { 17762 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17763 throw new IllegalArgumentException("Unknown package: " + packageName); 17764 } 17765 IBinder ksh = ks.getToken(); 17766 if (ksh instanceof KeySetHandle) { 17767 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17768 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 17769 } 17770 return false; 17771 } 17772 } 17773 17774 private void deletePackageIfUnusedLPr(final String packageName) { 17775 PackageSetting ps = mSettings.mPackages.get(packageName); 17776 if (ps == null) { 17777 return; 17778 } 17779 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 17780 // TODO Implement atomic delete if package is unused 17781 // It is currently possible that the package will be deleted even if it is installed 17782 // after this method returns. 17783 mHandler.post(new Runnable() { 17784 public void run() { 17785 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 17786 } 17787 }); 17788 } 17789 } 17790 17791 /** 17792 * Check and throw if the given before/after packages would be considered a 17793 * downgrade. 17794 */ 17795 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 17796 throws PackageManagerException { 17797 if (after.versionCode < before.mVersionCode) { 17798 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17799 "Update version code " + after.versionCode + " is older than current " 17800 + before.mVersionCode); 17801 } else if (after.versionCode == before.mVersionCode) { 17802 if (after.baseRevisionCode < before.baseRevisionCode) { 17803 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17804 "Update base revision code " + after.baseRevisionCode 17805 + " is older than current " + before.baseRevisionCode); 17806 } 17807 17808 if (!ArrayUtils.isEmpty(after.splitNames)) { 17809 for (int i = 0; i < after.splitNames.length; i++) { 17810 final String splitName = after.splitNames[i]; 17811 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 17812 if (j != -1) { 17813 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 17814 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17815 "Update split " + splitName + " revision code " 17816 + after.splitRevisionCodes[i] + " is older than current " 17817 + before.splitRevisionCodes[j]); 17818 } 17819 } 17820 } 17821 } 17822 } 17823 } 17824 17825 private static class MoveCallbacks extends Handler { 17826 private static final int MSG_CREATED = 1; 17827 private static final int MSG_STATUS_CHANGED = 2; 17828 17829 private final RemoteCallbackList<IPackageMoveObserver> 17830 mCallbacks = new RemoteCallbackList<>(); 17831 17832 private final SparseIntArray mLastStatus = new SparseIntArray(); 17833 17834 public MoveCallbacks(Looper looper) { 17835 super(looper); 17836 } 17837 17838 public void register(IPackageMoveObserver callback) { 17839 mCallbacks.register(callback); 17840 } 17841 17842 public void unregister(IPackageMoveObserver callback) { 17843 mCallbacks.unregister(callback); 17844 } 17845 17846 @Override 17847 public void handleMessage(Message msg) { 17848 final SomeArgs args = (SomeArgs) msg.obj; 17849 final int n = mCallbacks.beginBroadcast(); 17850 for (int i = 0; i < n; i++) { 17851 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 17852 try { 17853 invokeCallback(callback, msg.what, args); 17854 } catch (RemoteException ignored) { 17855 } 17856 } 17857 mCallbacks.finishBroadcast(); 17858 args.recycle(); 17859 } 17860 17861 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 17862 throws RemoteException { 17863 switch (what) { 17864 case MSG_CREATED: { 17865 callback.onCreated(args.argi1, (Bundle) args.arg2); 17866 break; 17867 } 17868 case MSG_STATUS_CHANGED: { 17869 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 17870 break; 17871 } 17872 } 17873 } 17874 17875 private void notifyCreated(int moveId, Bundle extras) { 17876 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 17877 17878 final SomeArgs args = SomeArgs.obtain(); 17879 args.argi1 = moveId; 17880 args.arg2 = extras; 17881 obtainMessage(MSG_CREATED, args).sendToTarget(); 17882 } 17883 17884 private void notifyStatusChanged(int moveId, int status) { 17885 notifyStatusChanged(moveId, status, -1); 17886 } 17887 17888 private void notifyStatusChanged(int moveId, int status, long estMillis) { 17889 Slog.v(TAG, "Move " + moveId + " status " + status); 17890 17891 final SomeArgs args = SomeArgs.obtain(); 17892 args.argi1 = moveId; 17893 args.argi2 = status; 17894 args.arg3 = estMillis; 17895 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 17896 17897 synchronized (mLastStatus) { 17898 mLastStatus.put(moveId, status); 17899 } 17900 } 17901 } 17902 17903 private final static class OnPermissionChangeListeners extends Handler { 17904 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 17905 17906 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 17907 new RemoteCallbackList<>(); 17908 17909 public OnPermissionChangeListeners(Looper looper) { 17910 super(looper); 17911 } 17912 17913 @Override 17914 public void handleMessage(Message msg) { 17915 switch (msg.what) { 17916 case MSG_ON_PERMISSIONS_CHANGED: { 17917 final int uid = msg.arg1; 17918 handleOnPermissionsChanged(uid); 17919 } break; 17920 } 17921 } 17922 17923 public void addListenerLocked(IOnPermissionsChangeListener listener) { 17924 mPermissionListeners.register(listener); 17925 17926 } 17927 17928 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 17929 mPermissionListeners.unregister(listener); 17930 } 17931 17932 public void onPermissionsChanged(int uid) { 17933 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 17934 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 17935 } 17936 } 17937 17938 private void handleOnPermissionsChanged(int uid) { 17939 final int count = mPermissionListeners.beginBroadcast(); 17940 try { 17941 for (int i = 0; i < count; i++) { 17942 IOnPermissionsChangeListener callback = mPermissionListeners 17943 .getBroadcastItem(i); 17944 try { 17945 callback.onPermissionsChanged(uid); 17946 } catch (RemoteException e) { 17947 Log.e(TAG, "Permission listener is dead", e); 17948 } 17949 } 17950 } finally { 17951 mPermissionListeners.finishBroadcast(); 17952 } 17953 } 17954 } 17955 17956 private class PackageManagerInternalImpl extends PackageManagerInternal { 17957 @Override 17958 public void setLocationPackagesProvider(PackagesProvider provider) { 17959 synchronized (mPackages) { 17960 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 17961 } 17962 } 17963 17964 @Override 17965 public void setImePackagesProvider(PackagesProvider provider) { 17966 synchronized (mPackages) { 17967 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 17968 } 17969 } 17970 17971 @Override 17972 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 17973 synchronized (mPackages) { 17974 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 17975 } 17976 } 17977 17978 @Override 17979 public void setSmsAppPackagesProvider(PackagesProvider provider) { 17980 synchronized (mPackages) { 17981 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 17982 } 17983 } 17984 17985 @Override 17986 public void setDialerAppPackagesProvider(PackagesProvider provider) { 17987 synchronized (mPackages) { 17988 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 17989 } 17990 } 17991 17992 @Override 17993 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 17994 synchronized (mPackages) { 17995 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 17996 } 17997 } 17998 17999 @Override 18000 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 18001 synchronized (mPackages) { 18002 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 18003 } 18004 } 18005 18006 @Override 18007 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 18008 synchronized (mPackages) { 18009 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 18010 packageName, userId); 18011 } 18012 } 18013 18014 @Override 18015 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 18016 synchronized (mPackages) { 18017 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 18018 packageName, userId); 18019 } 18020 } 18021 18022 @Override 18023 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 18024 synchronized (mPackages) { 18025 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 18026 packageName, userId); 18027 } 18028 } 18029 18030 @Override 18031 public void setKeepUninstalledPackages(final List<String> packageList) { 18032 Preconditions.checkNotNull(packageList); 18033 List<String> removedFromList = null; 18034 synchronized (mPackages) { 18035 if (mKeepUninstalledPackages != null) { 18036 final int packagesCount = mKeepUninstalledPackages.size(); 18037 for (int i = 0; i < packagesCount; i++) { 18038 String oldPackage = mKeepUninstalledPackages.get(i); 18039 if (packageList != null && packageList.contains(oldPackage)) { 18040 continue; 18041 } 18042 if (removedFromList == null) { 18043 removedFromList = new ArrayList<>(); 18044 } 18045 removedFromList.add(oldPackage); 18046 } 18047 } 18048 mKeepUninstalledPackages = new ArrayList<>(packageList); 18049 if (removedFromList != null) { 18050 final int removedCount = removedFromList.size(); 18051 for (int i = 0; i < removedCount; i++) { 18052 deletePackageIfUnusedLPr(removedFromList.get(i)); 18053 } 18054 } 18055 } 18056 } 18057 18058 @Override 18059 public boolean isPermissionsReviewRequired(String packageName, int userId) { 18060 synchronized (mPackages) { 18061 // If we do not support permission review, done. 18062 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 18063 return false; 18064 } 18065 18066 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 18067 if (packageSetting == null) { 18068 return false; 18069 } 18070 18071 // Permission review applies only to apps not supporting the new permission model. 18072 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 18073 return false; 18074 } 18075 18076 // Legacy apps have the permission and get user consent on launch. 18077 PermissionsState permissionsState = packageSetting.getPermissionsState(); 18078 return permissionsState.isPermissionReviewRequired(userId); 18079 } 18080 } 18081 } 18082 18083 @Override 18084 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 18085 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 18086 synchronized (mPackages) { 18087 final long identity = Binder.clearCallingIdentity(); 18088 try { 18089 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 18090 packageNames, userId); 18091 } finally { 18092 Binder.restoreCallingIdentity(identity); 18093 } 18094 } 18095 } 18096 18097 private static void enforceSystemOrPhoneCaller(String tag) { 18098 int callingUid = Binder.getCallingUid(); 18099 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 18100 throw new SecurityException( 18101 "Cannot call " + tag + " from UID " + callingUid); 18102 } 18103 } 18104 18105 boolean isHistoricalPackageUsageAvailable() { 18106 return mPackageUsage.isHistoricalPackageUsageAvailable(); 18107 } 18108} 18109