PackageManagerService.java revision 693f997cc8b8c2ba8d3ed29627b2641dd86392a5
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 65import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 67import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 68import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 69import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 70import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 71import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 72import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 73import static android.content.pm.PackageManager.PERMISSION_DENIED; 74import static android.content.pm.PackageManager.PERMISSION_GRANTED; 75import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 76import static android.content.pm.PackageParser.isApkFile; 77import static android.os.Process.PACKAGE_INFO_GID; 78import static android.os.Process.SYSTEM_UID; 79import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 80import static android.system.OsConstants.O_CREAT; 81import static android.system.OsConstants.O_RDWR; 82 83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 85import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 86import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 87import static com.android.internal.util.ArrayUtils.appendInt; 88import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 89import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 92import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 93import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 94import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 95import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 97 98import android.Manifest; 99import android.annotation.NonNull; 100import android.annotation.Nullable; 101import android.app.ActivityManager; 102import android.app.ActivityManagerNative; 103import android.app.IActivityManager; 104import android.app.admin.IDevicePolicyManager; 105import android.app.backup.IBackupManager; 106import android.content.BroadcastReceiver; 107import android.content.ComponentName; 108import android.content.Context; 109import android.content.IIntentReceiver; 110import android.content.Intent; 111import android.content.IntentFilter; 112import android.content.IntentSender; 113import android.content.IntentSender.SendIntentException; 114import android.content.ServiceConnection; 115import android.content.pm.ActivityInfo; 116import android.content.pm.ApplicationInfo; 117import android.content.pm.AppsQueryHelper; 118import android.content.pm.ComponentInfo; 119import android.content.pm.EphemeralApplicationInfo; 120import android.content.pm.EphemeralResolveInfo; 121import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 122import android.content.pm.FeatureInfo; 123import android.content.pm.IOnPermissionsChangeListener; 124import android.content.pm.IPackageDataObserver; 125import android.content.pm.IPackageDeleteObserver; 126import android.content.pm.IPackageDeleteObserver2; 127import android.content.pm.IPackageInstallObserver2; 128import android.content.pm.IPackageInstaller; 129import android.content.pm.IPackageManager; 130import android.content.pm.IPackageMoveObserver; 131import android.content.pm.IPackageStatsObserver; 132import android.content.pm.InstrumentationInfo; 133import android.content.pm.IntentFilterVerificationInfo; 134import android.content.pm.KeySet; 135import android.content.pm.PackageCleanItem; 136import android.content.pm.PackageInfo; 137import android.content.pm.PackageInfoLite; 138import android.content.pm.PackageInstaller; 139import android.content.pm.PackageManager; 140import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 141import android.content.pm.PackageManagerInternal; 142import android.content.pm.PackageParser; 143import android.content.pm.PackageParser.ActivityIntentInfo; 144import android.content.pm.PackageParser.PackageLite; 145import android.content.pm.PackageParser.PackageParserException; 146import android.content.pm.PackageStats; 147import android.content.pm.PackageUserState; 148import android.content.pm.ParceledListSlice; 149import android.content.pm.PermissionGroupInfo; 150import android.content.pm.PermissionInfo; 151import android.content.pm.ProviderInfo; 152import android.content.pm.ResolveInfo; 153import android.content.pm.ServiceInfo; 154import android.content.pm.Signature; 155import android.content.pm.UserInfo; 156import android.content.pm.VerificationParams; 157import android.content.pm.VerifierDeviceIdentity; 158import android.content.pm.VerifierInfo; 159import android.content.res.Resources; 160import android.graphics.Bitmap; 161import android.hardware.display.DisplayManager; 162import android.net.Uri; 163import android.os.Binder; 164import android.os.Build; 165import android.os.Bundle; 166import android.os.Debug; 167import android.os.Environment; 168import android.os.Environment.UserEnvironment; 169import android.os.FileUtils; 170import android.os.Handler; 171import android.os.IBinder; 172import android.os.Looper; 173import android.os.Message; 174import android.os.Parcel; 175import android.os.ParcelFileDescriptor; 176import android.os.Process; 177import android.os.RemoteCallbackList; 178import android.os.RemoteException; 179import android.os.ResultReceiver; 180import android.os.SELinux; 181import android.os.ServiceManager; 182import android.os.SystemClock; 183import android.os.SystemProperties; 184import android.os.Trace; 185import android.os.UserHandle; 186import android.os.UserManager; 187import android.os.storage.IMountService; 188import android.os.storage.MountServiceInternal; 189import android.os.storage.StorageEventListener; 190import android.os.storage.StorageManager; 191import android.os.storage.VolumeInfo; 192import android.os.storage.VolumeRecord; 193import android.security.KeyStore; 194import android.security.SystemKeyStore; 195import android.system.ErrnoException; 196import android.system.Os; 197import android.text.TextUtils; 198import android.text.format.DateUtils; 199import android.util.ArrayMap; 200import android.util.ArraySet; 201import android.util.AtomicFile; 202import android.util.DisplayMetrics; 203import android.util.EventLog; 204import android.util.ExceptionUtils; 205import android.util.Log; 206import android.util.LogPrinter; 207import android.util.MathUtils; 208import android.util.PrintStreamPrinter; 209import android.util.Slog; 210import android.util.SparseArray; 211import android.util.SparseBooleanArray; 212import android.util.SparseIntArray; 213import android.util.Xml; 214import android.view.Display; 215 216import com.android.internal.R; 217import com.android.internal.annotations.GuardedBy; 218import com.android.internal.app.IMediaContainerService; 219import com.android.internal.app.ResolverActivity; 220import com.android.internal.content.NativeLibraryHelper; 221import com.android.internal.content.PackageHelper; 222import com.android.internal.os.IParcelFileDescriptorFactory; 223import com.android.internal.os.InstallerConnection.InstallerException; 224import com.android.internal.os.SomeArgs; 225import com.android.internal.os.Zygote; 226import com.android.internal.util.ArrayUtils; 227import com.android.internal.util.FastPrintWriter; 228import com.android.internal.util.FastXmlSerializer; 229import com.android.internal.util.IndentingPrintWriter; 230import com.android.internal.util.Preconditions; 231import com.android.internal.util.XmlUtils; 232import com.android.server.EventLogTags; 233import com.android.server.FgThread; 234import com.android.server.IntentResolver; 235import com.android.server.LocalServices; 236import com.android.server.ServiceThread; 237import com.android.server.SystemConfig; 238import com.android.server.Watchdog; 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.PrintWriter; 268import java.nio.charset.StandardCharsets; 269import java.security.MessageDigest; 270import java.security.NoSuchAlgorithmException; 271import java.security.PublicKey; 272import java.security.cert.CertificateEncodingException; 273import java.security.cert.CertificateException; 274import java.text.SimpleDateFormat; 275import java.util.ArrayList; 276import java.util.Arrays; 277import java.util.Collection; 278import java.util.Collections; 279import java.util.Comparator; 280import java.util.Date; 281import java.util.HashSet; 282import java.util.Iterator; 283import java.util.List; 284import java.util.Map; 285import java.util.Objects; 286import java.util.Set; 287import java.util.concurrent.CountDownLatch; 288import java.util.concurrent.TimeUnit; 289import java.util.concurrent.atomic.AtomicBoolean; 290import java.util.concurrent.atomic.AtomicInteger; 291import java.util.concurrent.atomic.AtomicLong; 292 293/** 294 * Keep track of all those .apks everywhere. 295 * 296 * This is very central to the platform's security; please run the unit 297 * tests whenever making modifications here: 298 * 299runtest -c android.content.pm.PackageManagerTests frameworks-core 300 * 301 * {@hide} 302 */ 303public class PackageManagerService extends IPackageManager.Stub { 304 static final String TAG = "PackageManager"; 305 static final boolean DEBUG_SETTINGS = false; 306 static final boolean DEBUG_PREFERRED = false; 307 static final boolean DEBUG_UPGRADE = false; 308 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 309 private static final boolean DEBUG_BACKUP = false; 310 private static final boolean DEBUG_INSTALL = false; 311 private static final boolean DEBUG_REMOVE = false; 312 private static final boolean DEBUG_BROADCASTS = false; 313 private static final boolean DEBUG_SHOW_INFO = false; 314 private static final boolean DEBUG_PACKAGE_INFO = false; 315 private static final boolean DEBUG_INTENT_MATCHING = false; 316 private static final boolean DEBUG_PACKAGE_SCANNING = false; 317 private static final boolean DEBUG_VERIFY = false; 318 319 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 320 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 321 // user, but by default initialize to this. 322 static final boolean DEBUG_DEXOPT = false; 323 324 private static final boolean DEBUG_ABI_SELECTION = false; 325 private static final boolean DEBUG_EPHEMERAL = false; 326 private static final boolean DEBUG_TRIAGED_MISSING = false; 327 private static final boolean DEBUG_APP_DATA = false; 328 329 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 330 331 private static final boolean DISABLE_EPHEMERAL_APPS = true; 332 333 private static final int RADIO_UID = Process.PHONE_UID; 334 private static final int LOG_UID = Process.LOG_UID; 335 private static final int NFC_UID = Process.NFC_UID; 336 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 337 private static final int SHELL_UID = Process.SHELL_UID; 338 339 // Cap the size of permission trees that 3rd party apps can define 340 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 341 342 // Suffix used during package installation when copying/moving 343 // package apks to install directory. 344 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 345 346 static final int SCAN_NO_DEX = 1<<1; 347 static final int SCAN_FORCE_DEX = 1<<2; 348 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 349 static final int SCAN_NEW_INSTALL = 1<<4; 350 static final int SCAN_NO_PATHS = 1<<5; 351 static final int SCAN_UPDATE_TIME = 1<<6; 352 static final int SCAN_DEFER_DEX = 1<<7; 353 static final int SCAN_BOOTING = 1<<8; 354 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 355 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 356 static final int SCAN_REPLACING = 1<<11; 357 static final int SCAN_REQUIRE_KNOWN = 1<<12; 358 static final int SCAN_MOVE = 1<<13; 359 static final int SCAN_INITIAL = 1<<14; 360 static final int SCAN_CHECK_ONLY = 1<<15; 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 static class IFVerificationParams { 641 PackageParser.Package pkg; 642 boolean replacing; 643 int userId; 644 int verifierUid; 645 646 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 647 int _userId, int _verifierUid) { 648 pkg = _pkg; 649 replacing = _replacing; 650 userId = _userId; 651 replacing = _replacing; 652 verifierUid = _verifierUid; 653 } 654 } 655 656 private interface IntentFilterVerifier<T extends IntentFilter> { 657 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 658 T filter, String packageName); 659 void startVerifications(int userId); 660 void receiveVerificationResponse(int verificationId); 661 } 662 663 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 664 private Context mContext; 665 private ComponentName mIntentFilterVerifierComponent; 666 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 667 668 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 669 mContext = context; 670 mIntentFilterVerifierComponent = verifierComponent; 671 } 672 673 private String getDefaultScheme() { 674 return IntentFilter.SCHEME_HTTPS; 675 } 676 677 @Override 678 public void startVerifications(int userId) { 679 // Launch verifications requests 680 int count = mCurrentIntentFilterVerifications.size(); 681 for (int n=0; n<count; n++) { 682 int verificationId = mCurrentIntentFilterVerifications.get(n); 683 final IntentFilterVerificationState ivs = 684 mIntentFilterVerificationStates.get(verificationId); 685 686 String packageName = ivs.getPackageName(); 687 688 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 689 final int filterCount = filters.size(); 690 ArraySet<String> domainsSet = new ArraySet<>(); 691 for (int m=0; m<filterCount; m++) { 692 PackageParser.ActivityIntentInfo filter = filters.get(m); 693 domainsSet.addAll(filter.getHostsList()); 694 } 695 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 696 synchronized (mPackages) { 697 if (mSettings.createIntentFilterVerificationIfNeededLPw( 698 packageName, domainsList) != null) { 699 scheduleWriteSettingsLocked(); 700 } 701 } 702 sendVerificationRequest(userId, verificationId, ivs); 703 } 704 mCurrentIntentFilterVerifications.clear(); 705 } 706 707 private void sendVerificationRequest(int userId, int verificationId, 708 IntentFilterVerificationState ivs) { 709 710 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 711 verificationIntent.putExtra( 712 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 713 verificationId); 714 verificationIntent.putExtra( 715 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 716 getDefaultScheme()); 717 verificationIntent.putExtra( 718 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 719 ivs.getHostsString()); 720 verificationIntent.putExtra( 721 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 722 ivs.getPackageName()); 723 verificationIntent.setComponent(mIntentFilterVerifierComponent); 724 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 725 726 UserHandle user = new UserHandle(userId); 727 mContext.sendBroadcastAsUser(verificationIntent, user); 728 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 729 "Sending IntentFilter verification broadcast"); 730 } 731 732 public void receiveVerificationResponse(int verificationId) { 733 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 734 735 final boolean verified = ivs.isVerified(); 736 737 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 738 final int count = filters.size(); 739 if (DEBUG_DOMAIN_VERIFICATION) { 740 Slog.i(TAG, "Received verification response " + verificationId 741 + " for " + count + " filters, verified=" + verified); 742 } 743 for (int n=0; n<count; n++) { 744 PackageParser.ActivityIntentInfo filter = filters.get(n); 745 filter.setVerified(verified); 746 747 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 748 + " verified with result:" + verified + " and hosts:" 749 + ivs.getHostsString()); 750 } 751 752 mIntentFilterVerificationStates.remove(verificationId); 753 754 final String packageName = ivs.getPackageName(); 755 IntentFilterVerificationInfo ivi = null; 756 757 synchronized (mPackages) { 758 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 759 } 760 if (ivi == null) { 761 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 762 + verificationId + " packageName:" + packageName); 763 return; 764 } 765 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 766 "Updating IntentFilterVerificationInfo for package " + packageName 767 +" verificationId:" + verificationId); 768 769 synchronized (mPackages) { 770 if (verified) { 771 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 772 } else { 773 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 774 } 775 scheduleWriteSettingsLocked(); 776 777 final int userId = ivs.getUserId(); 778 if (userId != UserHandle.USER_ALL) { 779 final int userStatus = 780 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 781 782 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 783 boolean needUpdate = false; 784 785 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 786 // already been set by the User thru the Disambiguation dialog 787 switch (userStatus) { 788 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 789 if (verified) { 790 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 791 } else { 792 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 793 } 794 needUpdate = true; 795 break; 796 797 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 798 if (verified) { 799 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 800 needUpdate = true; 801 } 802 break; 803 804 default: 805 // Nothing to do 806 } 807 808 if (needUpdate) { 809 mSettings.updateIntentFilterVerificationStatusLPw( 810 packageName, updatedStatus, userId); 811 scheduleWritePackageRestrictionsLocked(userId); 812 } 813 } 814 } 815 } 816 817 @Override 818 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 819 ActivityIntentInfo filter, String packageName) { 820 if (!hasValidDomains(filter)) { 821 return false; 822 } 823 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 824 if (ivs == null) { 825 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 826 packageName); 827 } 828 if (DEBUG_DOMAIN_VERIFICATION) { 829 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 830 } 831 ivs.addFilter(filter); 832 return true; 833 } 834 835 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 836 int userId, int verificationId, String packageName) { 837 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 838 verifierUid, userId, packageName); 839 ivs.setPendingState(); 840 synchronized (mPackages) { 841 mIntentFilterVerificationStates.append(verificationId, ivs); 842 mCurrentIntentFilterVerifications.add(verificationId); 843 } 844 return ivs; 845 } 846 } 847 848 private static boolean hasValidDomains(ActivityIntentInfo filter) { 849 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 850 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 851 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 852 } 853 854 // Set of pending broadcasts for aggregating enable/disable of components. 855 static class PendingPackageBroadcasts { 856 // for each user id, a map of <package name -> components within that package> 857 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 858 859 public PendingPackageBroadcasts() { 860 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 861 } 862 863 public ArrayList<String> get(int userId, String packageName) { 864 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 865 return packages.get(packageName); 866 } 867 868 public void put(int userId, String packageName, ArrayList<String> components) { 869 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 870 packages.put(packageName, components); 871 } 872 873 public void remove(int userId, String packageName) { 874 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 875 if (packages != null) { 876 packages.remove(packageName); 877 } 878 } 879 880 public void remove(int userId) { 881 mUidMap.remove(userId); 882 } 883 884 public int userIdCount() { 885 return mUidMap.size(); 886 } 887 888 public int userIdAt(int n) { 889 return mUidMap.keyAt(n); 890 } 891 892 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 893 return mUidMap.get(userId); 894 } 895 896 public int size() { 897 // total number of pending broadcast entries across all userIds 898 int num = 0; 899 for (int i = 0; i< mUidMap.size(); i++) { 900 num += mUidMap.valueAt(i).size(); 901 } 902 return num; 903 } 904 905 public void clear() { 906 mUidMap.clear(); 907 } 908 909 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 910 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 911 if (map == null) { 912 map = new ArrayMap<String, ArrayList<String>>(); 913 mUidMap.put(userId, map); 914 } 915 return map; 916 } 917 } 918 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 919 920 // Service Connection to remote media container service to copy 921 // package uri's from external media onto secure containers 922 // or internal storage. 923 private IMediaContainerService mContainerService = null; 924 925 static final int SEND_PENDING_BROADCAST = 1; 926 static final int MCS_BOUND = 3; 927 static final int END_COPY = 4; 928 static final int INIT_COPY = 5; 929 static final int MCS_UNBIND = 6; 930 static final int START_CLEANING_PACKAGE = 7; 931 static final int FIND_INSTALL_LOC = 8; 932 static final int POST_INSTALL = 9; 933 static final int MCS_RECONNECT = 10; 934 static final int MCS_GIVE_UP = 11; 935 static final int UPDATED_MEDIA_STATUS = 12; 936 static final int WRITE_SETTINGS = 13; 937 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 938 static final int PACKAGE_VERIFIED = 15; 939 static final int CHECK_PENDING_VERIFICATION = 16; 940 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 941 static final int INTENT_FILTER_VERIFIED = 18; 942 943 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 944 945 // Delay time in millisecs 946 static final int BROADCAST_DELAY = 10 * 1000; 947 948 static UserManagerService sUserManager; 949 950 // Stores a list of users whose package restrictions file needs to be updated 951 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 952 953 final private DefaultContainerConnection mDefContainerConn = 954 new DefaultContainerConnection(); 955 class DefaultContainerConnection implements ServiceConnection { 956 public void onServiceConnected(ComponentName name, IBinder service) { 957 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 958 IMediaContainerService imcs = 959 IMediaContainerService.Stub.asInterface(service); 960 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 961 } 962 963 public void onServiceDisconnected(ComponentName name) { 964 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 965 } 966 } 967 968 // Recordkeeping of restore-after-install operations that are currently in flight 969 // between the Package Manager and the Backup Manager 970 static class PostInstallData { 971 public InstallArgs args; 972 public PackageInstalledInfo res; 973 974 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 975 args = _a; 976 res = _r; 977 } 978 } 979 980 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 981 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 982 983 // XML tags for backup/restore of various bits of state 984 private static final String TAG_PREFERRED_BACKUP = "pa"; 985 private static final String TAG_DEFAULT_APPS = "da"; 986 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 987 988 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 989 private static final String TAG_ALL_GRANTS = "rt-grants"; 990 private static final String TAG_GRANT = "grant"; 991 private static final String ATTR_PACKAGE_NAME = "pkg"; 992 993 private static final String TAG_PERMISSION = "perm"; 994 private static final String ATTR_PERMISSION_NAME = "name"; 995 private static final String ATTR_IS_GRANTED = "g"; 996 private static final String ATTR_USER_SET = "set"; 997 private static final String ATTR_USER_FIXED = "fixed"; 998 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 999 1000 // System/policy permission grants are not backed up 1001 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1002 FLAG_PERMISSION_POLICY_FIXED 1003 | FLAG_PERMISSION_SYSTEM_FIXED 1004 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1005 1006 // And we back up these user-adjusted states 1007 private static final int USER_RUNTIME_GRANT_MASK = 1008 FLAG_PERMISSION_USER_SET 1009 | FLAG_PERMISSION_USER_FIXED 1010 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1011 1012 final @Nullable String mRequiredVerifierPackage; 1013 final @Nullable String mRequiredInstallerPackage; 1014 1015 private final PackageUsage mPackageUsage = new PackageUsage(); 1016 1017 private class PackageUsage { 1018 private static final int WRITE_INTERVAL 1019 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1020 1021 private final Object mFileLock = new Object(); 1022 private final AtomicLong mLastWritten = new AtomicLong(0); 1023 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1024 1025 private boolean mIsHistoricalPackageUsageAvailable = true; 1026 1027 boolean isHistoricalPackageUsageAvailable() { 1028 return mIsHistoricalPackageUsageAvailable; 1029 } 1030 1031 void write(boolean force) { 1032 if (force) { 1033 writeInternal(); 1034 return; 1035 } 1036 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1037 && !DEBUG_DEXOPT) { 1038 return; 1039 } 1040 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1041 new Thread("PackageUsage_DiskWriter") { 1042 @Override 1043 public void run() { 1044 try { 1045 writeInternal(); 1046 } finally { 1047 mBackgroundWriteRunning.set(false); 1048 } 1049 } 1050 }.start(); 1051 } 1052 } 1053 1054 private void writeInternal() { 1055 synchronized (mPackages) { 1056 synchronized (mFileLock) { 1057 AtomicFile file = getFile(); 1058 FileOutputStream f = null; 1059 try { 1060 f = file.startWrite(); 1061 BufferedOutputStream out = new BufferedOutputStream(f); 1062 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1063 StringBuilder sb = new StringBuilder(); 1064 for (PackageParser.Package pkg : mPackages.values()) { 1065 if (pkg.mLastPackageUsageTimeInMills == 0) { 1066 continue; 1067 } 1068 sb.setLength(0); 1069 sb.append(pkg.packageName); 1070 sb.append(' '); 1071 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1072 sb.append('\n'); 1073 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1074 } 1075 out.flush(); 1076 file.finishWrite(f); 1077 } catch (IOException e) { 1078 if (f != null) { 1079 file.failWrite(f); 1080 } 1081 Log.e(TAG, "Failed to write package usage times", e); 1082 } 1083 } 1084 } 1085 mLastWritten.set(SystemClock.elapsedRealtime()); 1086 } 1087 1088 void readLP() { 1089 synchronized (mFileLock) { 1090 AtomicFile file = getFile(); 1091 BufferedInputStream in = null; 1092 try { 1093 in = new BufferedInputStream(file.openRead()); 1094 StringBuffer sb = new StringBuffer(); 1095 while (true) { 1096 String packageName = readToken(in, sb, ' '); 1097 if (packageName == null) { 1098 break; 1099 } 1100 String timeInMillisString = readToken(in, sb, '\n'); 1101 if (timeInMillisString == null) { 1102 throw new IOException("Failed to find last usage time for package " 1103 + packageName); 1104 } 1105 PackageParser.Package pkg = mPackages.get(packageName); 1106 if (pkg == null) { 1107 continue; 1108 } 1109 long timeInMillis; 1110 try { 1111 timeInMillis = Long.parseLong(timeInMillisString); 1112 } catch (NumberFormatException e) { 1113 throw new IOException("Failed to parse " + timeInMillisString 1114 + " as a long.", e); 1115 } 1116 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1117 } 1118 } catch (FileNotFoundException expected) { 1119 mIsHistoricalPackageUsageAvailable = false; 1120 } catch (IOException e) { 1121 Log.w(TAG, "Failed to read package usage times", e); 1122 } finally { 1123 IoUtils.closeQuietly(in); 1124 } 1125 } 1126 mLastWritten.set(SystemClock.elapsedRealtime()); 1127 } 1128 1129 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1130 throws IOException { 1131 sb.setLength(0); 1132 while (true) { 1133 int ch = in.read(); 1134 if (ch == -1) { 1135 if (sb.length() == 0) { 1136 return null; 1137 } 1138 throw new IOException("Unexpected EOF"); 1139 } 1140 if (ch == endOfToken) { 1141 return sb.toString(); 1142 } 1143 sb.append((char)ch); 1144 } 1145 } 1146 1147 private AtomicFile getFile() { 1148 File dataDir = Environment.getDataDirectory(); 1149 File systemDir = new File(dataDir, "system"); 1150 File fname = new File(systemDir, "package-usage.list"); 1151 return new AtomicFile(fname); 1152 } 1153 } 1154 1155 class PackageHandler extends Handler { 1156 private boolean mBound = false; 1157 final ArrayList<HandlerParams> mPendingInstalls = 1158 new ArrayList<HandlerParams>(); 1159 1160 private boolean connectToService() { 1161 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1162 " DefaultContainerService"); 1163 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1164 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1165 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1166 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1167 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1168 mBound = true; 1169 return true; 1170 } 1171 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1172 return false; 1173 } 1174 1175 private void disconnectService() { 1176 mContainerService = null; 1177 mBound = false; 1178 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1179 mContext.unbindService(mDefContainerConn); 1180 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1181 } 1182 1183 PackageHandler(Looper looper) { 1184 super(looper); 1185 } 1186 1187 public void handleMessage(Message msg) { 1188 try { 1189 doHandleMessage(msg); 1190 } finally { 1191 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1192 } 1193 } 1194 1195 void doHandleMessage(Message msg) { 1196 switch (msg.what) { 1197 case INIT_COPY: { 1198 HandlerParams params = (HandlerParams) msg.obj; 1199 int idx = mPendingInstalls.size(); 1200 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1201 // If a bind was already initiated we dont really 1202 // need to do anything. The pending install 1203 // will be processed later on. 1204 if (!mBound) { 1205 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1206 System.identityHashCode(mHandler)); 1207 // If this is the only one pending we might 1208 // have to bind to the service again. 1209 if (!connectToService()) { 1210 Slog.e(TAG, "Failed to bind to media container service"); 1211 params.serviceError(); 1212 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1213 System.identityHashCode(mHandler)); 1214 if (params.traceMethod != null) { 1215 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1216 params.traceCookie); 1217 } 1218 return; 1219 } else { 1220 // Once we bind to the service, the first 1221 // pending request will be processed. 1222 mPendingInstalls.add(idx, params); 1223 } 1224 } else { 1225 mPendingInstalls.add(idx, params); 1226 // Already bound to the service. Just make 1227 // sure we trigger off processing the first request. 1228 if (idx == 0) { 1229 mHandler.sendEmptyMessage(MCS_BOUND); 1230 } 1231 } 1232 break; 1233 } 1234 case MCS_BOUND: { 1235 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1236 if (msg.obj != null) { 1237 mContainerService = (IMediaContainerService) msg.obj; 1238 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1239 System.identityHashCode(mHandler)); 1240 } 1241 if (mContainerService == null) { 1242 if (!mBound) { 1243 // Something seriously wrong since we are not bound and we are not 1244 // waiting for connection. Bail out. 1245 Slog.e(TAG, "Cannot bind to media container service"); 1246 for (HandlerParams params : mPendingInstalls) { 1247 // Indicate service bind error 1248 params.serviceError(); 1249 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1250 System.identityHashCode(params)); 1251 if (params.traceMethod != null) { 1252 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1253 params.traceMethod, params.traceCookie); 1254 } 1255 return; 1256 } 1257 mPendingInstalls.clear(); 1258 } else { 1259 Slog.w(TAG, "Waiting to connect to media container service"); 1260 } 1261 } else if (mPendingInstalls.size() > 0) { 1262 HandlerParams params = mPendingInstalls.get(0); 1263 if (params != null) { 1264 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1265 System.identityHashCode(params)); 1266 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1267 if (params.startCopy()) { 1268 // We are done... look for more work or to 1269 // go idle. 1270 if (DEBUG_SD_INSTALL) Log.i(TAG, 1271 "Checking for more work or unbind..."); 1272 // Delete pending install 1273 if (mPendingInstalls.size() > 0) { 1274 mPendingInstalls.remove(0); 1275 } 1276 if (mPendingInstalls.size() == 0) { 1277 if (mBound) { 1278 if (DEBUG_SD_INSTALL) Log.i(TAG, 1279 "Posting delayed MCS_UNBIND"); 1280 removeMessages(MCS_UNBIND); 1281 Message ubmsg = obtainMessage(MCS_UNBIND); 1282 // Unbind after a little delay, to avoid 1283 // continual thrashing. 1284 sendMessageDelayed(ubmsg, 10000); 1285 } 1286 } else { 1287 // There are more pending requests in queue. 1288 // Just post MCS_BOUND message to trigger processing 1289 // of next pending install. 1290 if (DEBUG_SD_INSTALL) Log.i(TAG, 1291 "Posting MCS_BOUND for next work"); 1292 mHandler.sendEmptyMessage(MCS_BOUND); 1293 } 1294 } 1295 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1296 } 1297 } else { 1298 // Should never happen ideally. 1299 Slog.w(TAG, "Empty queue"); 1300 } 1301 break; 1302 } 1303 case MCS_RECONNECT: { 1304 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1305 if (mPendingInstalls.size() > 0) { 1306 if (mBound) { 1307 disconnectService(); 1308 } 1309 if (!connectToService()) { 1310 Slog.e(TAG, "Failed to bind to media container service"); 1311 for (HandlerParams params : mPendingInstalls) { 1312 // Indicate service bind error 1313 params.serviceError(); 1314 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1315 System.identityHashCode(params)); 1316 } 1317 mPendingInstalls.clear(); 1318 } 1319 } 1320 break; 1321 } 1322 case MCS_UNBIND: { 1323 // If there is no actual work left, then time to unbind. 1324 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1325 1326 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1327 if (mBound) { 1328 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1329 1330 disconnectService(); 1331 } 1332 } else if (mPendingInstalls.size() > 0) { 1333 // There are more pending requests in queue. 1334 // Just post MCS_BOUND message to trigger processing 1335 // of next pending install. 1336 mHandler.sendEmptyMessage(MCS_BOUND); 1337 } 1338 1339 break; 1340 } 1341 case MCS_GIVE_UP: { 1342 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1343 HandlerParams params = mPendingInstalls.remove(0); 1344 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1345 System.identityHashCode(params)); 1346 break; 1347 } 1348 case SEND_PENDING_BROADCAST: { 1349 String packages[]; 1350 ArrayList<String> components[]; 1351 int size = 0; 1352 int uids[]; 1353 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1354 synchronized (mPackages) { 1355 if (mPendingBroadcasts == null) { 1356 return; 1357 } 1358 size = mPendingBroadcasts.size(); 1359 if (size <= 0) { 1360 // Nothing to be done. Just return 1361 return; 1362 } 1363 packages = new String[size]; 1364 components = new ArrayList[size]; 1365 uids = new int[size]; 1366 int i = 0; // filling out the above arrays 1367 1368 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1369 int packageUserId = mPendingBroadcasts.userIdAt(n); 1370 Iterator<Map.Entry<String, ArrayList<String>>> it 1371 = mPendingBroadcasts.packagesForUserId(packageUserId) 1372 .entrySet().iterator(); 1373 while (it.hasNext() && i < size) { 1374 Map.Entry<String, ArrayList<String>> ent = it.next(); 1375 packages[i] = ent.getKey(); 1376 components[i] = ent.getValue(); 1377 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1378 uids[i] = (ps != null) 1379 ? UserHandle.getUid(packageUserId, ps.appId) 1380 : -1; 1381 i++; 1382 } 1383 } 1384 size = i; 1385 mPendingBroadcasts.clear(); 1386 } 1387 // Send broadcasts 1388 for (int i = 0; i < size; i++) { 1389 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1390 } 1391 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1392 break; 1393 } 1394 case START_CLEANING_PACKAGE: { 1395 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1396 final String packageName = (String)msg.obj; 1397 final int userId = msg.arg1; 1398 final boolean andCode = msg.arg2 != 0; 1399 synchronized (mPackages) { 1400 if (userId == UserHandle.USER_ALL) { 1401 int[] users = sUserManager.getUserIds(); 1402 for (int user : users) { 1403 mSettings.addPackageToCleanLPw( 1404 new PackageCleanItem(user, packageName, andCode)); 1405 } 1406 } else { 1407 mSettings.addPackageToCleanLPw( 1408 new PackageCleanItem(userId, packageName, andCode)); 1409 } 1410 } 1411 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1412 startCleaningPackages(); 1413 } break; 1414 case POST_INSTALL: { 1415 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1416 1417 PostInstallData data = mRunningInstalls.get(msg.arg1); 1418 mRunningInstalls.delete(msg.arg1); 1419 1420 if (data != null) { 1421 InstallArgs args = data.args; 1422 PackageInstalledInfo parentRes = data.res; 1423 1424 final boolean grantPermissions = (args.installFlags 1425 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1426 final String[] grantedPermissions = args.installGrantPermissions; 1427 1428 // Handle the parent package 1429 handlePackagePostInstall(parentRes, grantPermissions, grantedPermissions, 1430 args.observer); 1431 1432 // Handle the child packages 1433 final int childCount = (parentRes.addedChildPackages != null) 1434 ? parentRes.addedChildPackages.size() : 0; 1435 for (int i = 0; i < childCount; i++) { 1436 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1437 handlePackagePostInstall(childRes, grantPermissions, grantedPermissions, 1438 args.observer); 1439 } 1440 1441 // Log tracing if needed 1442 if (args.traceMethod != null) { 1443 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1444 args.traceCookie); 1445 } 1446 } else { 1447 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1448 } 1449 1450 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1451 } break; 1452 case UPDATED_MEDIA_STATUS: { 1453 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1454 boolean reportStatus = msg.arg1 == 1; 1455 boolean doGc = msg.arg2 == 1; 1456 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1457 if (doGc) { 1458 // Force a gc to clear up stale containers. 1459 Runtime.getRuntime().gc(); 1460 } 1461 if (msg.obj != null) { 1462 @SuppressWarnings("unchecked") 1463 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1464 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1465 // Unload containers 1466 unloadAllContainers(args); 1467 } 1468 if (reportStatus) { 1469 try { 1470 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1471 PackageHelper.getMountService().finishMediaUpdate(); 1472 } catch (RemoteException e) { 1473 Log.e(TAG, "MountService not running?"); 1474 } 1475 } 1476 } break; 1477 case WRITE_SETTINGS: { 1478 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1479 synchronized (mPackages) { 1480 removeMessages(WRITE_SETTINGS); 1481 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1482 mSettings.writeLPr(); 1483 mDirtyUsers.clear(); 1484 } 1485 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1486 } break; 1487 case WRITE_PACKAGE_RESTRICTIONS: { 1488 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1489 synchronized (mPackages) { 1490 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1491 for (int userId : mDirtyUsers) { 1492 mSettings.writePackageRestrictionsLPr(userId); 1493 } 1494 mDirtyUsers.clear(); 1495 } 1496 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1497 } break; 1498 case CHECK_PENDING_VERIFICATION: { 1499 final int verificationId = msg.arg1; 1500 final PackageVerificationState state = mPendingVerification.get(verificationId); 1501 1502 if ((state != null) && !state.timeoutExtended()) { 1503 final InstallArgs args = state.getInstallArgs(); 1504 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1505 1506 Slog.i(TAG, "Verification timed out for " + originUri); 1507 mPendingVerification.remove(verificationId); 1508 1509 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1510 1511 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1512 Slog.i(TAG, "Continuing with installation of " + originUri); 1513 state.setVerifierResponse(Binder.getCallingUid(), 1514 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1515 broadcastPackageVerified(verificationId, originUri, 1516 PackageManager.VERIFICATION_ALLOW, 1517 state.getInstallArgs().getUser()); 1518 try { 1519 ret = args.copyApk(mContainerService, true); 1520 } catch (RemoteException e) { 1521 Slog.e(TAG, "Could not contact the ContainerService"); 1522 } 1523 } else { 1524 broadcastPackageVerified(verificationId, originUri, 1525 PackageManager.VERIFICATION_REJECT, 1526 state.getInstallArgs().getUser()); 1527 } 1528 1529 Trace.asyncTraceEnd( 1530 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1531 1532 processPendingInstall(args, ret); 1533 mHandler.sendEmptyMessage(MCS_UNBIND); 1534 } 1535 break; 1536 } 1537 case PACKAGE_VERIFIED: { 1538 final int verificationId = msg.arg1; 1539 1540 final PackageVerificationState state = mPendingVerification.get(verificationId); 1541 if (state == null) { 1542 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1543 break; 1544 } 1545 1546 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1547 1548 state.setVerifierResponse(response.callerUid, response.code); 1549 1550 if (state.isVerificationComplete()) { 1551 mPendingVerification.remove(verificationId); 1552 1553 final InstallArgs args = state.getInstallArgs(); 1554 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1555 1556 int ret; 1557 if (state.isInstallAllowed()) { 1558 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1559 broadcastPackageVerified(verificationId, originUri, 1560 response.code, state.getInstallArgs().getUser()); 1561 try { 1562 ret = args.copyApk(mContainerService, true); 1563 } catch (RemoteException e) { 1564 Slog.e(TAG, "Could not contact the ContainerService"); 1565 } 1566 } else { 1567 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1568 } 1569 1570 Trace.asyncTraceEnd( 1571 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1572 1573 processPendingInstall(args, ret); 1574 mHandler.sendEmptyMessage(MCS_UNBIND); 1575 } 1576 1577 break; 1578 } 1579 case START_INTENT_FILTER_VERIFICATIONS: { 1580 IFVerificationParams params = (IFVerificationParams) msg.obj; 1581 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1582 params.replacing, params.pkg); 1583 break; 1584 } 1585 case INTENT_FILTER_VERIFIED: { 1586 final int verificationId = msg.arg1; 1587 1588 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1589 verificationId); 1590 if (state == null) { 1591 Slog.w(TAG, "Invalid IntentFilter verification token " 1592 + verificationId + " received"); 1593 break; 1594 } 1595 1596 final int userId = state.getUserId(); 1597 1598 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1599 "Processing IntentFilter verification with token:" 1600 + verificationId + " and userId:" + userId); 1601 1602 final IntentFilterVerificationResponse response = 1603 (IntentFilterVerificationResponse) msg.obj; 1604 1605 state.setVerifierResponse(response.callerUid, response.code); 1606 1607 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1608 "IntentFilter verification with token:" + verificationId 1609 + " and userId:" + userId 1610 + " is settings verifier response with response code:" 1611 + response.code); 1612 1613 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1614 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1615 + response.getFailedDomainsString()); 1616 } 1617 1618 if (state.isVerificationComplete()) { 1619 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1620 } else { 1621 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1622 "IntentFilter verification with token:" + verificationId 1623 + " was not said to be complete"); 1624 } 1625 1626 break; 1627 } 1628 } 1629 } 1630 } 1631 1632 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1633 String[] grantedPermissions, IPackageInstallObserver2 installObserver) { 1634 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1635 // Send the removed broadcasts 1636 if (res.removedInfo != null) { 1637 res.removedInfo.sendPackageRemovedBroadcasts(); 1638 } 1639 1640 // Now that we successfully installed the package, grant runtime 1641 // permissions if requested before broadcasting the install. 1642 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1643 >= Build.VERSION_CODES.M) { 1644 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1645 } 1646 1647 final boolean update = res.removedInfo != null 1648 && res.removedInfo.removedPackage != null; 1649 1650 // If this is the first time we have child packages for a disabled privileged 1651 // app that had no children, we grant requested runtime permissions to the new 1652 // children if the parent on the system image had them already granted. 1653 if (res.pkg.parentPackage != null) { 1654 synchronized (mPackages) { 1655 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1656 } 1657 } 1658 1659 synchronized (mPackages) { 1660 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1661 } 1662 1663 final String packageName = res.pkg.applicationInfo.packageName; 1664 Bundle extras = new Bundle(1); 1665 extras.putInt(Intent.EXTRA_UID, res.uid); 1666 1667 // Determine the set of users who are adding this package for 1668 // the first time vs. those who are seeing an update. 1669 int[] firstUsers = EMPTY_INT_ARRAY; 1670 int[] updateUsers = EMPTY_INT_ARRAY; 1671 if (res.origUsers == null || res.origUsers.length == 0) { 1672 firstUsers = res.newUsers; 1673 } else { 1674 for (int newUser : res.newUsers) { 1675 boolean isNew = true; 1676 for (int origUser : res.origUsers) { 1677 if (origUser == newUser) { 1678 isNew = false; 1679 break; 1680 } 1681 } 1682 if (isNew) { 1683 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1684 } else { 1685 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1686 } 1687 } 1688 } 1689 1690 // Send installed broadcasts if the install/update is not ephemeral 1691 if (!isEphemeral(res.pkg)) { 1692 // Send added for users that see the package for the first time 1693 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1694 extras, 0 /*flags*/, null /*targetPackage*/, 1695 null /*finishedReceiver*/, firstUsers); 1696 1697 // Send added for users that don't see the package for the first time 1698 if (update) { 1699 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1700 } 1701 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1702 extras, 0 /*flags*/, null /*targetPackage*/, 1703 null /*finishedReceiver*/, updateUsers); 1704 1705 // Send replaced for users that don't see the package for the first time 1706 if (update) { 1707 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1708 packageName, extras, 0 /*flags*/, 1709 null /*targetPackage*/, null /*finishedReceiver*/, 1710 updateUsers); 1711 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1712 null /*package*/, null /*extras*/, 0 /*flags*/, 1713 packageName /*targetPackage*/, 1714 null /*finishedReceiver*/, updateUsers); 1715 } 1716 1717 // Send broadcast package appeared if forward locked/external for all users 1718 // treat asec-hosted packages like removable media on upgrade 1719 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1720 if (DEBUG_INSTALL) { 1721 Slog.i(TAG, "upgrading pkg " + res.pkg 1722 + " is ASEC-hosted -> AVAILABLE"); 1723 } 1724 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1725 ArrayList<String> pkgList = new ArrayList<>(1); 1726 pkgList.add(packageName); 1727 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1728 } 1729 } 1730 1731 // Work that needs to happen on first install within each user 1732 if (firstUsers != null && firstUsers.length > 0) { 1733 synchronized (mPackages) { 1734 for (int userId : firstUsers) { 1735 // If this app is a browser and it's newly-installed for some 1736 // users, clear any default-browser state in those users. The 1737 // app's nature doesn't depend on the user, so we can just check 1738 // its browser nature in any user and generalize. 1739 if (packageIsBrowser(packageName, userId)) { 1740 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1741 } 1742 1743 // We may also need to apply pending (restored) runtime 1744 // permission grants within these users. 1745 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1746 } 1747 } 1748 } 1749 1750 // Log current value of "unknown sources" setting 1751 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1752 getUnknownSourcesSettings()); 1753 1754 // Force a gc to clear up things 1755 Runtime.getRuntime().gc(); 1756 1757 // Remove the replaced package's older resources safely now 1758 // We delete after a gc for applications on sdcard. 1759 if (res.removedInfo != null && res.removedInfo.args != null) { 1760 synchronized (mInstallLock) { 1761 res.removedInfo.args.doPostDeleteLI(true); 1762 } 1763 } 1764 } 1765 1766 // If someone is watching installs - notify them 1767 if (installObserver != null) { 1768 try { 1769 Bundle extras = extrasForInstallResult(res); 1770 installObserver.onPackageInstalled(res.name, res.returnCode, 1771 res.returnMsg, extras); 1772 } catch (RemoteException e) { 1773 Slog.i(TAG, "Observer no longer exists."); 1774 } 1775 } 1776 } 1777 1778 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1779 PackageParser.Package pkg) { 1780 if (pkg.parentPackage == null) { 1781 return; 1782 } 1783 if (pkg.requestedPermissions == null) { 1784 return; 1785 } 1786 final PackageSetting disabledSysParentPs = mSettings 1787 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1788 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1789 || !disabledSysParentPs.isPrivileged() 1790 || (disabledSysParentPs.childPackageNames != null 1791 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1792 return; 1793 } 1794 final int[] allUserIds = sUserManager.getUserIds(); 1795 final int permCount = pkg.requestedPermissions.size(); 1796 for (int i = 0; i < permCount; i++) { 1797 String permission = pkg.requestedPermissions.get(i); 1798 BasePermission bp = mSettings.mPermissions.get(permission); 1799 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1800 continue; 1801 } 1802 for (int userId : allUserIds) { 1803 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1804 permission, userId)) { 1805 grantRuntimePermission(pkg.packageName, permission, userId); 1806 } 1807 } 1808 } 1809 } 1810 1811 private StorageEventListener mStorageListener = new StorageEventListener() { 1812 @Override 1813 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1814 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1815 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1816 final String volumeUuid = vol.getFsUuid(); 1817 1818 // Clean up any users or apps that were removed or recreated 1819 // while this volume was missing 1820 reconcileUsers(volumeUuid); 1821 reconcileApps(volumeUuid); 1822 1823 // Clean up any install sessions that expired or were 1824 // cancelled while this volume was missing 1825 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1826 1827 loadPrivatePackages(vol); 1828 1829 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1830 unloadPrivatePackages(vol); 1831 } 1832 } 1833 1834 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1835 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1836 updateExternalMediaStatus(true, false); 1837 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1838 updateExternalMediaStatus(false, false); 1839 } 1840 } 1841 } 1842 1843 @Override 1844 public void onVolumeForgotten(String fsUuid) { 1845 if (TextUtils.isEmpty(fsUuid)) { 1846 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1847 return; 1848 } 1849 1850 // Remove any apps installed on the forgotten volume 1851 synchronized (mPackages) { 1852 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1853 for (PackageSetting ps : packages) { 1854 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1855 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1856 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1857 } 1858 1859 mSettings.onVolumeForgotten(fsUuid); 1860 mSettings.writeLPr(); 1861 } 1862 } 1863 }; 1864 1865 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1866 String[] grantedPermissions) { 1867 for (int userId : userIds) { 1868 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1869 } 1870 1871 // We could have touched GID membership, so flush out packages.list 1872 synchronized (mPackages) { 1873 mSettings.writePackageListLPr(); 1874 } 1875 } 1876 1877 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1878 String[] grantedPermissions) { 1879 SettingBase sb = (SettingBase) pkg.mExtras; 1880 if (sb == null) { 1881 return; 1882 } 1883 1884 PermissionsState permissionsState = sb.getPermissionsState(); 1885 1886 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1887 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1888 1889 synchronized (mPackages) { 1890 for (String permission : pkg.requestedPermissions) { 1891 BasePermission bp = mSettings.mPermissions.get(permission); 1892 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1893 && (grantedPermissions == null 1894 || ArrayUtils.contains(grantedPermissions, permission))) { 1895 final int flags = permissionsState.getPermissionFlags(permission, userId); 1896 // Installer cannot change immutable permissions. 1897 if ((flags & immutableFlags) == 0) { 1898 grantRuntimePermission(pkg.packageName, permission, userId); 1899 } 1900 } 1901 } 1902 } 1903 } 1904 1905 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1906 Bundle extras = null; 1907 switch (res.returnCode) { 1908 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1909 extras = new Bundle(); 1910 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1911 res.origPermission); 1912 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1913 res.origPackage); 1914 break; 1915 } 1916 case PackageManager.INSTALL_SUCCEEDED: { 1917 extras = new Bundle(); 1918 extras.putBoolean(Intent.EXTRA_REPLACING, 1919 res.removedInfo != null && res.removedInfo.removedPackage != null); 1920 break; 1921 } 1922 } 1923 return extras; 1924 } 1925 1926 void scheduleWriteSettingsLocked() { 1927 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1928 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1929 } 1930 } 1931 1932 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1933 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1934 scheduleWritePackageRestrictionsLocked(userId); 1935 } 1936 1937 void scheduleWritePackageRestrictionsLocked(int userId) { 1938 final int[] userIds = (userId == UserHandle.USER_ALL) 1939 ? sUserManager.getUserIds() : new int[]{userId}; 1940 for (int nextUserId : userIds) { 1941 if (!sUserManager.exists(nextUserId)) return; 1942 mDirtyUsers.add(nextUserId); 1943 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1944 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1945 } 1946 } 1947 } 1948 1949 public static PackageManagerService main(Context context, Installer installer, 1950 boolean factoryTest, boolean onlyCore) { 1951 PackageManagerService m = new PackageManagerService(context, installer, 1952 factoryTest, onlyCore); 1953 m.enableSystemUserPackages(); 1954 ServiceManager.addService("package", m); 1955 return m; 1956 } 1957 1958 private void enableSystemUserPackages() { 1959 if (!UserManager.isSplitSystemUser()) { 1960 return; 1961 } 1962 // For system user, enable apps based on the following conditions: 1963 // - app is whitelisted or belong to one of these groups: 1964 // -- system app which has no launcher icons 1965 // -- system app which has INTERACT_ACROSS_USERS permission 1966 // -- system IME app 1967 // - app is not in the blacklist 1968 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1969 Set<String> enableApps = new ArraySet<>(); 1970 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1971 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1972 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1973 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1974 enableApps.addAll(wlApps); 1975 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1976 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1977 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1978 enableApps.removeAll(blApps); 1979 Log.i(TAG, "Applications installed for system user: " + enableApps); 1980 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1981 UserHandle.SYSTEM); 1982 final int allAppsSize = allAps.size(); 1983 synchronized (mPackages) { 1984 for (int i = 0; i < allAppsSize; i++) { 1985 String pName = allAps.get(i); 1986 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1987 // Should not happen, but we shouldn't be failing if it does 1988 if (pkgSetting == null) { 1989 continue; 1990 } 1991 boolean install = enableApps.contains(pName); 1992 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 1993 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 1994 + " for system user"); 1995 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 1996 } 1997 } 1998 } 1999 } 2000 2001 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2002 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2003 Context.DISPLAY_SERVICE); 2004 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2005 } 2006 2007 public PackageManagerService(Context context, Installer installer, 2008 boolean factoryTest, boolean onlyCore) { 2009 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2010 SystemClock.uptimeMillis()); 2011 2012 if (mSdkVersion <= 0) { 2013 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2014 } 2015 2016 mContext = context; 2017 mFactoryTest = factoryTest; 2018 mOnlyCore = onlyCore; 2019 mMetrics = new DisplayMetrics(); 2020 mSettings = new Settings(mPackages); 2021 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2022 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2023 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2024 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2025 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2026 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2027 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2028 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2029 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2030 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2031 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2032 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2033 2034 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2035 if (separateProcesses != null && separateProcesses.length() > 0) { 2036 if ("*".equals(separateProcesses)) { 2037 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2038 mSeparateProcesses = null; 2039 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2040 } else { 2041 mDefParseFlags = 0; 2042 mSeparateProcesses = separateProcesses.split(","); 2043 Slog.w(TAG, "Running with debug.separate_processes: " 2044 + separateProcesses); 2045 } 2046 } else { 2047 mDefParseFlags = 0; 2048 mSeparateProcesses = null; 2049 } 2050 2051 mInstaller = installer; 2052 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2053 "*dexopt*"); 2054 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2055 2056 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2057 FgThread.get().getLooper()); 2058 2059 getDefaultDisplayMetrics(context, mMetrics); 2060 2061 SystemConfig systemConfig = SystemConfig.getInstance(); 2062 mGlobalGids = systemConfig.getGlobalGids(); 2063 mSystemPermissions = systemConfig.getSystemPermissions(); 2064 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2065 2066 synchronized (mInstallLock) { 2067 // writer 2068 synchronized (mPackages) { 2069 mHandlerThread = new ServiceThread(TAG, 2070 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2071 mHandlerThread.start(); 2072 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2073 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2074 2075 File dataDir = Environment.getDataDirectory(); 2076 mAppInstallDir = new File(dataDir, "app"); 2077 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2078 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2079 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2080 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2081 2082 sUserManager = new UserManagerService(context, this, mPackages); 2083 2084 // Propagate permission configuration in to package manager. 2085 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2086 = systemConfig.getPermissions(); 2087 for (int i=0; i<permConfig.size(); i++) { 2088 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2089 BasePermission bp = mSettings.mPermissions.get(perm.name); 2090 if (bp == null) { 2091 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2092 mSettings.mPermissions.put(perm.name, bp); 2093 } 2094 if (perm.gids != null) { 2095 bp.setGids(perm.gids, perm.perUser); 2096 } 2097 } 2098 2099 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2100 for (int i=0; i<libConfig.size(); i++) { 2101 mSharedLibraries.put(libConfig.keyAt(i), 2102 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2103 } 2104 2105 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2106 2107 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2108 2109 String customResolverActivity = Resources.getSystem().getString( 2110 R.string.config_customResolverActivity); 2111 if (TextUtils.isEmpty(customResolverActivity)) { 2112 customResolverActivity = null; 2113 } else { 2114 mCustomResolverComponentName = ComponentName.unflattenFromString( 2115 customResolverActivity); 2116 } 2117 2118 long startTime = SystemClock.uptimeMillis(); 2119 2120 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2121 startTime); 2122 2123 // Set flag to monitor and not change apk file paths when 2124 // scanning install directories. 2125 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2126 2127 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2128 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2129 2130 if (bootClassPath == null) { 2131 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2132 } 2133 2134 if (systemServerClassPath == null) { 2135 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2136 } 2137 2138 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2139 final String[] dexCodeInstructionSets = 2140 getDexCodeInstructionSets( 2141 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2142 2143 /** 2144 * Ensure all external libraries have had dexopt run on them. 2145 */ 2146 if (mSharedLibraries.size() > 0) { 2147 // NOTE: For now, we're compiling these system "shared libraries" 2148 // (and framework jars) into all available architectures. It's possible 2149 // to compile them only when we come across an app that uses them (there's 2150 // already logic for that in scanPackageLI) but that adds some complexity. 2151 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2152 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2153 final String lib = libEntry.path; 2154 if (lib == null) { 2155 continue; 2156 } 2157 2158 try { 2159 // Shared libraries do not have profiles so we perform a full 2160 // AOT compilation (if needed). 2161 int dexoptNeeded = DexFile.getDexOptNeeded( 2162 lib, dexCodeInstructionSet, 2163 DexFile.COMPILATION_TYPE_FULL); 2164 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2165 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2166 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2167 StorageManager.UUID_PRIVATE_INTERNAL, 2168 false /*useProfiles*/); 2169 } 2170 } catch (FileNotFoundException e) { 2171 Slog.w(TAG, "Library not found: " + lib); 2172 } catch (IOException | InstallerException e) { 2173 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2174 + e.getMessage()); 2175 } 2176 } 2177 } 2178 } 2179 2180 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2181 2182 final VersionInfo ver = mSettings.getInternalVersion(); 2183 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2184 // when upgrading from pre-M, promote system app permissions from install to runtime 2185 mPromoteSystemApps = 2186 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2187 2188 // save off the names of pre-existing system packages prior to scanning; we don't 2189 // want to automatically grant runtime permissions for new system apps 2190 if (mPromoteSystemApps) { 2191 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2192 while (pkgSettingIter.hasNext()) { 2193 PackageSetting ps = pkgSettingIter.next(); 2194 if (isSystemApp(ps)) { 2195 mExistingSystemPackages.add(ps.name); 2196 } 2197 } 2198 } 2199 2200 // Collect vendor overlay packages. 2201 // (Do this before scanning any apps.) 2202 // For security and version matching reason, only consider 2203 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2204 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2205 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2206 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2207 2208 // Find base frameworks (resource packages without code). 2209 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2210 | PackageParser.PARSE_IS_SYSTEM_DIR 2211 | PackageParser.PARSE_IS_PRIVILEGED, 2212 scanFlags | SCAN_NO_DEX, 0); 2213 2214 // Collected privileged system packages. 2215 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2216 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2217 | PackageParser.PARSE_IS_SYSTEM_DIR 2218 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2219 2220 // Collect ordinary system packages. 2221 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2222 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2223 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2224 2225 // Collect all vendor packages. 2226 File vendorAppDir = new File("/vendor/app"); 2227 try { 2228 vendorAppDir = vendorAppDir.getCanonicalFile(); 2229 } catch (IOException e) { 2230 // failed to look up canonical path, continue with original one 2231 } 2232 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2233 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2234 2235 // Collect all OEM packages. 2236 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2237 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2238 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2239 2240 // Prune any system packages that no longer exist. 2241 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2242 if (!mOnlyCore) { 2243 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2244 while (psit.hasNext()) { 2245 PackageSetting ps = psit.next(); 2246 2247 /* 2248 * If this is not a system app, it can't be a 2249 * disable system app. 2250 */ 2251 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2252 continue; 2253 } 2254 2255 /* 2256 * If the package is scanned, it's not erased. 2257 */ 2258 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2259 if (scannedPkg != null) { 2260 /* 2261 * If the system app is both scanned and in the 2262 * disabled packages list, then it must have been 2263 * added via OTA. Remove it from the currently 2264 * scanned package so the previously user-installed 2265 * application can be scanned. 2266 */ 2267 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2268 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2269 + ps.name + "; removing system app. Last known codePath=" 2270 + ps.codePathString + ", installStatus=" + ps.installStatus 2271 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2272 + scannedPkg.mVersionCode); 2273 removePackageLI(scannedPkg, true); 2274 mExpectingBetter.put(ps.name, ps.codePath); 2275 } 2276 2277 continue; 2278 } 2279 2280 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2281 psit.remove(); 2282 logCriticalInfo(Log.WARN, "System package " + ps.name 2283 + " no longer exists; wiping its data"); 2284 removeDataDirsLI(null, ps.name); 2285 } else { 2286 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2287 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2288 possiblyDeletedUpdatedSystemApps.add(ps.name); 2289 } 2290 } 2291 } 2292 } 2293 2294 //look for any incomplete package installations 2295 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2296 //clean up list 2297 for(int i = 0; i < deletePkgsList.size(); i++) { 2298 //clean up here 2299 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2300 } 2301 //delete tmp files 2302 deleteTempPackageFiles(); 2303 2304 // Remove any shared userIDs that have no associated packages 2305 mSettings.pruneSharedUsersLPw(); 2306 2307 if (!mOnlyCore) { 2308 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2309 SystemClock.uptimeMillis()); 2310 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2311 2312 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2313 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2314 2315 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2316 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2317 2318 /** 2319 * Remove disable package settings for any updated system 2320 * apps that were removed via an OTA. If they're not a 2321 * previously-updated app, remove them completely. 2322 * Otherwise, just revoke their system-level permissions. 2323 */ 2324 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2325 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2326 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2327 2328 String msg; 2329 if (deletedPkg == null) { 2330 msg = "Updated system package " + deletedAppName 2331 + " no longer exists; wiping its data"; 2332 removeDataDirsLI(null, deletedAppName); 2333 } else { 2334 msg = "Updated system app + " + deletedAppName 2335 + " no longer present; removing system privileges for " 2336 + deletedAppName; 2337 2338 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2339 2340 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2341 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2342 } 2343 logCriticalInfo(Log.WARN, msg); 2344 } 2345 2346 /** 2347 * Make sure all system apps that we expected to appear on 2348 * the userdata partition actually showed up. If they never 2349 * appeared, crawl back and revive the system version. 2350 */ 2351 for (int i = 0; i < mExpectingBetter.size(); i++) { 2352 final String packageName = mExpectingBetter.keyAt(i); 2353 if (!mPackages.containsKey(packageName)) { 2354 final File scanFile = mExpectingBetter.valueAt(i); 2355 2356 logCriticalInfo(Log.WARN, "Expected better " + packageName 2357 + " but never showed up; reverting to system"); 2358 2359 final int reparseFlags; 2360 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2361 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2362 | PackageParser.PARSE_IS_SYSTEM_DIR 2363 | PackageParser.PARSE_IS_PRIVILEGED; 2364 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2365 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2366 | PackageParser.PARSE_IS_SYSTEM_DIR; 2367 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2368 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2369 | PackageParser.PARSE_IS_SYSTEM_DIR; 2370 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2371 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2372 | PackageParser.PARSE_IS_SYSTEM_DIR; 2373 } else { 2374 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2375 continue; 2376 } 2377 2378 mSettings.enableSystemPackageLPw(packageName); 2379 2380 try { 2381 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2382 } catch (PackageManagerException e) { 2383 Slog.e(TAG, "Failed to parse original system package: " 2384 + e.getMessage()); 2385 } 2386 } 2387 } 2388 } 2389 mExpectingBetter.clear(); 2390 2391 // Now that we know all of the shared libraries, update all clients to have 2392 // the correct library paths. 2393 updateAllSharedLibrariesLPw(); 2394 2395 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2396 // NOTE: We ignore potential failures here during a system scan (like 2397 // the rest of the commands above) because there's precious little we 2398 // can do about it. A settings error is reported, though. 2399 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2400 false /* boot complete */); 2401 } 2402 2403 // Now that we know all the packages we are keeping, 2404 // read and update their last usage times. 2405 mPackageUsage.readLP(); 2406 2407 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2408 SystemClock.uptimeMillis()); 2409 Slog.i(TAG, "Time to scan packages: " 2410 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2411 + " seconds"); 2412 2413 // If the platform SDK has changed since the last time we booted, 2414 // we need to re-grant app permission to catch any new ones that 2415 // appear. This is really a hack, and means that apps can in some 2416 // cases get permissions that the user didn't initially explicitly 2417 // allow... it would be nice to have some better way to handle 2418 // this situation. 2419 int updateFlags = UPDATE_PERMISSIONS_ALL; 2420 if (ver.sdkVersion != mSdkVersion) { 2421 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2422 + mSdkVersion + "; regranting permissions for internal storage"); 2423 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2424 } 2425 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2426 ver.sdkVersion = mSdkVersion; 2427 2428 // If this is the first boot or an update from pre-M, and it is a normal 2429 // boot, then we need to initialize the default preferred apps across 2430 // all defined users. 2431 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2432 for (UserInfo user : sUserManager.getUsers(true)) { 2433 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2434 applyFactoryDefaultBrowserLPw(user.id); 2435 primeDomainVerificationsLPw(user.id); 2436 } 2437 } 2438 2439 // Prepare storage for system user really early during boot, 2440 // since core system apps like SettingsProvider and SystemUI 2441 // can't wait for user to start 2442 final int storageFlags; 2443 if (StorageManager.isFileBasedEncryptionEnabled()) { 2444 storageFlags = StorageManager.FLAG_STORAGE_DE; 2445 } else { 2446 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2447 } 2448 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2449 storageFlags); 2450 2451 // If this is first boot after an OTA, and a normal boot, then 2452 // we need to clear code cache directories. 2453 if (mIsUpgrade && !onlyCore) { 2454 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2455 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2456 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2457 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2458 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2459 } 2460 } 2461 ver.fingerprint = Build.FINGERPRINT; 2462 } 2463 2464 checkDefaultBrowser(); 2465 2466 // clear only after permissions and other defaults have been updated 2467 mExistingSystemPackages.clear(); 2468 mPromoteSystemApps = false; 2469 2470 // All the changes are done during package scanning. 2471 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2472 2473 // can downgrade to reader 2474 mSettings.writeLPr(); 2475 2476 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2477 SystemClock.uptimeMillis()); 2478 2479 if (!mOnlyCore) { 2480 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2481 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2482 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2483 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2484 mIntentFilterVerifierComponent); 2485 } else { 2486 mRequiredVerifierPackage = null; 2487 mRequiredInstallerPackage = null; 2488 mIntentFilterVerifierComponent = null; 2489 mIntentFilterVerifier = null; 2490 } 2491 2492 mInstallerService = new PackageInstallerService(context, this); 2493 2494 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2495 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2496 // both the installer and resolver must be present to enable ephemeral 2497 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2498 if (DEBUG_EPHEMERAL) { 2499 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2500 + " installer:" + ephemeralInstallerComponent); 2501 } 2502 mEphemeralResolverComponent = ephemeralResolverComponent; 2503 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2504 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2505 mEphemeralResolverConnection = 2506 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2507 } else { 2508 if (DEBUG_EPHEMERAL) { 2509 final String missingComponent = 2510 (ephemeralResolverComponent == null) 2511 ? (ephemeralInstallerComponent == null) 2512 ? "resolver and installer" 2513 : "resolver" 2514 : "installer"; 2515 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2516 } 2517 mEphemeralResolverComponent = null; 2518 mEphemeralInstallerComponent = null; 2519 mEphemeralResolverConnection = null; 2520 } 2521 2522 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2523 } // synchronized (mPackages) 2524 } // synchronized (mInstallLock) 2525 2526 // Now after opening every single application zip, make sure they 2527 // are all flushed. Not really needed, but keeps things nice and 2528 // tidy. 2529 Runtime.getRuntime().gc(); 2530 2531 // The initial scanning above does many calls into installd while 2532 // holding the mPackages lock, but we're mostly interested in yelling 2533 // once we have a booted system. 2534 mInstaller.setWarnIfHeld(mPackages); 2535 2536 // Expose private service for system components to use. 2537 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2538 } 2539 2540 @Override 2541 public boolean isFirstBoot() { 2542 return !mRestoredSettings; 2543 } 2544 2545 @Override 2546 public boolean isOnlyCoreApps() { 2547 return mOnlyCore; 2548 } 2549 2550 @Override 2551 public boolean isUpgrade() { 2552 return mIsUpgrade; 2553 } 2554 2555 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2556 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2557 2558 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2559 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2560 if (matches.size() == 1) { 2561 return matches.get(0).getComponentInfo().packageName; 2562 } else { 2563 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2564 return null; 2565 } 2566 } 2567 2568 private @NonNull String getRequiredInstallerLPr() { 2569 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2570 intent.addCategory(Intent.CATEGORY_DEFAULT); 2571 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2572 2573 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2574 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2575 if (matches.size() == 1) { 2576 return matches.get(0).getComponentInfo().packageName; 2577 } else { 2578 throw new RuntimeException("There must be exactly one installer; found " + matches); 2579 } 2580 } 2581 2582 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2583 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2584 2585 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2586 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2587 ResolveInfo best = null; 2588 final int N = matches.size(); 2589 for (int i = 0; i < N; i++) { 2590 final ResolveInfo cur = matches.get(i); 2591 final String packageName = cur.getComponentInfo().packageName; 2592 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2593 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2594 continue; 2595 } 2596 2597 if (best == null || cur.priority > best.priority) { 2598 best = cur; 2599 } 2600 } 2601 2602 if (best != null) { 2603 return best.getComponentInfo().getComponentName(); 2604 } else { 2605 throw new RuntimeException("There must be at least one intent filter verifier"); 2606 } 2607 } 2608 2609 private @Nullable ComponentName getEphemeralResolverLPr() { 2610 final String[] packageArray = 2611 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2612 if (packageArray.length == 0) { 2613 if (DEBUG_EPHEMERAL) { 2614 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2615 } 2616 return null; 2617 } 2618 2619 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2620 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null, 2621 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2622 2623 final int N = resolvers.size(); 2624 if (N == 0) { 2625 if (DEBUG_EPHEMERAL) { 2626 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2627 } 2628 return null; 2629 } 2630 2631 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2632 for (int i = 0; i < N; i++) { 2633 final ResolveInfo info = resolvers.get(i); 2634 2635 if (info.serviceInfo == null) { 2636 continue; 2637 } 2638 2639 final String packageName = info.serviceInfo.packageName; 2640 if (!possiblePackages.contains(packageName)) { 2641 if (DEBUG_EPHEMERAL) { 2642 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2643 + " pkg: " + packageName + ", info:" + info); 2644 } 2645 continue; 2646 } 2647 2648 if (DEBUG_EPHEMERAL) { 2649 Slog.v(TAG, "Ephemeral resolver found;" 2650 + " pkg: " + packageName + ", info:" + info); 2651 } 2652 return new ComponentName(packageName, info.serviceInfo.name); 2653 } 2654 if (DEBUG_EPHEMERAL) { 2655 Slog.v(TAG, "Ephemeral resolver NOT found"); 2656 } 2657 return null; 2658 } 2659 2660 private @Nullable ComponentName getEphemeralInstallerLPr() { 2661 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2662 intent.addCategory(Intent.CATEGORY_DEFAULT); 2663 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2664 2665 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2666 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2667 if (matches.size() == 0) { 2668 return null; 2669 } else if (matches.size() == 1) { 2670 return matches.get(0).getComponentInfo().getComponentName(); 2671 } else { 2672 throw new RuntimeException( 2673 "There must be at most one ephemeral installer; found " + matches); 2674 } 2675 } 2676 2677 private void primeDomainVerificationsLPw(int userId) { 2678 if (DEBUG_DOMAIN_VERIFICATION) { 2679 Slog.d(TAG, "Priming domain verifications in user " + userId); 2680 } 2681 2682 SystemConfig systemConfig = SystemConfig.getInstance(); 2683 ArraySet<String> packages = systemConfig.getLinkedApps(); 2684 ArraySet<String> domains = new ArraySet<String>(); 2685 2686 for (String packageName : packages) { 2687 PackageParser.Package pkg = mPackages.get(packageName); 2688 if (pkg != null) { 2689 if (!pkg.isSystemApp()) { 2690 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2691 continue; 2692 } 2693 2694 domains.clear(); 2695 for (PackageParser.Activity a : pkg.activities) { 2696 for (ActivityIntentInfo filter : a.intents) { 2697 if (hasValidDomains(filter)) { 2698 domains.addAll(filter.getHostsList()); 2699 } 2700 } 2701 } 2702 2703 if (domains.size() > 0) { 2704 if (DEBUG_DOMAIN_VERIFICATION) { 2705 Slog.v(TAG, " + " + packageName); 2706 } 2707 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2708 // state w.r.t. the formal app-linkage "no verification attempted" state; 2709 // and then 'always' in the per-user state actually used for intent resolution. 2710 final IntentFilterVerificationInfo ivi; 2711 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2712 new ArrayList<String>(domains)); 2713 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2714 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2715 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2716 } else { 2717 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2718 + "' does not handle web links"); 2719 } 2720 } else { 2721 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2722 } 2723 } 2724 2725 scheduleWritePackageRestrictionsLocked(userId); 2726 scheduleWriteSettingsLocked(); 2727 } 2728 2729 private void applyFactoryDefaultBrowserLPw(int userId) { 2730 // The default browser app's package name is stored in a string resource, 2731 // with a product-specific overlay used for vendor customization. 2732 String browserPkg = mContext.getResources().getString( 2733 com.android.internal.R.string.default_browser); 2734 if (!TextUtils.isEmpty(browserPkg)) { 2735 // non-empty string => required to be a known package 2736 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2737 if (ps == null) { 2738 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2739 browserPkg = null; 2740 } else { 2741 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2742 } 2743 } 2744 2745 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2746 // default. If there's more than one, just leave everything alone. 2747 if (browserPkg == null) { 2748 calculateDefaultBrowserLPw(userId); 2749 } 2750 } 2751 2752 private void calculateDefaultBrowserLPw(int userId) { 2753 List<String> allBrowsers = resolveAllBrowserApps(userId); 2754 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2755 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2756 } 2757 2758 private List<String> resolveAllBrowserApps(int userId) { 2759 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2760 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2761 PackageManager.MATCH_ALL, userId); 2762 2763 final int count = list.size(); 2764 List<String> result = new ArrayList<String>(count); 2765 for (int i=0; i<count; i++) { 2766 ResolveInfo info = list.get(i); 2767 if (info.activityInfo == null 2768 || !info.handleAllWebDataURI 2769 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2770 || result.contains(info.activityInfo.packageName)) { 2771 continue; 2772 } 2773 result.add(info.activityInfo.packageName); 2774 } 2775 2776 return result; 2777 } 2778 2779 private boolean packageIsBrowser(String packageName, int userId) { 2780 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2781 PackageManager.MATCH_ALL, userId); 2782 final int N = list.size(); 2783 for (int i = 0; i < N; i++) { 2784 ResolveInfo info = list.get(i); 2785 if (packageName.equals(info.activityInfo.packageName)) { 2786 return true; 2787 } 2788 } 2789 return false; 2790 } 2791 2792 private void checkDefaultBrowser() { 2793 final int myUserId = UserHandle.myUserId(); 2794 final String packageName = getDefaultBrowserPackageName(myUserId); 2795 if (packageName != null) { 2796 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2797 if (info == null) { 2798 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2799 synchronized (mPackages) { 2800 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2801 } 2802 } 2803 } 2804 } 2805 2806 @Override 2807 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2808 throws RemoteException { 2809 try { 2810 return super.onTransact(code, data, reply, flags); 2811 } catch (RuntimeException e) { 2812 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2813 Slog.wtf(TAG, "Package Manager Crash", e); 2814 } 2815 throw e; 2816 } 2817 } 2818 2819 void cleanupInstallFailedPackage(PackageSetting ps) { 2820 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2821 2822 removeDataDirsLI(ps.volumeUuid, ps.name); 2823 if (ps.codePath != null) { 2824 removeCodePathLI(ps.codePath); 2825 } 2826 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2827 if (ps.resourcePath.isDirectory()) { 2828 FileUtils.deleteContents(ps.resourcePath); 2829 } 2830 ps.resourcePath.delete(); 2831 } 2832 mSettings.removePackageLPw(ps.name); 2833 } 2834 2835 static int[] appendInts(int[] cur, int[] add) { 2836 if (add == null) return cur; 2837 if (cur == null) return add; 2838 final int N = add.length; 2839 for (int i=0; i<N; i++) { 2840 cur = appendInt(cur, add[i]); 2841 } 2842 return cur; 2843 } 2844 2845 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2846 if (!sUserManager.exists(userId)) return null; 2847 final PackageSetting ps = (PackageSetting) p.mExtras; 2848 if (ps == null) { 2849 return null; 2850 } 2851 2852 final PermissionsState permissionsState = ps.getPermissionsState(); 2853 2854 final int[] gids = permissionsState.computeGids(userId); 2855 final Set<String> permissions = permissionsState.getPermissions(userId); 2856 final PackageUserState state = ps.readUserState(userId); 2857 2858 return PackageParser.generatePackageInfo(p, gids, flags, 2859 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2860 } 2861 2862 @Override 2863 public void checkPackageStartable(String packageName, int userId) { 2864 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2865 2866 synchronized (mPackages) { 2867 final PackageSetting ps = mSettings.mPackages.get(packageName); 2868 if (ps == null) { 2869 throw new SecurityException("Package " + packageName + " was not found!"); 2870 } 2871 2872 if (mSafeMode && !ps.isSystem()) { 2873 throw new SecurityException("Package " + packageName + " not a system app!"); 2874 } 2875 2876 if (ps.frozen) { 2877 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2878 } 2879 2880 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2881 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2882 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2883 } 2884 } 2885 } 2886 2887 @Override 2888 public boolean isPackageAvailable(String packageName, int userId) { 2889 if (!sUserManager.exists(userId)) return false; 2890 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2891 false /* requireFullPermission */, false /* checkShell */, "is package available"); 2892 synchronized (mPackages) { 2893 PackageParser.Package p = mPackages.get(packageName); 2894 if (p != null) { 2895 final PackageSetting ps = (PackageSetting) p.mExtras; 2896 if (ps != null) { 2897 final PackageUserState state = ps.readUserState(userId); 2898 if (state != null) { 2899 return PackageParser.isAvailable(state); 2900 } 2901 } 2902 } 2903 } 2904 return false; 2905 } 2906 2907 @Override 2908 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2909 if (!sUserManager.exists(userId)) return null; 2910 flags = updateFlagsForPackage(flags, userId, packageName); 2911 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2912 false /* requireFullPermission */, false /* checkShell */, "get package info"); 2913 // reader 2914 synchronized (mPackages) { 2915 PackageParser.Package p = mPackages.get(packageName); 2916 if (DEBUG_PACKAGE_INFO) 2917 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2918 if (p != null) { 2919 return generatePackageInfo(p, flags, userId); 2920 } 2921 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2922 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2923 } 2924 } 2925 return null; 2926 } 2927 2928 @Override 2929 public String[] currentToCanonicalPackageNames(String[] names) { 2930 String[] out = new String[names.length]; 2931 // reader 2932 synchronized (mPackages) { 2933 for (int i=names.length-1; i>=0; i--) { 2934 PackageSetting ps = mSettings.mPackages.get(names[i]); 2935 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2936 } 2937 } 2938 return out; 2939 } 2940 2941 @Override 2942 public String[] canonicalToCurrentPackageNames(String[] names) { 2943 String[] out = new String[names.length]; 2944 // reader 2945 synchronized (mPackages) { 2946 for (int i=names.length-1; i>=0; i--) { 2947 String cur = mSettings.mRenamedPackages.get(names[i]); 2948 out[i] = cur != null ? cur : names[i]; 2949 } 2950 } 2951 return out; 2952 } 2953 2954 @Override 2955 public int getPackageUid(String packageName, int flags, int userId) { 2956 if (!sUserManager.exists(userId)) return -1; 2957 flags = updateFlagsForPackage(flags, userId, packageName); 2958 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2959 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 2960 2961 // reader 2962 synchronized (mPackages) { 2963 final PackageParser.Package p = mPackages.get(packageName); 2964 if (p != null && p.isMatch(flags)) { 2965 return UserHandle.getUid(userId, p.applicationInfo.uid); 2966 } 2967 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2968 final PackageSetting ps = mSettings.mPackages.get(packageName); 2969 if (ps != null && ps.isMatch(flags)) { 2970 return UserHandle.getUid(userId, ps.appId); 2971 } 2972 } 2973 } 2974 2975 return -1; 2976 } 2977 2978 @Override 2979 public int[] getPackageGids(String packageName, int flags, int userId) { 2980 if (!sUserManager.exists(userId)) return null; 2981 flags = updateFlagsForPackage(flags, userId, packageName); 2982 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2983 false /* requireFullPermission */, false /* checkShell */, 2984 "getPackageGids"); 2985 2986 // reader 2987 synchronized (mPackages) { 2988 final PackageParser.Package p = mPackages.get(packageName); 2989 if (p != null && p.isMatch(flags)) { 2990 PackageSetting ps = (PackageSetting) p.mExtras; 2991 return ps.getPermissionsState().computeGids(userId); 2992 } 2993 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2994 final PackageSetting ps = mSettings.mPackages.get(packageName); 2995 if (ps != null && ps.isMatch(flags)) { 2996 return ps.getPermissionsState().computeGids(userId); 2997 } 2998 } 2999 } 3000 3001 return null; 3002 } 3003 3004 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3005 if (bp.perm != null) { 3006 return PackageParser.generatePermissionInfo(bp.perm, flags); 3007 } 3008 PermissionInfo pi = new PermissionInfo(); 3009 pi.name = bp.name; 3010 pi.packageName = bp.sourcePackage; 3011 pi.nonLocalizedLabel = bp.name; 3012 pi.protectionLevel = bp.protectionLevel; 3013 return pi; 3014 } 3015 3016 @Override 3017 public PermissionInfo getPermissionInfo(String name, int flags) { 3018 // reader 3019 synchronized (mPackages) { 3020 final BasePermission p = mSettings.mPermissions.get(name); 3021 if (p != null) { 3022 return generatePermissionInfo(p, flags); 3023 } 3024 return null; 3025 } 3026 } 3027 3028 @Override 3029 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 3030 // reader 3031 synchronized (mPackages) { 3032 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3033 for (BasePermission p : mSettings.mPermissions.values()) { 3034 if (group == null) { 3035 if (p.perm == null || p.perm.info.group == null) { 3036 out.add(generatePermissionInfo(p, flags)); 3037 } 3038 } else { 3039 if (p.perm != null && group.equals(p.perm.info.group)) { 3040 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3041 } 3042 } 3043 } 3044 3045 if (out.size() > 0) { 3046 return out; 3047 } 3048 return mPermissionGroups.containsKey(group) ? out : null; 3049 } 3050 } 3051 3052 @Override 3053 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3054 // reader 3055 synchronized (mPackages) { 3056 return PackageParser.generatePermissionGroupInfo( 3057 mPermissionGroups.get(name), flags); 3058 } 3059 } 3060 3061 @Override 3062 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3063 // reader 3064 synchronized (mPackages) { 3065 final int N = mPermissionGroups.size(); 3066 ArrayList<PermissionGroupInfo> out 3067 = new ArrayList<PermissionGroupInfo>(N); 3068 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3069 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3070 } 3071 return out; 3072 } 3073 } 3074 3075 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3076 int userId) { 3077 if (!sUserManager.exists(userId)) return null; 3078 PackageSetting ps = mSettings.mPackages.get(packageName); 3079 if (ps != null) { 3080 if (ps.pkg == null) { 3081 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3082 flags, userId); 3083 if (pInfo != null) { 3084 return pInfo.applicationInfo; 3085 } 3086 return null; 3087 } 3088 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3089 ps.readUserState(userId), userId); 3090 } 3091 return null; 3092 } 3093 3094 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3095 int userId) { 3096 if (!sUserManager.exists(userId)) return null; 3097 PackageSetting ps = mSettings.mPackages.get(packageName); 3098 if (ps != null) { 3099 PackageParser.Package pkg = ps.pkg; 3100 if (pkg == null) { 3101 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3102 return null; 3103 } 3104 // Only data remains, so we aren't worried about code paths 3105 pkg = new PackageParser.Package(packageName); 3106 pkg.applicationInfo.packageName = packageName; 3107 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3108 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3109 pkg.applicationInfo.uid = ps.appId; 3110 pkg.applicationInfo.initForUser(userId); 3111 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3112 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3113 } 3114 return generatePackageInfo(pkg, flags, userId); 3115 } 3116 return null; 3117 } 3118 3119 @Override 3120 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3121 if (!sUserManager.exists(userId)) return null; 3122 flags = updateFlagsForApplication(flags, userId, packageName); 3123 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3124 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3125 // writer 3126 synchronized (mPackages) { 3127 PackageParser.Package p = mPackages.get(packageName); 3128 if (DEBUG_PACKAGE_INFO) Log.v( 3129 TAG, "getApplicationInfo " + packageName 3130 + ": " + p); 3131 if (p != null) { 3132 PackageSetting ps = mSettings.mPackages.get(packageName); 3133 if (ps == null) return null; 3134 // Note: isEnabledLP() does not apply here - always return info 3135 return PackageParser.generateApplicationInfo( 3136 p, flags, ps.readUserState(userId), userId); 3137 } 3138 if ("android".equals(packageName)||"system".equals(packageName)) { 3139 return mAndroidApplication; 3140 } 3141 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3142 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3143 } 3144 } 3145 return null; 3146 } 3147 3148 @Override 3149 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3150 final IPackageDataObserver observer) { 3151 mContext.enforceCallingOrSelfPermission( 3152 android.Manifest.permission.CLEAR_APP_CACHE, null); 3153 // Queue up an async operation since clearing cache may take a little while. 3154 mHandler.post(new Runnable() { 3155 public void run() { 3156 mHandler.removeCallbacks(this); 3157 boolean success = true; 3158 synchronized (mInstallLock) { 3159 try { 3160 mInstaller.freeCache(volumeUuid, freeStorageSize); 3161 } catch (InstallerException e) { 3162 Slog.w(TAG, "Couldn't clear application caches: " + e); 3163 success = false; 3164 } 3165 } 3166 if (observer != null) { 3167 try { 3168 observer.onRemoveCompleted(null, success); 3169 } catch (RemoteException e) { 3170 Slog.w(TAG, "RemoveException when invoking call back"); 3171 } 3172 } 3173 } 3174 }); 3175 } 3176 3177 @Override 3178 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3179 final IntentSender pi) { 3180 mContext.enforceCallingOrSelfPermission( 3181 android.Manifest.permission.CLEAR_APP_CACHE, null); 3182 // Queue up an async operation since clearing cache may take a little while. 3183 mHandler.post(new Runnable() { 3184 public void run() { 3185 mHandler.removeCallbacks(this); 3186 boolean success = true; 3187 synchronized (mInstallLock) { 3188 try { 3189 mInstaller.freeCache(volumeUuid, freeStorageSize); 3190 } catch (InstallerException e) { 3191 Slog.w(TAG, "Couldn't clear application caches: " + e); 3192 success = false; 3193 } 3194 } 3195 if(pi != null) { 3196 try { 3197 // Callback via pending intent 3198 int code = success ? 1 : 0; 3199 pi.sendIntent(null, code, null, 3200 null, null); 3201 } catch (SendIntentException e1) { 3202 Slog.i(TAG, "Failed to send pending intent"); 3203 } 3204 } 3205 } 3206 }); 3207 } 3208 3209 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3210 synchronized (mInstallLock) { 3211 try { 3212 mInstaller.freeCache(volumeUuid, freeStorageSize); 3213 } catch (InstallerException e) { 3214 throw new IOException("Failed to free enough space", e); 3215 } 3216 } 3217 } 3218 3219 /** 3220 * Return if the user key is currently unlocked. 3221 */ 3222 private boolean isUserKeyUnlocked(int userId) { 3223 if (StorageManager.isFileBasedEncryptionEnabled()) { 3224 final IMountService mount = IMountService.Stub 3225 .asInterface(ServiceManager.getService("mount")); 3226 if (mount == null) { 3227 Slog.w(TAG, "Early during boot, assuming locked"); 3228 return false; 3229 } 3230 final long token = Binder.clearCallingIdentity(); 3231 try { 3232 return mount.isUserKeyUnlocked(userId); 3233 } catch (RemoteException e) { 3234 throw e.rethrowAsRuntimeException(); 3235 } finally { 3236 Binder.restoreCallingIdentity(token); 3237 } 3238 } else { 3239 return true; 3240 } 3241 } 3242 3243 /** 3244 * Update given flags based on encryption status of current user. 3245 */ 3246 private int updateFlags(int flags, int userId) { 3247 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3248 | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) { 3249 // Caller expressed an explicit opinion about what encryption 3250 // aware/unaware components they want to see, so fall through and 3251 // give them what they want 3252 } else { 3253 // Caller expressed no opinion, so match based on user state 3254 if (isUserKeyUnlocked(userId)) { 3255 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 3256 } else { 3257 flags |= PackageManager.MATCH_ENCRYPTION_AWARE; 3258 } 3259 } 3260 return flags; 3261 } 3262 3263 /** 3264 * Update given flags when being used to request {@link PackageInfo}. 3265 */ 3266 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3267 boolean triaged = true; 3268 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3269 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3270 // Caller is asking for component details, so they'd better be 3271 // asking for specific encryption matching behavior, or be triaged 3272 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3273 | PackageManager.MATCH_ENCRYPTION_AWARE 3274 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3275 triaged = false; 3276 } 3277 } 3278 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3279 | PackageManager.MATCH_SYSTEM_ONLY 3280 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3281 triaged = false; 3282 } 3283 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3284 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3285 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3286 } 3287 return updateFlags(flags, userId); 3288 } 3289 3290 /** 3291 * Update given flags when being used to request {@link ApplicationInfo}. 3292 */ 3293 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3294 return updateFlagsForPackage(flags, userId, cookie); 3295 } 3296 3297 /** 3298 * Update given flags when being used to request {@link ComponentInfo}. 3299 */ 3300 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3301 if (cookie instanceof Intent) { 3302 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3303 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3304 } 3305 } 3306 3307 boolean triaged = true; 3308 // Caller is asking for component details, so they'd better be 3309 // asking for specific encryption matching behavior, or be triaged 3310 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3311 | PackageManager.MATCH_ENCRYPTION_AWARE 3312 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3313 triaged = false; 3314 } 3315 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3316 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3317 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3318 } 3319 3320 return updateFlags(flags, userId); 3321 } 3322 3323 /** 3324 * Update given flags when being used to request {@link ResolveInfo}. 3325 */ 3326 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3327 // Safe mode means we shouldn't match any third-party components 3328 if (mSafeMode) { 3329 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3330 } 3331 3332 return updateFlagsForComponent(flags, userId, cookie); 3333 } 3334 3335 @Override 3336 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3337 if (!sUserManager.exists(userId)) return null; 3338 flags = updateFlagsForComponent(flags, userId, component); 3339 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3340 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3341 synchronized (mPackages) { 3342 PackageParser.Activity a = mActivities.mActivities.get(component); 3343 3344 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3345 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3346 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3347 if (ps == null) return null; 3348 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3349 userId); 3350 } 3351 if (mResolveComponentName.equals(component)) { 3352 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3353 new PackageUserState(), userId); 3354 } 3355 } 3356 return null; 3357 } 3358 3359 @Override 3360 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3361 String resolvedType) { 3362 synchronized (mPackages) { 3363 if (component.equals(mResolveComponentName)) { 3364 // The resolver supports EVERYTHING! 3365 return true; 3366 } 3367 PackageParser.Activity a = mActivities.mActivities.get(component); 3368 if (a == null) { 3369 return false; 3370 } 3371 for (int i=0; i<a.intents.size(); i++) { 3372 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3373 intent.getData(), intent.getCategories(), TAG) >= 0) { 3374 return true; 3375 } 3376 } 3377 return false; 3378 } 3379 } 3380 3381 @Override 3382 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3383 if (!sUserManager.exists(userId)) return null; 3384 flags = updateFlagsForComponent(flags, userId, component); 3385 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3386 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3387 synchronized (mPackages) { 3388 PackageParser.Activity a = mReceivers.mActivities.get(component); 3389 if (DEBUG_PACKAGE_INFO) Log.v( 3390 TAG, "getReceiverInfo " + component + ": " + a); 3391 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3392 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3393 if (ps == null) return null; 3394 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3395 userId); 3396 } 3397 } 3398 return null; 3399 } 3400 3401 @Override 3402 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3403 if (!sUserManager.exists(userId)) return null; 3404 flags = updateFlagsForComponent(flags, userId, component); 3405 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3406 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3407 synchronized (mPackages) { 3408 PackageParser.Service s = mServices.mServices.get(component); 3409 if (DEBUG_PACKAGE_INFO) Log.v( 3410 TAG, "getServiceInfo " + component + ": " + s); 3411 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3412 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3413 if (ps == null) return null; 3414 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3415 userId); 3416 } 3417 } 3418 return null; 3419 } 3420 3421 @Override 3422 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3423 if (!sUserManager.exists(userId)) return null; 3424 flags = updateFlagsForComponent(flags, userId, component); 3425 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3426 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3427 synchronized (mPackages) { 3428 PackageParser.Provider p = mProviders.mProviders.get(component); 3429 if (DEBUG_PACKAGE_INFO) Log.v( 3430 TAG, "getProviderInfo " + component + ": " + p); 3431 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3432 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3433 if (ps == null) return null; 3434 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3435 userId); 3436 } 3437 } 3438 return null; 3439 } 3440 3441 @Override 3442 public String[] getSystemSharedLibraryNames() { 3443 Set<String> libSet; 3444 synchronized (mPackages) { 3445 libSet = mSharedLibraries.keySet(); 3446 int size = libSet.size(); 3447 if (size > 0) { 3448 String[] libs = new String[size]; 3449 libSet.toArray(libs); 3450 return libs; 3451 } 3452 } 3453 return null; 3454 } 3455 3456 @Override 3457 public @Nullable String getServicesSystemSharedLibraryPackageName() { 3458 synchronized (mPackages) { 3459 SharedLibraryEntry libraryEntry = mSharedLibraries.get( 3460 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 3461 if (libraryEntry != null) { 3462 return libraryEntry.apk; 3463 } 3464 } 3465 return null; 3466 } 3467 3468 @Override 3469 public FeatureInfo[] getSystemAvailableFeatures() { 3470 Collection<FeatureInfo> featSet; 3471 synchronized (mPackages) { 3472 featSet = mAvailableFeatures.values(); 3473 int size = featSet.size(); 3474 if (size > 0) { 3475 FeatureInfo[] features = new FeatureInfo[size+1]; 3476 featSet.toArray(features); 3477 FeatureInfo fi = new FeatureInfo(); 3478 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3479 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3480 features[size] = fi; 3481 return features; 3482 } 3483 } 3484 return null; 3485 } 3486 3487 @Override 3488 public boolean hasSystemFeature(String name, int version) { 3489 synchronized (mPackages) { 3490 final FeatureInfo feat = mAvailableFeatures.get(name); 3491 if (feat == null) { 3492 return false; 3493 } else { 3494 return feat.version >= version; 3495 } 3496 } 3497 } 3498 3499 @Override 3500 public int checkPermission(String permName, String pkgName, int userId) { 3501 if (!sUserManager.exists(userId)) { 3502 return PackageManager.PERMISSION_DENIED; 3503 } 3504 3505 synchronized (mPackages) { 3506 final PackageParser.Package p = mPackages.get(pkgName); 3507 if (p != null && p.mExtras != null) { 3508 final PackageSetting ps = (PackageSetting) p.mExtras; 3509 final PermissionsState permissionsState = ps.getPermissionsState(); 3510 if (permissionsState.hasPermission(permName, userId)) { 3511 return PackageManager.PERMISSION_GRANTED; 3512 } 3513 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3514 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3515 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3516 return PackageManager.PERMISSION_GRANTED; 3517 } 3518 } 3519 } 3520 3521 return PackageManager.PERMISSION_DENIED; 3522 } 3523 3524 @Override 3525 public int checkUidPermission(String permName, int uid) { 3526 final int userId = UserHandle.getUserId(uid); 3527 3528 if (!sUserManager.exists(userId)) { 3529 return PackageManager.PERMISSION_DENIED; 3530 } 3531 3532 synchronized (mPackages) { 3533 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3534 if (obj != null) { 3535 final SettingBase ps = (SettingBase) obj; 3536 final PermissionsState permissionsState = ps.getPermissionsState(); 3537 if (permissionsState.hasPermission(permName, userId)) { 3538 return PackageManager.PERMISSION_GRANTED; 3539 } 3540 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3541 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3542 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3543 return PackageManager.PERMISSION_GRANTED; 3544 } 3545 } else { 3546 ArraySet<String> perms = mSystemPermissions.get(uid); 3547 if (perms != null) { 3548 if (perms.contains(permName)) { 3549 return PackageManager.PERMISSION_GRANTED; 3550 } 3551 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3552 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3553 return PackageManager.PERMISSION_GRANTED; 3554 } 3555 } 3556 } 3557 } 3558 3559 return PackageManager.PERMISSION_DENIED; 3560 } 3561 3562 @Override 3563 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3564 if (UserHandle.getCallingUserId() != userId) { 3565 mContext.enforceCallingPermission( 3566 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3567 "isPermissionRevokedByPolicy for user " + userId); 3568 } 3569 3570 if (checkPermission(permission, packageName, userId) 3571 == PackageManager.PERMISSION_GRANTED) { 3572 return false; 3573 } 3574 3575 final long identity = Binder.clearCallingIdentity(); 3576 try { 3577 final int flags = getPermissionFlags(permission, packageName, userId); 3578 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3579 } finally { 3580 Binder.restoreCallingIdentity(identity); 3581 } 3582 } 3583 3584 @Override 3585 public String getPermissionControllerPackageName() { 3586 synchronized (mPackages) { 3587 return mRequiredInstallerPackage; 3588 } 3589 } 3590 3591 /** 3592 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3593 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3594 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3595 * @param message the message to log on security exception 3596 */ 3597 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3598 boolean checkShell, String message) { 3599 if (userId < 0) { 3600 throw new IllegalArgumentException("Invalid userId " + userId); 3601 } 3602 if (checkShell) { 3603 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3604 } 3605 if (userId == UserHandle.getUserId(callingUid)) return; 3606 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3607 if (requireFullPermission) { 3608 mContext.enforceCallingOrSelfPermission( 3609 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3610 } else { 3611 try { 3612 mContext.enforceCallingOrSelfPermission( 3613 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3614 } catch (SecurityException se) { 3615 mContext.enforceCallingOrSelfPermission( 3616 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3617 } 3618 } 3619 } 3620 } 3621 3622 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3623 if (callingUid == Process.SHELL_UID) { 3624 if (userHandle >= 0 3625 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3626 throw new SecurityException("Shell does not have permission to access user " 3627 + userHandle); 3628 } else if (userHandle < 0) { 3629 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3630 + Debug.getCallers(3)); 3631 } 3632 } 3633 } 3634 3635 private BasePermission findPermissionTreeLP(String permName) { 3636 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3637 if (permName.startsWith(bp.name) && 3638 permName.length() > bp.name.length() && 3639 permName.charAt(bp.name.length()) == '.') { 3640 return bp; 3641 } 3642 } 3643 return null; 3644 } 3645 3646 private BasePermission checkPermissionTreeLP(String permName) { 3647 if (permName != null) { 3648 BasePermission bp = findPermissionTreeLP(permName); 3649 if (bp != null) { 3650 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3651 return bp; 3652 } 3653 throw new SecurityException("Calling uid " 3654 + Binder.getCallingUid() 3655 + " is not allowed to add to permission tree " 3656 + bp.name + " owned by uid " + bp.uid); 3657 } 3658 } 3659 throw new SecurityException("No permission tree found for " + permName); 3660 } 3661 3662 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3663 if (s1 == null) { 3664 return s2 == null; 3665 } 3666 if (s2 == null) { 3667 return false; 3668 } 3669 if (s1.getClass() != s2.getClass()) { 3670 return false; 3671 } 3672 return s1.equals(s2); 3673 } 3674 3675 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3676 if (pi1.icon != pi2.icon) return false; 3677 if (pi1.logo != pi2.logo) return false; 3678 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3679 if (!compareStrings(pi1.name, pi2.name)) return false; 3680 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3681 // We'll take care of setting this one. 3682 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3683 // These are not currently stored in settings. 3684 //if (!compareStrings(pi1.group, pi2.group)) return false; 3685 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3686 //if (pi1.labelRes != pi2.labelRes) return false; 3687 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3688 return true; 3689 } 3690 3691 int permissionInfoFootprint(PermissionInfo info) { 3692 int size = info.name.length(); 3693 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3694 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3695 return size; 3696 } 3697 3698 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3699 int size = 0; 3700 for (BasePermission perm : mSettings.mPermissions.values()) { 3701 if (perm.uid == tree.uid) { 3702 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3703 } 3704 } 3705 return size; 3706 } 3707 3708 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3709 // We calculate the max size of permissions defined by this uid and throw 3710 // if that plus the size of 'info' would exceed our stated maximum. 3711 if (tree.uid != Process.SYSTEM_UID) { 3712 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3713 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3714 throw new SecurityException("Permission tree size cap exceeded"); 3715 } 3716 } 3717 } 3718 3719 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3720 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3721 throw new SecurityException("Label must be specified in permission"); 3722 } 3723 BasePermission tree = checkPermissionTreeLP(info.name); 3724 BasePermission bp = mSettings.mPermissions.get(info.name); 3725 boolean added = bp == null; 3726 boolean changed = true; 3727 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3728 if (added) { 3729 enforcePermissionCapLocked(info, tree); 3730 bp = new BasePermission(info.name, tree.sourcePackage, 3731 BasePermission.TYPE_DYNAMIC); 3732 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3733 throw new SecurityException( 3734 "Not allowed to modify non-dynamic permission " 3735 + info.name); 3736 } else { 3737 if (bp.protectionLevel == fixedLevel 3738 && bp.perm.owner.equals(tree.perm.owner) 3739 && bp.uid == tree.uid 3740 && comparePermissionInfos(bp.perm.info, info)) { 3741 changed = false; 3742 } 3743 } 3744 bp.protectionLevel = fixedLevel; 3745 info = new PermissionInfo(info); 3746 info.protectionLevel = fixedLevel; 3747 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3748 bp.perm.info.packageName = tree.perm.info.packageName; 3749 bp.uid = tree.uid; 3750 if (added) { 3751 mSettings.mPermissions.put(info.name, bp); 3752 } 3753 if (changed) { 3754 if (!async) { 3755 mSettings.writeLPr(); 3756 } else { 3757 scheduleWriteSettingsLocked(); 3758 } 3759 } 3760 return added; 3761 } 3762 3763 @Override 3764 public boolean addPermission(PermissionInfo info) { 3765 synchronized (mPackages) { 3766 return addPermissionLocked(info, false); 3767 } 3768 } 3769 3770 @Override 3771 public boolean addPermissionAsync(PermissionInfo info) { 3772 synchronized (mPackages) { 3773 return addPermissionLocked(info, true); 3774 } 3775 } 3776 3777 @Override 3778 public void removePermission(String name) { 3779 synchronized (mPackages) { 3780 checkPermissionTreeLP(name); 3781 BasePermission bp = mSettings.mPermissions.get(name); 3782 if (bp != null) { 3783 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3784 throw new SecurityException( 3785 "Not allowed to modify non-dynamic permission " 3786 + name); 3787 } 3788 mSettings.mPermissions.remove(name); 3789 mSettings.writeLPr(); 3790 } 3791 } 3792 } 3793 3794 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3795 BasePermission bp) { 3796 int index = pkg.requestedPermissions.indexOf(bp.name); 3797 if (index == -1) { 3798 throw new SecurityException("Package " + pkg.packageName 3799 + " has not requested permission " + bp.name); 3800 } 3801 if (!bp.isRuntime() && !bp.isDevelopment()) { 3802 throw new SecurityException("Permission " + bp.name 3803 + " is not a changeable permission type"); 3804 } 3805 } 3806 3807 @Override 3808 public void grantRuntimePermission(String packageName, String name, final int userId) { 3809 if (!sUserManager.exists(userId)) { 3810 Log.e(TAG, "No such user:" + userId); 3811 return; 3812 } 3813 3814 mContext.enforceCallingOrSelfPermission( 3815 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3816 "grantRuntimePermission"); 3817 3818 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3819 true /* requireFullPermission */, true /* checkShell */, 3820 "grantRuntimePermission"); 3821 3822 final int uid; 3823 final SettingBase sb; 3824 3825 synchronized (mPackages) { 3826 final PackageParser.Package pkg = mPackages.get(packageName); 3827 if (pkg == null) { 3828 throw new IllegalArgumentException("Unknown package: " + packageName); 3829 } 3830 3831 final BasePermission bp = mSettings.mPermissions.get(name); 3832 if (bp == null) { 3833 throw new IllegalArgumentException("Unknown permission: " + name); 3834 } 3835 3836 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3837 3838 // If a permission review is required for legacy apps we represent 3839 // their permissions as always granted runtime ones since we need 3840 // to keep the review required permission flag per user while an 3841 // install permission's state is shared across all users. 3842 if (Build.PERMISSIONS_REVIEW_REQUIRED 3843 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3844 && bp.isRuntime()) { 3845 return; 3846 } 3847 3848 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3849 sb = (SettingBase) pkg.mExtras; 3850 if (sb == null) { 3851 throw new IllegalArgumentException("Unknown package: " + packageName); 3852 } 3853 3854 final PermissionsState permissionsState = sb.getPermissionsState(); 3855 3856 final int flags = permissionsState.getPermissionFlags(name, userId); 3857 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3858 throw new SecurityException("Cannot grant system fixed permission " 3859 + name + " for package " + packageName); 3860 } 3861 3862 if (bp.isDevelopment()) { 3863 // Development permissions must be handled specially, since they are not 3864 // normal runtime permissions. For now they apply to all users. 3865 if (permissionsState.grantInstallPermission(bp) != 3866 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3867 scheduleWriteSettingsLocked(); 3868 } 3869 return; 3870 } 3871 3872 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3873 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3874 return; 3875 } 3876 3877 final int result = permissionsState.grantRuntimePermission(bp, userId); 3878 switch (result) { 3879 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3880 return; 3881 } 3882 3883 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3884 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3885 mHandler.post(new Runnable() { 3886 @Override 3887 public void run() { 3888 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3889 } 3890 }); 3891 } 3892 break; 3893 } 3894 3895 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3896 3897 // Not critical if that is lost - app has to request again. 3898 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3899 } 3900 3901 // Only need to do this if user is initialized. Otherwise it's a new user 3902 // and there are no processes running as the user yet and there's no need 3903 // to make an expensive call to remount processes for the changed permissions. 3904 if (READ_EXTERNAL_STORAGE.equals(name) 3905 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3906 final long token = Binder.clearCallingIdentity(); 3907 try { 3908 if (sUserManager.isInitialized(userId)) { 3909 MountServiceInternal mountServiceInternal = LocalServices.getService( 3910 MountServiceInternal.class); 3911 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3912 } 3913 } finally { 3914 Binder.restoreCallingIdentity(token); 3915 } 3916 } 3917 } 3918 3919 @Override 3920 public void revokeRuntimePermission(String packageName, String name, int userId) { 3921 if (!sUserManager.exists(userId)) { 3922 Log.e(TAG, "No such user:" + userId); 3923 return; 3924 } 3925 3926 mContext.enforceCallingOrSelfPermission( 3927 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3928 "revokeRuntimePermission"); 3929 3930 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3931 true /* requireFullPermission */, true /* checkShell */, 3932 "revokeRuntimePermission"); 3933 3934 final int appId; 3935 3936 synchronized (mPackages) { 3937 final PackageParser.Package pkg = mPackages.get(packageName); 3938 if (pkg == null) { 3939 throw new IllegalArgumentException("Unknown package: " + packageName); 3940 } 3941 3942 final BasePermission bp = mSettings.mPermissions.get(name); 3943 if (bp == null) { 3944 throw new IllegalArgumentException("Unknown permission: " + name); 3945 } 3946 3947 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3948 3949 // If a permission review is required for legacy apps we represent 3950 // their permissions as always granted runtime ones since we need 3951 // to keep the review required permission flag per user while an 3952 // install permission's state is shared across all users. 3953 if (Build.PERMISSIONS_REVIEW_REQUIRED 3954 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3955 && bp.isRuntime()) { 3956 return; 3957 } 3958 3959 SettingBase sb = (SettingBase) pkg.mExtras; 3960 if (sb == null) { 3961 throw new IllegalArgumentException("Unknown package: " + packageName); 3962 } 3963 3964 final PermissionsState permissionsState = sb.getPermissionsState(); 3965 3966 final int flags = permissionsState.getPermissionFlags(name, userId); 3967 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3968 throw new SecurityException("Cannot revoke system fixed permission " 3969 + name + " for package " + packageName); 3970 } 3971 3972 if (bp.isDevelopment()) { 3973 // Development permissions must be handled specially, since they are not 3974 // normal runtime permissions. For now they apply to all users. 3975 if (permissionsState.revokeInstallPermission(bp) != 3976 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3977 scheduleWriteSettingsLocked(); 3978 } 3979 return; 3980 } 3981 3982 if (permissionsState.revokeRuntimePermission(bp, userId) == 3983 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3984 return; 3985 } 3986 3987 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3988 3989 // Critical, after this call app should never have the permission. 3990 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3991 3992 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3993 } 3994 3995 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3996 } 3997 3998 @Override 3999 public void resetRuntimePermissions() { 4000 mContext.enforceCallingOrSelfPermission( 4001 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4002 "revokeRuntimePermission"); 4003 4004 int callingUid = Binder.getCallingUid(); 4005 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4006 mContext.enforceCallingOrSelfPermission( 4007 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4008 "resetRuntimePermissions"); 4009 } 4010 4011 synchronized (mPackages) { 4012 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4013 for (int userId : UserManagerService.getInstance().getUserIds()) { 4014 final int packageCount = mPackages.size(); 4015 for (int i = 0; i < packageCount; i++) { 4016 PackageParser.Package pkg = mPackages.valueAt(i); 4017 if (!(pkg.mExtras instanceof PackageSetting)) { 4018 continue; 4019 } 4020 PackageSetting ps = (PackageSetting) pkg.mExtras; 4021 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4022 } 4023 } 4024 } 4025 } 4026 4027 @Override 4028 public int getPermissionFlags(String name, String packageName, int userId) { 4029 if (!sUserManager.exists(userId)) { 4030 return 0; 4031 } 4032 4033 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4034 4035 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4036 true /* requireFullPermission */, false /* checkShell */, 4037 "getPermissionFlags"); 4038 4039 synchronized (mPackages) { 4040 final PackageParser.Package pkg = mPackages.get(packageName); 4041 if (pkg == null) { 4042 throw new IllegalArgumentException("Unknown package: " + packageName); 4043 } 4044 4045 final BasePermission bp = mSettings.mPermissions.get(name); 4046 if (bp == null) { 4047 throw new IllegalArgumentException("Unknown permission: " + name); 4048 } 4049 4050 SettingBase sb = (SettingBase) pkg.mExtras; 4051 if (sb == null) { 4052 throw new IllegalArgumentException("Unknown package: " + packageName); 4053 } 4054 4055 PermissionsState permissionsState = sb.getPermissionsState(); 4056 return permissionsState.getPermissionFlags(name, userId); 4057 } 4058 } 4059 4060 @Override 4061 public void updatePermissionFlags(String name, String packageName, int flagMask, 4062 int flagValues, int userId) { 4063 if (!sUserManager.exists(userId)) { 4064 return; 4065 } 4066 4067 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4068 4069 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4070 true /* requireFullPermission */, true /* checkShell */, 4071 "updatePermissionFlags"); 4072 4073 // Only the system can change these flags and nothing else. 4074 if (getCallingUid() != Process.SYSTEM_UID) { 4075 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4076 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4077 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4078 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4079 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4080 } 4081 4082 synchronized (mPackages) { 4083 final PackageParser.Package pkg = mPackages.get(packageName); 4084 if (pkg == null) { 4085 throw new IllegalArgumentException("Unknown package: " + packageName); 4086 } 4087 4088 final BasePermission bp = mSettings.mPermissions.get(name); 4089 if (bp == null) { 4090 throw new IllegalArgumentException("Unknown permission: " + name); 4091 } 4092 4093 SettingBase sb = (SettingBase) pkg.mExtras; 4094 if (sb == null) { 4095 throw new IllegalArgumentException("Unknown package: " + packageName); 4096 } 4097 4098 PermissionsState permissionsState = sb.getPermissionsState(); 4099 4100 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4101 4102 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4103 // Install and runtime permissions are stored in different places, 4104 // so figure out what permission changed and persist the change. 4105 if (permissionsState.getInstallPermissionState(name) != null) { 4106 scheduleWriteSettingsLocked(); 4107 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4108 || hadState) { 4109 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4110 } 4111 } 4112 } 4113 } 4114 4115 /** 4116 * Update the permission flags for all packages and runtime permissions of a user in order 4117 * to allow device or profile owner to remove POLICY_FIXED. 4118 */ 4119 @Override 4120 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4121 if (!sUserManager.exists(userId)) { 4122 return; 4123 } 4124 4125 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4126 4127 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4128 true /* requireFullPermission */, true /* checkShell */, 4129 "updatePermissionFlagsForAllApps"); 4130 4131 // Only the system can change system fixed flags. 4132 if (getCallingUid() != Process.SYSTEM_UID) { 4133 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4134 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4135 } 4136 4137 synchronized (mPackages) { 4138 boolean changed = false; 4139 final int packageCount = mPackages.size(); 4140 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4141 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4142 SettingBase sb = (SettingBase) pkg.mExtras; 4143 if (sb == null) { 4144 continue; 4145 } 4146 PermissionsState permissionsState = sb.getPermissionsState(); 4147 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4148 userId, flagMask, flagValues); 4149 } 4150 if (changed) { 4151 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4152 } 4153 } 4154 } 4155 4156 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4157 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4158 != PackageManager.PERMISSION_GRANTED 4159 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4160 != PackageManager.PERMISSION_GRANTED) { 4161 throw new SecurityException(message + " requires " 4162 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4163 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4164 } 4165 } 4166 4167 @Override 4168 public boolean shouldShowRequestPermissionRationale(String permissionName, 4169 String packageName, int userId) { 4170 if (UserHandle.getCallingUserId() != userId) { 4171 mContext.enforceCallingPermission( 4172 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4173 "canShowRequestPermissionRationale for user " + userId); 4174 } 4175 4176 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4177 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4178 return false; 4179 } 4180 4181 if (checkPermission(permissionName, packageName, userId) 4182 == PackageManager.PERMISSION_GRANTED) { 4183 return false; 4184 } 4185 4186 final int flags; 4187 4188 final long identity = Binder.clearCallingIdentity(); 4189 try { 4190 flags = getPermissionFlags(permissionName, 4191 packageName, userId); 4192 } finally { 4193 Binder.restoreCallingIdentity(identity); 4194 } 4195 4196 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4197 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4198 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4199 4200 if ((flags & fixedFlags) != 0) { 4201 return false; 4202 } 4203 4204 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4205 } 4206 4207 @Override 4208 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4209 mContext.enforceCallingOrSelfPermission( 4210 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4211 "addOnPermissionsChangeListener"); 4212 4213 synchronized (mPackages) { 4214 mOnPermissionChangeListeners.addListenerLocked(listener); 4215 } 4216 } 4217 4218 @Override 4219 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4220 synchronized (mPackages) { 4221 mOnPermissionChangeListeners.removeListenerLocked(listener); 4222 } 4223 } 4224 4225 @Override 4226 public boolean isProtectedBroadcast(String actionName) { 4227 synchronized (mPackages) { 4228 if (mProtectedBroadcasts.contains(actionName)) { 4229 return true; 4230 } else if (actionName != null) { 4231 // TODO: remove these terrible hacks 4232 if (actionName.startsWith("android.net.netmon.lingerExpired") 4233 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4234 || actionName.startsWith("com.android.internal.telephony.data-reconnect")) { 4235 return true; 4236 } 4237 } 4238 } 4239 return false; 4240 } 4241 4242 @Override 4243 public int checkSignatures(String pkg1, String pkg2) { 4244 synchronized (mPackages) { 4245 final PackageParser.Package p1 = mPackages.get(pkg1); 4246 final PackageParser.Package p2 = mPackages.get(pkg2); 4247 if (p1 == null || p1.mExtras == null 4248 || p2 == null || p2.mExtras == null) { 4249 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4250 } 4251 return compareSignatures(p1.mSignatures, p2.mSignatures); 4252 } 4253 } 4254 4255 @Override 4256 public int checkUidSignatures(int uid1, int uid2) { 4257 // Map to base uids. 4258 uid1 = UserHandle.getAppId(uid1); 4259 uid2 = UserHandle.getAppId(uid2); 4260 // reader 4261 synchronized (mPackages) { 4262 Signature[] s1; 4263 Signature[] s2; 4264 Object obj = mSettings.getUserIdLPr(uid1); 4265 if (obj != null) { 4266 if (obj instanceof SharedUserSetting) { 4267 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4268 } else if (obj instanceof PackageSetting) { 4269 s1 = ((PackageSetting)obj).signatures.mSignatures; 4270 } else { 4271 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4272 } 4273 } else { 4274 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4275 } 4276 obj = mSettings.getUserIdLPr(uid2); 4277 if (obj != null) { 4278 if (obj instanceof SharedUserSetting) { 4279 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4280 } else if (obj instanceof PackageSetting) { 4281 s2 = ((PackageSetting)obj).signatures.mSignatures; 4282 } else { 4283 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4284 } 4285 } else { 4286 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4287 } 4288 return compareSignatures(s1, s2); 4289 } 4290 } 4291 4292 private void killUid(int appId, int userId, String reason) { 4293 final long identity = Binder.clearCallingIdentity(); 4294 try { 4295 IActivityManager am = ActivityManagerNative.getDefault(); 4296 if (am != null) { 4297 try { 4298 am.killUid(appId, userId, reason); 4299 } catch (RemoteException e) { 4300 /* ignore - same process */ 4301 } 4302 } 4303 } finally { 4304 Binder.restoreCallingIdentity(identity); 4305 } 4306 } 4307 4308 /** 4309 * Compares two sets of signatures. Returns: 4310 * <br /> 4311 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4312 * <br /> 4313 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4314 * <br /> 4315 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4316 * <br /> 4317 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4318 * <br /> 4319 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4320 */ 4321 static int compareSignatures(Signature[] s1, Signature[] s2) { 4322 if (s1 == null) { 4323 return s2 == null 4324 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4325 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4326 } 4327 4328 if (s2 == null) { 4329 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4330 } 4331 4332 if (s1.length != s2.length) { 4333 return PackageManager.SIGNATURE_NO_MATCH; 4334 } 4335 4336 // Since both signature sets are of size 1, we can compare without HashSets. 4337 if (s1.length == 1) { 4338 return s1[0].equals(s2[0]) ? 4339 PackageManager.SIGNATURE_MATCH : 4340 PackageManager.SIGNATURE_NO_MATCH; 4341 } 4342 4343 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4344 for (Signature sig : s1) { 4345 set1.add(sig); 4346 } 4347 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4348 for (Signature sig : s2) { 4349 set2.add(sig); 4350 } 4351 // Make sure s2 contains all signatures in s1. 4352 if (set1.equals(set2)) { 4353 return PackageManager.SIGNATURE_MATCH; 4354 } 4355 return PackageManager.SIGNATURE_NO_MATCH; 4356 } 4357 4358 /** 4359 * If the database version for this type of package (internal storage or 4360 * external storage) is less than the version where package signatures 4361 * were updated, return true. 4362 */ 4363 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4364 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4365 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4366 } 4367 4368 /** 4369 * Used for backward compatibility to make sure any packages with 4370 * certificate chains get upgraded to the new style. {@code existingSigs} 4371 * will be in the old format (since they were stored on disk from before the 4372 * system upgrade) and {@code scannedSigs} will be in the newer format. 4373 */ 4374 private int compareSignaturesCompat(PackageSignatures existingSigs, 4375 PackageParser.Package scannedPkg) { 4376 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4377 return PackageManager.SIGNATURE_NO_MATCH; 4378 } 4379 4380 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4381 for (Signature sig : existingSigs.mSignatures) { 4382 existingSet.add(sig); 4383 } 4384 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4385 for (Signature sig : scannedPkg.mSignatures) { 4386 try { 4387 Signature[] chainSignatures = sig.getChainSignatures(); 4388 for (Signature chainSig : chainSignatures) { 4389 scannedCompatSet.add(chainSig); 4390 } 4391 } catch (CertificateEncodingException e) { 4392 scannedCompatSet.add(sig); 4393 } 4394 } 4395 /* 4396 * Make sure the expanded scanned set contains all signatures in the 4397 * existing one. 4398 */ 4399 if (scannedCompatSet.equals(existingSet)) { 4400 // Migrate the old signatures to the new scheme. 4401 existingSigs.assignSignatures(scannedPkg.mSignatures); 4402 // The new KeySets will be re-added later in the scanning process. 4403 synchronized (mPackages) { 4404 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4405 } 4406 return PackageManager.SIGNATURE_MATCH; 4407 } 4408 return PackageManager.SIGNATURE_NO_MATCH; 4409 } 4410 4411 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4412 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4413 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4414 } 4415 4416 private int compareSignaturesRecover(PackageSignatures existingSigs, 4417 PackageParser.Package scannedPkg) { 4418 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4419 return PackageManager.SIGNATURE_NO_MATCH; 4420 } 4421 4422 String msg = null; 4423 try { 4424 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4425 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4426 + scannedPkg.packageName); 4427 return PackageManager.SIGNATURE_MATCH; 4428 } 4429 } catch (CertificateException e) { 4430 msg = e.getMessage(); 4431 } 4432 4433 logCriticalInfo(Log.INFO, 4434 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4435 return PackageManager.SIGNATURE_NO_MATCH; 4436 } 4437 4438 @Override 4439 public String[] getPackagesForUid(int uid) { 4440 uid = UserHandle.getAppId(uid); 4441 // reader 4442 synchronized (mPackages) { 4443 Object obj = mSettings.getUserIdLPr(uid); 4444 if (obj instanceof SharedUserSetting) { 4445 final SharedUserSetting sus = (SharedUserSetting) obj; 4446 final int N = sus.packages.size(); 4447 final String[] res = new String[N]; 4448 final Iterator<PackageSetting> it = sus.packages.iterator(); 4449 int i = 0; 4450 while (it.hasNext()) { 4451 res[i++] = it.next().name; 4452 } 4453 return res; 4454 } else if (obj instanceof PackageSetting) { 4455 final PackageSetting ps = (PackageSetting) obj; 4456 return new String[] { ps.name }; 4457 } 4458 } 4459 return null; 4460 } 4461 4462 @Override 4463 public String getNameForUid(int uid) { 4464 // reader 4465 synchronized (mPackages) { 4466 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4467 if (obj instanceof SharedUserSetting) { 4468 final SharedUserSetting sus = (SharedUserSetting) obj; 4469 return sus.name + ":" + sus.userId; 4470 } else if (obj instanceof PackageSetting) { 4471 final PackageSetting ps = (PackageSetting) obj; 4472 return ps.name; 4473 } 4474 } 4475 return null; 4476 } 4477 4478 @Override 4479 public int getUidForSharedUser(String sharedUserName) { 4480 if(sharedUserName == null) { 4481 return -1; 4482 } 4483 // reader 4484 synchronized (mPackages) { 4485 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4486 if (suid == null) { 4487 return -1; 4488 } 4489 return suid.userId; 4490 } 4491 } 4492 4493 @Override 4494 public int getFlagsForUid(int uid) { 4495 synchronized (mPackages) { 4496 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4497 if (obj instanceof SharedUserSetting) { 4498 final SharedUserSetting sus = (SharedUserSetting) obj; 4499 return sus.pkgFlags; 4500 } else if (obj instanceof PackageSetting) { 4501 final PackageSetting ps = (PackageSetting) obj; 4502 return ps.pkgFlags; 4503 } 4504 } 4505 return 0; 4506 } 4507 4508 @Override 4509 public int getPrivateFlagsForUid(int uid) { 4510 synchronized (mPackages) { 4511 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4512 if (obj instanceof SharedUserSetting) { 4513 final SharedUserSetting sus = (SharedUserSetting) obj; 4514 return sus.pkgPrivateFlags; 4515 } else if (obj instanceof PackageSetting) { 4516 final PackageSetting ps = (PackageSetting) obj; 4517 return ps.pkgPrivateFlags; 4518 } 4519 } 4520 return 0; 4521 } 4522 4523 @Override 4524 public boolean isUidPrivileged(int uid) { 4525 uid = UserHandle.getAppId(uid); 4526 // reader 4527 synchronized (mPackages) { 4528 Object obj = mSettings.getUserIdLPr(uid); 4529 if (obj instanceof SharedUserSetting) { 4530 final SharedUserSetting sus = (SharedUserSetting) obj; 4531 final Iterator<PackageSetting> it = sus.packages.iterator(); 4532 while (it.hasNext()) { 4533 if (it.next().isPrivileged()) { 4534 return true; 4535 } 4536 } 4537 } else if (obj instanceof PackageSetting) { 4538 final PackageSetting ps = (PackageSetting) obj; 4539 return ps.isPrivileged(); 4540 } 4541 } 4542 return false; 4543 } 4544 4545 @Override 4546 public String[] getAppOpPermissionPackages(String permissionName) { 4547 synchronized (mPackages) { 4548 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4549 if (pkgs == null) { 4550 return null; 4551 } 4552 return pkgs.toArray(new String[pkgs.size()]); 4553 } 4554 } 4555 4556 @Override 4557 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4558 int flags, int userId) { 4559 if (!sUserManager.exists(userId)) return null; 4560 flags = updateFlagsForResolve(flags, userId, intent); 4561 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4562 false /* requireFullPermission */, false /* checkShell */, "resolve intent"); 4563 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4564 final ResolveInfo bestChoice = 4565 chooseBestActivity(intent, resolvedType, flags, query, userId); 4566 4567 if (isEphemeralAllowed(intent, query, userId)) { 4568 final EphemeralResolveInfo ai = 4569 getEphemeralResolveInfo(intent, resolvedType, userId); 4570 if (ai != null) { 4571 if (DEBUG_EPHEMERAL) { 4572 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4573 } 4574 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4575 bestChoice.ephemeralResolveInfo = ai; 4576 } 4577 } 4578 return bestChoice; 4579 } 4580 4581 @Override 4582 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4583 IntentFilter filter, int match, ComponentName activity) { 4584 final int userId = UserHandle.getCallingUserId(); 4585 if (DEBUG_PREFERRED) { 4586 Log.v(TAG, "setLastChosenActivity intent=" + intent 4587 + " resolvedType=" + resolvedType 4588 + " flags=" + flags 4589 + " filter=" + filter 4590 + " match=" + match 4591 + " activity=" + activity); 4592 filter.dump(new PrintStreamPrinter(System.out), " "); 4593 } 4594 intent.setComponent(null); 4595 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4596 // Find any earlier preferred or last chosen entries and nuke them 4597 findPreferredActivity(intent, resolvedType, 4598 flags, query, 0, false, true, false, userId); 4599 // Add the new activity as the last chosen for this filter 4600 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4601 "Setting last chosen"); 4602 } 4603 4604 @Override 4605 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4606 final int userId = UserHandle.getCallingUserId(); 4607 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4608 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4609 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4610 false, false, false, userId); 4611 } 4612 4613 4614 private boolean isEphemeralAllowed( 4615 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4616 // Short circuit and return early if possible. 4617 if (DISABLE_EPHEMERAL_APPS) { 4618 return false; 4619 } 4620 final int callingUser = UserHandle.getCallingUserId(); 4621 if (callingUser != UserHandle.USER_SYSTEM) { 4622 return false; 4623 } 4624 if (mEphemeralResolverConnection == null) { 4625 return false; 4626 } 4627 if (intent.getComponent() != null) { 4628 return false; 4629 } 4630 if (intent.getPackage() != null) { 4631 return false; 4632 } 4633 final boolean isWebUri = hasWebURI(intent); 4634 if (!isWebUri) { 4635 return false; 4636 } 4637 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4638 synchronized (mPackages) { 4639 final int count = resolvedActivites.size(); 4640 for (int n = 0; n < count; n++) { 4641 ResolveInfo info = resolvedActivites.get(n); 4642 String packageName = info.activityInfo.packageName; 4643 PackageSetting ps = mSettings.mPackages.get(packageName); 4644 if (ps != null) { 4645 // Try to get the status from User settings first 4646 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4647 int status = (int) (packedStatus >> 32); 4648 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4649 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4650 if (DEBUG_EPHEMERAL) { 4651 Slog.v(TAG, "DENY ephemeral apps;" 4652 + " pkg: " + packageName + ", status: " + status); 4653 } 4654 return false; 4655 } 4656 } 4657 } 4658 } 4659 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4660 return true; 4661 } 4662 4663 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4664 int userId) { 4665 MessageDigest digest = null; 4666 try { 4667 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4668 } catch (NoSuchAlgorithmException e) { 4669 // If we can't create a digest, ignore ephemeral apps. 4670 return null; 4671 } 4672 4673 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4674 final byte[] digestBytes = digest.digest(hostBytes); 4675 int shaPrefix = 4676 digestBytes[0] << 24 4677 | digestBytes[1] << 16 4678 | digestBytes[2] << 8 4679 | digestBytes[3] << 0; 4680 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4681 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4682 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4683 // No hash prefix match; there are no ephemeral apps for this domain. 4684 return null; 4685 } 4686 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4687 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4688 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4689 continue; 4690 } 4691 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4692 // No filters; this should never happen. 4693 if (filters.isEmpty()) { 4694 continue; 4695 } 4696 // We have a domain match; resolve the filters to see if anything matches. 4697 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4698 for (int j = filters.size() - 1; j >= 0; --j) { 4699 final EphemeralResolveIntentInfo intentInfo = 4700 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4701 ephemeralResolver.addFilter(intentInfo); 4702 } 4703 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4704 intent, resolvedType, false /*defaultOnly*/, userId); 4705 if (!matchedResolveInfoList.isEmpty()) { 4706 return matchedResolveInfoList.get(0); 4707 } 4708 } 4709 // Hash or filter mis-match; no ephemeral apps for this domain. 4710 return null; 4711 } 4712 4713 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4714 int flags, List<ResolveInfo> query, int userId) { 4715 if (query != null) { 4716 final int N = query.size(); 4717 if (N == 1) { 4718 return query.get(0); 4719 } else if (N > 1) { 4720 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4721 // If there is more than one activity with the same priority, 4722 // then let the user decide between them. 4723 ResolveInfo r0 = query.get(0); 4724 ResolveInfo r1 = query.get(1); 4725 if (DEBUG_INTENT_MATCHING || debug) { 4726 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4727 + r1.activityInfo.name + "=" + r1.priority); 4728 } 4729 // If the first activity has a higher priority, or a different 4730 // default, then it is always desirable to pick it. 4731 if (r0.priority != r1.priority 4732 || r0.preferredOrder != r1.preferredOrder 4733 || r0.isDefault != r1.isDefault) { 4734 return query.get(0); 4735 } 4736 // If we have saved a preference for a preferred activity for 4737 // this Intent, use that. 4738 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4739 flags, query, r0.priority, true, false, debug, userId); 4740 if (ri != null) { 4741 return ri; 4742 } 4743 ri = new ResolveInfo(mResolveInfo); 4744 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4745 ri.activityInfo.applicationInfo = new ApplicationInfo( 4746 ri.activityInfo.applicationInfo); 4747 if (userId != 0) { 4748 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4749 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4750 } 4751 // Make sure that the resolver is displayable in car mode 4752 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4753 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4754 return ri; 4755 } 4756 } 4757 return null; 4758 } 4759 4760 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4761 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4762 final int N = query.size(); 4763 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4764 .get(userId); 4765 // Get the list of persistent preferred activities that handle the intent 4766 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4767 List<PersistentPreferredActivity> pprefs = ppir != null 4768 ? ppir.queryIntent(intent, resolvedType, 4769 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4770 : null; 4771 if (pprefs != null && pprefs.size() > 0) { 4772 final int M = pprefs.size(); 4773 for (int i=0; i<M; i++) { 4774 final PersistentPreferredActivity ppa = pprefs.get(i); 4775 if (DEBUG_PREFERRED || debug) { 4776 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4777 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4778 + "\n component=" + ppa.mComponent); 4779 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4780 } 4781 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4782 flags | MATCH_DISABLED_COMPONENTS, userId); 4783 if (DEBUG_PREFERRED || debug) { 4784 Slog.v(TAG, "Found persistent preferred activity:"); 4785 if (ai != null) { 4786 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4787 } else { 4788 Slog.v(TAG, " null"); 4789 } 4790 } 4791 if (ai == null) { 4792 // This previously registered persistent preferred activity 4793 // component is no longer known. Ignore it and do NOT remove it. 4794 continue; 4795 } 4796 for (int j=0; j<N; j++) { 4797 final ResolveInfo ri = query.get(j); 4798 if (!ri.activityInfo.applicationInfo.packageName 4799 .equals(ai.applicationInfo.packageName)) { 4800 continue; 4801 } 4802 if (!ri.activityInfo.name.equals(ai.name)) { 4803 continue; 4804 } 4805 // Found a persistent preference that can handle the intent. 4806 if (DEBUG_PREFERRED || debug) { 4807 Slog.v(TAG, "Returning persistent preferred activity: " + 4808 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4809 } 4810 return ri; 4811 } 4812 } 4813 } 4814 return null; 4815 } 4816 4817 // TODO: handle preferred activities missing while user has amnesia 4818 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4819 List<ResolveInfo> query, int priority, boolean always, 4820 boolean removeMatches, boolean debug, int userId) { 4821 if (!sUserManager.exists(userId)) return null; 4822 flags = updateFlagsForResolve(flags, userId, intent); 4823 // writer 4824 synchronized (mPackages) { 4825 if (intent.getSelector() != null) { 4826 intent = intent.getSelector(); 4827 } 4828 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4829 4830 // Try to find a matching persistent preferred activity. 4831 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4832 debug, userId); 4833 4834 // If a persistent preferred activity matched, use it. 4835 if (pri != null) { 4836 return pri; 4837 } 4838 4839 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4840 // Get the list of preferred activities that handle the intent 4841 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4842 List<PreferredActivity> prefs = pir != null 4843 ? pir.queryIntent(intent, resolvedType, 4844 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4845 : null; 4846 if (prefs != null && prefs.size() > 0) { 4847 boolean changed = false; 4848 try { 4849 // First figure out how good the original match set is. 4850 // We will only allow preferred activities that came 4851 // from the same match quality. 4852 int match = 0; 4853 4854 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4855 4856 final int N = query.size(); 4857 for (int j=0; j<N; j++) { 4858 final ResolveInfo ri = query.get(j); 4859 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4860 + ": 0x" + Integer.toHexString(match)); 4861 if (ri.match > match) { 4862 match = ri.match; 4863 } 4864 } 4865 4866 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4867 + Integer.toHexString(match)); 4868 4869 match &= IntentFilter.MATCH_CATEGORY_MASK; 4870 final int M = prefs.size(); 4871 for (int i=0; i<M; i++) { 4872 final PreferredActivity pa = prefs.get(i); 4873 if (DEBUG_PREFERRED || debug) { 4874 Slog.v(TAG, "Checking PreferredActivity ds=" 4875 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4876 + "\n component=" + pa.mPref.mComponent); 4877 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4878 } 4879 if (pa.mPref.mMatch != match) { 4880 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4881 + Integer.toHexString(pa.mPref.mMatch)); 4882 continue; 4883 } 4884 // If it's not an "always" type preferred activity and that's what we're 4885 // looking for, skip it. 4886 if (always && !pa.mPref.mAlways) { 4887 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4888 continue; 4889 } 4890 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4891 flags | MATCH_DISABLED_COMPONENTS, userId); 4892 if (DEBUG_PREFERRED || debug) { 4893 Slog.v(TAG, "Found preferred activity:"); 4894 if (ai != null) { 4895 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4896 } else { 4897 Slog.v(TAG, " null"); 4898 } 4899 } 4900 if (ai == null) { 4901 // This previously registered preferred activity 4902 // component is no longer known. Most likely an update 4903 // to the app was installed and in the new version this 4904 // component no longer exists. Clean it up by removing 4905 // it from the preferred activities list, and skip it. 4906 Slog.w(TAG, "Removing dangling preferred activity: " 4907 + pa.mPref.mComponent); 4908 pir.removeFilter(pa); 4909 changed = true; 4910 continue; 4911 } 4912 for (int j=0; j<N; j++) { 4913 final ResolveInfo ri = query.get(j); 4914 if (!ri.activityInfo.applicationInfo.packageName 4915 .equals(ai.applicationInfo.packageName)) { 4916 continue; 4917 } 4918 if (!ri.activityInfo.name.equals(ai.name)) { 4919 continue; 4920 } 4921 4922 if (removeMatches) { 4923 pir.removeFilter(pa); 4924 changed = true; 4925 if (DEBUG_PREFERRED) { 4926 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4927 } 4928 break; 4929 } 4930 4931 // Okay we found a previously set preferred or last chosen app. 4932 // If the result set is different from when this 4933 // was created, we need to clear it and re-ask the 4934 // user their preference, if we're looking for an "always" type entry. 4935 if (always && !pa.mPref.sameSet(query)) { 4936 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4937 + intent + " type " + resolvedType); 4938 if (DEBUG_PREFERRED) { 4939 Slog.v(TAG, "Removing preferred activity since set changed " 4940 + pa.mPref.mComponent); 4941 } 4942 pir.removeFilter(pa); 4943 // Re-add the filter as a "last chosen" entry (!always) 4944 PreferredActivity lastChosen = new PreferredActivity( 4945 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4946 pir.addFilter(lastChosen); 4947 changed = true; 4948 return null; 4949 } 4950 4951 // Yay! Either the set matched or we're looking for the last chosen 4952 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4953 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4954 return ri; 4955 } 4956 } 4957 } finally { 4958 if (changed) { 4959 if (DEBUG_PREFERRED) { 4960 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4961 } 4962 scheduleWritePackageRestrictionsLocked(userId); 4963 } 4964 } 4965 } 4966 } 4967 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4968 return null; 4969 } 4970 4971 /* 4972 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4973 */ 4974 @Override 4975 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4976 int targetUserId) { 4977 mContext.enforceCallingOrSelfPermission( 4978 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4979 List<CrossProfileIntentFilter> matches = 4980 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4981 if (matches != null) { 4982 int size = matches.size(); 4983 for (int i = 0; i < size; i++) { 4984 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4985 } 4986 } 4987 if (hasWebURI(intent)) { 4988 // cross-profile app linking works only towards the parent. 4989 final UserInfo parent = getProfileParent(sourceUserId); 4990 synchronized(mPackages) { 4991 int flags = updateFlagsForResolve(0, parent.id, intent); 4992 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4993 intent, resolvedType, flags, sourceUserId, parent.id); 4994 return xpDomainInfo != null; 4995 } 4996 } 4997 return false; 4998 } 4999 5000 private UserInfo getProfileParent(int userId) { 5001 final long identity = Binder.clearCallingIdentity(); 5002 try { 5003 return sUserManager.getProfileParent(userId); 5004 } finally { 5005 Binder.restoreCallingIdentity(identity); 5006 } 5007 } 5008 5009 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5010 String resolvedType, int userId) { 5011 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5012 if (resolver != null) { 5013 return resolver.queryIntent(intent, resolvedType, false, userId); 5014 } 5015 return null; 5016 } 5017 5018 @Override 5019 public List<ResolveInfo> queryIntentActivities(Intent intent, 5020 String resolvedType, int flags, int userId) { 5021 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5022 flags = updateFlagsForResolve(flags, userId, intent); 5023 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5024 false /* requireFullPermission */, false /* checkShell */, 5025 "query intent activities"); 5026 ComponentName comp = intent.getComponent(); 5027 if (comp == null) { 5028 if (intent.getSelector() != null) { 5029 intent = intent.getSelector(); 5030 comp = intent.getComponent(); 5031 } 5032 } 5033 5034 if (comp != null) { 5035 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5036 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5037 if (ai != null) { 5038 final ResolveInfo ri = new ResolveInfo(); 5039 ri.activityInfo = ai; 5040 list.add(ri); 5041 } 5042 return list; 5043 } 5044 5045 // reader 5046 synchronized (mPackages) { 5047 final String pkgName = intent.getPackage(); 5048 if (pkgName == null) { 5049 List<CrossProfileIntentFilter> matchingFilters = 5050 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5051 // Check for results that need to skip the current profile. 5052 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5053 resolvedType, flags, userId); 5054 if (xpResolveInfo != null) { 5055 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5056 result.add(xpResolveInfo); 5057 return filterIfNotSystemUser(result, userId); 5058 } 5059 5060 // Check for results in the current profile. 5061 List<ResolveInfo> result = mActivities.queryIntent( 5062 intent, resolvedType, flags, userId); 5063 result = filterIfNotSystemUser(result, userId); 5064 5065 // Check for cross profile results. 5066 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5067 xpResolveInfo = queryCrossProfileIntents( 5068 matchingFilters, intent, resolvedType, flags, userId, 5069 hasNonNegativePriorityResult); 5070 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5071 boolean isVisibleToUser = filterIfNotSystemUser( 5072 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5073 if (isVisibleToUser) { 5074 result.add(xpResolveInfo); 5075 Collections.sort(result, mResolvePrioritySorter); 5076 } 5077 } 5078 if (hasWebURI(intent)) { 5079 CrossProfileDomainInfo xpDomainInfo = null; 5080 final UserInfo parent = getProfileParent(userId); 5081 if (parent != null) { 5082 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5083 flags, userId, parent.id); 5084 } 5085 if (xpDomainInfo != null) { 5086 if (xpResolveInfo != null) { 5087 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5088 // in the result. 5089 result.remove(xpResolveInfo); 5090 } 5091 if (result.size() == 0) { 5092 result.add(xpDomainInfo.resolveInfo); 5093 return result; 5094 } 5095 } else if (result.size() <= 1) { 5096 return result; 5097 } 5098 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5099 xpDomainInfo, userId); 5100 Collections.sort(result, mResolvePrioritySorter); 5101 } 5102 return result; 5103 } 5104 final PackageParser.Package pkg = mPackages.get(pkgName); 5105 if (pkg != null) { 5106 return filterIfNotSystemUser( 5107 mActivities.queryIntentForPackage( 5108 intent, resolvedType, flags, pkg.activities, userId), 5109 userId); 5110 } 5111 return new ArrayList<ResolveInfo>(); 5112 } 5113 } 5114 5115 private static class CrossProfileDomainInfo { 5116 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5117 ResolveInfo resolveInfo; 5118 /* Best domain verification status of the activities found in the other profile */ 5119 int bestDomainVerificationStatus; 5120 } 5121 5122 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5123 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5124 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5125 sourceUserId)) { 5126 return null; 5127 } 5128 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5129 resolvedType, flags, parentUserId); 5130 5131 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5132 return null; 5133 } 5134 CrossProfileDomainInfo result = null; 5135 int size = resultTargetUser.size(); 5136 for (int i = 0; i < size; i++) { 5137 ResolveInfo riTargetUser = resultTargetUser.get(i); 5138 // Intent filter verification is only for filters that specify a host. So don't return 5139 // those that handle all web uris. 5140 if (riTargetUser.handleAllWebDataURI) { 5141 continue; 5142 } 5143 String packageName = riTargetUser.activityInfo.packageName; 5144 PackageSetting ps = mSettings.mPackages.get(packageName); 5145 if (ps == null) { 5146 continue; 5147 } 5148 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5149 int status = (int)(verificationState >> 32); 5150 if (result == null) { 5151 result = new CrossProfileDomainInfo(); 5152 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5153 sourceUserId, parentUserId); 5154 result.bestDomainVerificationStatus = status; 5155 } else { 5156 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5157 result.bestDomainVerificationStatus); 5158 } 5159 } 5160 // Don't consider matches with status NEVER across profiles. 5161 if (result != null && result.bestDomainVerificationStatus 5162 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5163 return null; 5164 } 5165 return result; 5166 } 5167 5168 /** 5169 * Verification statuses are ordered from the worse to the best, except for 5170 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5171 */ 5172 private int bestDomainVerificationStatus(int status1, int status2) { 5173 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5174 return status2; 5175 } 5176 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5177 return status1; 5178 } 5179 return (int) MathUtils.max(status1, status2); 5180 } 5181 5182 private boolean isUserEnabled(int userId) { 5183 long callingId = Binder.clearCallingIdentity(); 5184 try { 5185 UserInfo userInfo = sUserManager.getUserInfo(userId); 5186 return userInfo != null && userInfo.isEnabled(); 5187 } finally { 5188 Binder.restoreCallingIdentity(callingId); 5189 } 5190 } 5191 5192 /** 5193 * Filter out activities with systemUserOnly flag set, when current user is not System. 5194 * 5195 * @return filtered list 5196 */ 5197 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5198 if (userId == UserHandle.USER_SYSTEM) { 5199 return resolveInfos; 5200 } 5201 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5202 ResolveInfo info = resolveInfos.get(i); 5203 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5204 resolveInfos.remove(i); 5205 } 5206 } 5207 return resolveInfos; 5208 } 5209 5210 /** 5211 * @param resolveInfos list of resolve infos in descending priority order 5212 * @return if the list contains a resolve info with non-negative priority 5213 */ 5214 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5215 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5216 } 5217 5218 private static boolean hasWebURI(Intent intent) { 5219 if (intent.getData() == null) { 5220 return false; 5221 } 5222 final String scheme = intent.getScheme(); 5223 if (TextUtils.isEmpty(scheme)) { 5224 return false; 5225 } 5226 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5227 } 5228 5229 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5230 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5231 int userId) { 5232 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5233 5234 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5235 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5236 candidates.size()); 5237 } 5238 5239 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5240 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5241 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5242 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5243 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5244 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5245 5246 synchronized (mPackages) { 5247 final int count = candidates.size(); 5248 // First, try to use linked apps. Partition the candidates into four lists: 5249 // one for the final results, one for the "do not use ever", one for "undefined status" 5250 // and finally one for "browser app type". 5251 for (int n=0; n<count; n++) { 5252 ResolveInfo info = candidates.get(n); 5253 String packageName = info.activityInfo.packageName; 5254 PackageSetting ps = mSettings.mPackages.get(packageName); 5255 if (ps != null) { 5256 // Add to the special match all list (Browser use case) 5257 if (info.handleAllWebDataURI) { 5258 matchAllList.add(info); 5259 continue; 5260 } 5261 // Try to get the status from User settings first 5262 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5263 int status = (int)(packedStatus >> 32); 5264 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5265 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5266 if (DEBUG_DOMAIN_VERIFICATION) { 5267 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5268 + " : linkgen=" + linkGeneration); 5269 } 5270 // Use link-enabled generation as preferredOrder, i.e. 5271 // prefer newly-enabled over earlier-enabled. 5272 info.preferredOrder = linkGeneration; 5273 alwaysList.add(info); 5274 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5275 if (DEBUG_DOMAIN_VERIFICATION) { 5276 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5277 } 5278 neverList.add(info); 5279 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5280 if (DEBUG_DOMAIN_VERIFICATION) { 5281 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5282 } 5283 alwaysAskList.add(info); 5284 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5285 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5286 if (DEBUG_DOMAIN_VERIFICATION) { 5287 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5288 } 5289 undefinedList.add(info); 5290 } 5291 } 5292 } 5293 5294 // We'll want to include browser possibilities in a few cases 5295 boolean includeBrowser = false; 5296 5297 // First try to add the "always" resolution(s) for the current user, if any 5298 if (alwaysList.size() > 0) { 5299 result.addAll(alwaysList); 5300 } else { 5301 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5302 result.addAll(undefinedList); 5303 // Maybe add one for the other profile. 5304 if (xpDomainInfo != null && ( 5305 xpDomainInfo.bestDomainVerificationStatus 5306 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5307 result.add(xpDomainInfo.resolveInfo); 5308 } 5309 includeBrowser = true; 5310 } 5311 5312 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5313 // If there were 'always' entries their preferred order has been set, so we also 5314 // back that off to make the alternatives equivalent 5315 if (alwaysAskList.size() > 0) { 5316 for (ResolveInfo i : result) { 5317 i.preferredOrder = 0; 5318 } 5319 result.addAll(alwaysAskList); 5320 includeBrowser = true; 5321 } 5322 5323 if (includeBrowser) { 5324 // Also add browsers (all of them or only the default one) 5325 if (DEBUG_DOMAIN_VERIFICATION) { 5326 Slog.v(TAG, " ...including browsers in candidate set"); 5327 } 5328 if ((matchFlags & MATCH_ALL) != 0) { 5329 result.addAll(matchAllList); 5330 } else { 5331 // Browser/generic handling case. If there's a default browser, go straight 5332 // to that (but only if there is no other higher-priority match). 5333 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5334 int maxMatchPrio = 0; 5335 ResolveInfo defaultBrowserMatch = null; 5336 final int numCandidates = matchAllList.size(); 5337 for (int n = 0; n < numCandidates; n++) { 5338 ResolveInfo info = matchAllList.get(n); 5339 // track the highest overall match priority... 5340 if (info.priority > maxMatchPrio) { 5341 maxMatchPrio = info.priority; 5342 } 5343 // ...and the highest-priority default browser match 5344 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5345 if (defaultBrowserMatch == null 5346 || (defaultBrowserMatch.priority < info.priority)) { 5347 if (debug) { 5348 Slog.v(TAG, "Considering default browser match " + info); 5349 } 5350 defaultBrowserMatch = info; 5351 } 5352 } 5353 } 5354 if (defaultBrowserMatch != null 5355 && defaultBrowserMatch.priority >= maxMatchPrio 5356 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5357 { 5358 if (debug) { 5359 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5360 } 5361 result.add(defaultBrowserMatch); 5362 } else { 5363 result.addAll(matchAllList); 5364 } 5365 } 5366 5367 // If there is nothing selected, add all candidates and remove the ones that the user 5368 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5369 if (result.size() == 0) { 5370 result.addAll(candidates); 5371 result.removeAll(neverList); 5372 } 5373 } 5374 } 5375 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5376 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5377 result.size()); 5378 for (ResolveInfo info : result) { 5379 Slog.v(TAG, " + " + info.activityInfo); 5380 } 5381 } 5382 return result; 5383 } 5384 5385 // Returns a packed value as a long: 5386 // 5387 // high 'int'-sized word: link status: undefined/ask/never/always. 5388 // low 'int'-sized word: relative priority among 'always' results. 5389 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5390 long result = ps.getDomainVerificationStatusForUser(userId); 5391 // if none available, get the master status 5392 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5393 if (ps.getIntentFilterVerificationInfo() != null) { 5394 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5395 } 5396 } 5397 return result; 5398 } 5399 5400 private ResolveInfo querySkipCurrentProfileIntents( 5401 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5402 int flags, int sourceUserId) { 5403 if (matchingFilters != null) { 5404 int size = matchingFilters.size(); 5405 for (int i = 0; i < size; i ++) { 5406 CrossProfileIntentFilter filter = matchingFilters.get(i); 5407 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5408 // Checking if there are activities in the target user that can handle the 5409 // intent. 5410 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5411 resolvedType, flags, sourceUserId); 5412 if (resolveInfo != null) { 5413 return resolveInfo; 5414 } 5415 } 5416 } 5417 } 5418 return null; 5419 } 5420 5421 // Return matching ResolveInfo in target user if any. 5422 private ResolveInfo queryCrossProfileIntents( 5423 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5424 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5425 if (matchingFilters != null) { 5426 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5427 // match the same intent. For performance reasons, it is better not to 5428 // run queryIntent twice for the same userId 5429 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5430 int size = matchingFilters.size(); 5431 for (int i = 0; i < size; i++) { 5432 CrossProfileIntentFilter filter = matchingFilters.get(i); 5433 int targetUserId = filter.getTargetUserId(); 5434 boolean skipCurrentProfile = 5435 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5436 boolean skipCurrentProfileIfNoMatchFound = 5437 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5438 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5439 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5440 // Checking if there are activities in the target user that can handle the 5441 // intent. 5442 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5443 resolvedType, flags, sourceUserId); 5444 if (resolveInfo != null) return resolveInfo; 5445 alreadyTriedUserIds.put(targetUserId, true); 5446 } 5447 } 5448 } 5449 return null; 5450 } 5451 5452 /** 5453 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5454 * will forward the intent to the filter's target user. 5455 * Otherwise, returns null. 5456 */ 5457 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5458 String resolvedType, int flags, int sourceUserId) { 5459 int targetUserId = filter.getTargetUserId(); 5460 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5461 resolvedType, flags, targetUserId); 5462 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5463 // If all the matches in the target profile are suspended, return null. 5464 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5465 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5466 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5467 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5468 targetUserId); 5469 } 5470 } 5471 } 5472 return null; 5473 } 5474 5475 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5476 int sourceUserId, int targetUserId) { 5477 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5478 long ident = Binder.clearCallingIdentity(); 5479 boolean targetIsProfile; 5480 try { 5481 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5482 } finally { 5483 Binder.restoreCallingIdentity(ident); 5484 } 5485 String className; 5486 if (targetIsProfile) { 5487 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5488 } else { 5489 className = FORWARD_INTENT_TO_PARENT; 5490 } 5491 ComponentName forwardingActivityComponentName = new ComponentName( 5492 mAndroidApplication.packageName, className); 5493 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5494 sourceUserId); 5495 if (!targetIsProfile) { 5496 forwardingActivityInfo.showUserIcon = targetUserId; 5497 forwardingResolveInfo.noResourceId = true; 5498 } 5499 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5500 forwardingResolveInfo.priority = 0; 5501 forwardingResolveInfo.preferredOrder = 0; 5502 forwardingResolveInfo.match = 0; 5503 forwardingResolveInfo.isDefault = true; 5504 forwardingResolveInfo.filter = filter; 5505 forwardingResolveInfo.targetUserId = targetUserId; 5506 return forwardingResolveInfo; 5507 } 5508 5509 @Override 5510 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5511 Intent[] specifics, String[] specificTypes, Intent intent, 5512 String resolvedType, int flags, int userId) { 5513 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5514 flags = updateFlagsForResolve(flags, userId, intent); 5515 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5516 false /* requireFullPermission */, false /* checkShell */, 5517 "query intent activity options"); 5518 final String resultsAction = intent.getAction(); 5519 5520 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5521 | PackageManager.GET_RESOLVED_FILTER, userId); 5522 5523 if (DEBUG_INTENT_MATCHING) { 5524 Log.v(TAG, "Query " + intent + ": " + results); 5525 } 5526 5527 int specificsPos = 0; 5528 int N; 5529 5530 // todo: note that the algorithm used here is O(N^2). This 5531 // isn't a problem in our current environment, but if we start running 5532 // into situations where we have more than 5 or 10 matches then this 5533 // should probably be changed to something smarter... 5534 5535 // First we go through and resolve each of the specific items 5536 // that were supplied, taking care of removing any corresponding 5537 // duplicate items in the generic resolve list. 5538 if (specifics != null) { 5539 for (int i=0; i<specifics.length; i++) { 5540 final Intent sintent = specifics[i]; 5541 if (sintent == null) { 5542 continue; 5543 } 5544 5545 if (DEBUG_INTENT_MATCHING) { 5546 Log.v(TAG, "Specific #" + i + ": " + sintent); 5547 } 5548 5549 String action = sintent.getAction(); 5550 if (resultsAction != null && resultsAction.equals(action)) { 5551 // If this action was explicitly requested, then don't 5552 // remove things that have it. 5553 action = null; 5554 } 5555 5556 ResolveInfo ri = null; 5557 ActivityInfo ai = null; 5558 5559 ComponentName comp = sintent.getComponent(); 5560 if (comp == null) { 5561 ri = resolveIntent( 5562 sintent, 5563 specificTypes != null ? specificTypes[i] : null, 5564 flags, userId); 5565 if (ri == null) { 5566 continue; 5567 } 5568 if (ri == mResolveInfo) { 5569 // ACK! Must do something better with this. 5570 } 5571 ai = ri.activityInfo; 5572 comp = new ComponentName(ai.applicationInfo.packageName, 5573 ai.name); 5574 } else { 5575 ai = getActivityInfo(comp, flags, userId); 5576 if (ai == null) { 5577 continue; 5578 } 5579 } 5580 5581 // Look for any generic query activities that are duplicates 5582 // of this specific one, and remove them from the results. 5583 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5584 N = results.size(); 5585 int j; 5586 for (j=specificsPos; j<N; j++) { 5587 ResolveInfo sri = results.get(j); 5588 if ((sri.activityInfo.name.equals(comp.getClassName()) 5589 && sri.activityInfo.applicationInfo.packageName.equals( 5590 comp.getPackageName())) 5591 || (action != null && sri.filter.matchAction(action))) { 5592 results.remove(j); 5593 if (DEBUG_INTENT_MATCHING) Log.v( 5594 TAG, "Removing duplicate item from " + j 5595 + " due to specific " + specificsPos); 5596 if (ri == null) { 5597 ri = sri; 5598 } 5599 j--; 5600 N--; 5601 } 5602 } 5603 5604 // Add this specific item to its proper place. 5605 if (ri == null) { 5606 ri = new ResolveInfo(); 5607 ri.activityInfo = ai; 5608 } 5609 results.add(specificsPos, ri); 5610 ri.specificIndex = i; 5611 specificsPos++; 5612 } 5613 } 5614 5615 // Now we go through the remaining generic results and remove any 5616 // duplicate actions that are found here. 5617 N = results.size(); 5618 for (int i=specificsPos; i<N-1; i++) { 5619 final ResolveInfo rii = results.get(i); 5620 if (rii.filter == null) { 5621 continue; 5622 } 5623 5624 // Iterate over all of the actions of this result's intent 5625 // filter... typically this should be just one. 5626 final Iterator<String> it = rii.filter.actionsIterator(); 5627 if (it == null) { 5628 continue; 5629 } 5630 while (it.hasNext()) { 5631 final String action = it.next(); 5632 if (resultsAction != null && resultsAction.equals(action)) { 5633 // If this action was explicitly requested, then don't 5634 // remove things that have it. 5635 continue; 5636 } 5637 for (int j=i+1; j<N; j++) { 5638 final ResolveInfo rij = results.get(j); 5639 if (rij.filter != null && rij.filter.hasAction(action)) { 5640 results.remove(j); 5641 if (DEBUG_INTENT_MATCHING) Log.v( 5642 TAG, "Removing duplicate item from " + j 5643 + " due to action " + action + " at " + i); 5644 j--; 5645 N--; 5646 } 5647 } 5648 } 5649 5650 // If the caller didn't request filter information, drop it now 5651 // so we don't have to marshall/unmarshall it. 5652 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5653 rii.filter = null; 5654 } 5655 } 5656 5657 // Filter out the caller activity if so requested. 5658 if (caller != null) { 5659 N = results.size(); 5660 for (int i=0; i<N; i++) { 5661 ActivityInfo ainfo = results.get(i).activityInfo; 5662 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5663 && caller.getClassName().equals(ainfo.name)) { 5664 results.remove(i); 5665 break; 5666 } 5667 } 5668 } 5669 5670 // If the caller didn't request filter information, 5671 // drop them now so we don't have to 5672 // marshall/unmarshall it. 5673 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5674 N = results.size(); 5675 for (int i=0; i<N; i++) { 5676 results.get(i).filter = null; 5677 } 5678 } 5679 5680 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5681 return results; 5682 } 5683 5684 @Override 5685 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5686 int userId) { 5687 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5688 flags = updateFlagsForResolve(flags, userId, intent); 5689 ComponentName comp = intent.getComponent(); 5690 if (comp == null) { 5691 if (intent.getSelector() != null) { 5692 intent = intent.getSelector(); 5693 comp = intent.getComponent(); 5694 } 5695 } 5696 if (comp != null) { 5697 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5698 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5699 if (ai != null) { 5700 ResolveInfo ri = new ResolveInfo(); 5701 ri.activityInfo = ai; 5702 list.add(ri); 5703 } 5704 return list; 5705 } 5706 5707 // reader 5708 synchronized (mPackages) { 5709 String pkgName = intent.getPackage(); 5710 if (pkgName == null) { 5711 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5712 } 5713 final PackageParser.Package pkg = mPackages.get(pkgName); 5714 if (pkg != null) { 5715 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5716 userId); 5717 } 5718 return null; 5719 } 5720 } 5721 5722 @Override 5723 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5724 if (!sUserManager.exists(userId)) return null; 5725 flags = updateFlagsForResolve(flags, userId, intent); 5726 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5727 if (query != null) { 5728 if (query.size() >= 1) { 5729 // If there is more than one service with the same priority, 5730 // just arbitrarily pick the first one. 5731 return query.get(0); 5732 } 5733 } 5734 return null; 5735 } 5736 5737 @Override 5738 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5739 int userId) { 5740 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5741 flags = updateFlagsForResolve(flags, userId, intent); 5742 ComponentName comp = intent.getComponent(); 5743 if (comp == null) { 5744 if (intent.getSelector() != null) { 5745 intent = intent.getSelector(); 5746 comp = intent.getComponent(); 5747 } 5748 } 5749 if (comp != null) { 5750 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5751 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5752 if (si != null) { 5753 final ResolveInfo ri = new ResolveInfo(); 5754 ri.serviceInfo = si; 5755 list.add(ri); 5756 } 5757 return list; 5758 } 5759 5760 // reader 5761 synchronized (mPackages) { 5762 String pkgName = intent.getPackage(); 5763 if (pkgName == null) { 5764 return mServices.queryIntent(intent, resolvedType, flags, userId); 5765 } 5766 final PackageParser.Package pkg = mPackages.get(pkgName); 5767 if (pkg != null) { 5768 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5769 userId); 5770 } 5771 return null; 5772 } 5773 } 5774 5775 @Override 5776 public List<ResolveInfo> queryIntentContentProviders( 5777 Intent intent, String resolvedType, int flags, int userId) { 5778 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5779 flags = updateFlagsForResolve(flags, userId, intent); 5780 ComponentName comp = intent.getComponent(); 5781 if (comp == null) { 5782 if (intent.getSelector() != null) { 5783 intent = intent.getSelector(); 5784 comp = intent.getComponent(); 5785 } 5786 } 5787 if (comp != null) { 5788 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5789 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5790 if (pi != null) { 5791 final ResolveInfo ri = new ResolveInfo(); 5792 ri.providerInfo = pi; 5793 list.add(ri); 5794 } 5795 return list; 5796 } 5797 5798 // reader 5799 synchronized (mPackages) { 5800 String pkgName = intent.getPackage(); 5801 if (pkgName == null) { 5802 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5803 } 5804 final PackageParser.Package pkg = mPackages.get(pkgName); 5805 if (pkg != null) { 5806 return mProviders.queryIntentForPackage( 5807 intent, resolvedType, flags, pkg.providers, userId); 5808 } 5809 return null; 5810 } 5811 } 5812 5813 @Override 5814 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5815 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5816 flags = updateFlagsForPackage(flags, userId, null); 5817 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5818 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5819 true /* requireFullPermission */, false /* checkShell */, 5820 "get installed packages"); 5821 5822 // writer 5823 synchronized (mPackages) { 5824 ArrayList<PackageInfo> list; 5825 if (listUninstalled) { 5826 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5827 for (PackageSetting ps : mSettings.mPackages.values()) { 5828 PackageInfo pi; 5829 if (ps.pkg != null) { 5830 pi = generatePackageInfo(ps.pkg, flags, userId); 5831 } else { 5832 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5833 } 5834 if (pi != null) { 5835 list.add(pi); 5836 } 5837 } 5838 } else { 5839 list = new ArrayList<PackageInfo>(mPackages.size()); 5840 for (PackageParser.Package p : mPackages.values()) { 5841 PackageInfo pi = generatePackageInfo(p, flags, userId); 5842 if (pi != null) { 5843 list.add(pi); 5844 } 5845 } 5846 } 5847 5848 return new ParceledListSlice<PackageInfo>(list); 5849 } 5850 } 5851 5852 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5853 String[] permissions, boolean[] tmp, int flags, int userId) { 5854 int numMatch = 0; 5855 final PermissionsState permissionsState = ps.getPermissionsState(); 5856 for (int i=0; i<permissions.length; i++) { 5857 final String permission = permissions[i]; 5858 if (permissionsState.hasPermission(permission, userId)) { 5859 tmp[i] = true; 5860 numMatch++; 5861 } else { 5862 tmp[i] = false; 5863 } 5864 } 5865 if (numMatch == 0) { 5866 return; 5867 } 5868 PackageInfo pi; 5869 if (ps.pkg != null) { 5870 pi = generatePackageInfo(ps.pkg, flags, userId); 5871 } else { 5872 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5873 } 5874 // The above might return null in cases of uninstalled apps or install-state 5875 // skew across users/profiles. 5876 if (pi != null) { 5877 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5878 if (numMatch == permissions.length) { 5879 pi.requestedPermissions = permissions; 5880 } else { 5881 pi.requestedPermissions = new String[numMatch]; 5882 numMatch = 0; 5883 for (int i=0; i<permissions.length; i++) { 5884 if (tmp[i]) { 5885 pi.requestedPermissions[numMatch] = permissions[i]; 5886 numMatch++; 5887 } 5888 } 5889 } 5890 } 5891 list.add(pi); 5892 } 5893 } 5894 5895 @Override 5896 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5897 String[] permissions, int flags, int userId) { 5898 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5899 flags = updateFlagsForPackage(flags, userId, permissions); 5900 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5901 5902 // writer 5903 synchronized (mPackages) { 5904 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5905 boolean[] tmpBools = new boolean[permissions.length]; 5906 if (listUninstalled) { 5907 for (PackageSetting ps : mSettings.mPackages.values()) { 5908 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5909 } 5910 } else { 5911 for (PackageParser.Package pkg : mPackages.values()) { 5912 PackageSetting ps = (PackageSetting)pkg.mExtras; 5913 if (ps != null) { 5914 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5915 userId); 5916 } 5917 } 5918 } 5919 5920 return new ParceledListSlice<PackageInfo>(list); 5921 } 5922 } 5923 5924 @Override 5925 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5926 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5927 flags = updateFlagsForApplication(flags, userId, null); 5928 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5929 5930 // writer 5931 synchronized (mPackages) { 5932 ArrayList<ApplicationInfo> list; 5933 if (listUninstalled) { 5934 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5935 for (PackageSetting ps : mSettings.mPackages.values()) { 5936 ApplicationInfo ai; 5937 if (ps.pkg != null) { 5938 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5939 ps.readUserState(userId), userId); 5940 } else { 5941 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5942 } 5943 if (ai != null) { 5944 list.add(ai); 5945 } 5946 } 5947 } else { 5948 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5949 for (PackageParser.Package p : mPackages.values()) { 5950 if (p.mExtras != null) { 5951 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5952 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5953 if (ai != null) { 5954 list.add(ai); 5955 } 5956 } 5957 } 5958 } 5959 5960 return new ParceledListSlice<ApplicationInfo>(list); 5961 } 5962 } 5963 5964 @Override 5965 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5966 if (DISABLE_EPHEMERAL_APPS) { 5967 return null; 5968 } 5969 5970 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5971 "getEphemeralApplications"); 5972 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5973 true /* requireFullPermission */, false /* checkShell */, 5974 "getEphemeralApplications"); 5975 synchronized (mPackages) { 5976 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5977 .getEphemeralApplicationsLPw(userId); 5978 if (ephemeralApps != null) { 5979 return new ParceledListSlice<>(ephemeralApps); 5980 } 5981 } 5982 return null; 5983 } 5984 5985 @Override 5986 public boolean isEphemeralApplication(String packageName, int userId) { 5987 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5988 true /* requireFullPermission */, false /* checkShell */, 5989 "isEphemeral"); 5990 if (DISABLE_EPHEMERAL_APPS) { 5991 return false; 5992 } 5993 5994 if (!isCallerSameApp(packageName)) { 5995 return false; 5996 } 5997 synchronized (mPackages) { 5998 PackageParser.Package pkg = mPackages.get(packageName); 5999 if (pkg != null) { 6000 return pkg.applicationInfo.isEphemeralApp(); 6001 } 6002 } 6003 return false; 6004 } 6005 6006 @Override 6007 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6008 if (DISABLE_EPHEMERAL_APPS) { 6009 return null; 6010 } 6011 6012 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6013 true /* requireFullPermission */, false /* checkShell */, 6014 "getCookie"); 6015 if (!isCallerSameApp(packageName)) { 6016 return null; 6017 } 6018 synchronized (mPackages) { 6019 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6020 packageName, userId); 6021 } 6022 } 6023 6024 @Override 6025 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6026 if (DISABLE_EPHEMERAL_APPS) { 6027 return true; 6028 } 6029 6030 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6031 true /* requireFullPermission */, true /* checkShell */, 6032 "setCookie"); 6033 if (!isCallerSameApp(packageName)) { 6034 return false; 6035 } 6036 synchronized (mPackages) { 6037 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6038 packageName, cookie, userId); 6039 } 6040 } 6041 6042 @Override 6043 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6044 if (DISABLE_EPHEMERAL_APPS) { 6045 return null; 6046 } 6047 6048 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6049 "getEphemeralApplicationIcon"); 6050 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6051 true /* requireFullPermission */, false /* checkShell */, 6052 "getEphemeralApplicationIcon"); 6053 synchronized (mPackages) { 6054 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6055 packageName, userId); 6056 } 6057 } 6058 6059 private boolean isCallerSameApp(String packageName) { 6060 PackageParser.Package pkg = mPackages.get(packageName); 6061 return pkg != null 6062 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6063 } 6064 6065 public List<ApplicationInfo> getPersistentApplications(int flags) { 6066 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6067 6068 // reader 6069 synchronized (mPackages) { 6070 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6071 final int userId = UserHandle.getCallingUserId(); 6072 while (i.hasNext()) { 6073 final PackageParser.Package p = i.next(); 6074 if (p.applicationInfo != null 6075 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 6076 && (!mSafeMode || isSystemApp(p))) { 6077 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6078 if (ps != null) { 6079 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6080 ps.readUserState(userId), userId); 6081 if (ai != null) { 6082 finalList.add(ai); 6083 } 6084 } 6085 } 6086 } 6087 } 6088 6089 return finalList; 6090 } 6091 6092 @Override 6093 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6094 if (!sUserManager.exists(userId)) return null; 6095 flags = updateFlagsForComponent(flags, userId, name); 6096 // reader 6097 synchronized (mPackages) { 6098 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6099 PackageSetting ps = provider != null 6100 ? mSettings.mPackages.get(provider.owner.packageName) 6101 : null; 6102 return ps != null 6103 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6104 ? PackageParser.generateProviderInfo(provider, flags, 6105 ps.readUserState(userId), userId) 6106 : null; 6107 } 6108 } 6109 6110 /** 6111 * @deprecated 6112 */ 6113 @Deprecated 6114 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6115 // reader 6116 synchronized (mPackages) { 6117 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6118 .entrySet().iterator(); 6119 final int userId = UserHandle.getCallingUserId(); 6120 while (i.hasNext()) { 6121 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6122 PackageParser.Provider p = entry.getValue(); 6123 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6124 6125 if (ps != null && p.syncable 6126 && (!mSafeMode || (p.info.applicationInfo.flags 6127 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6128 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6129 ps.readUserState(userId), userId); 6130 if (info != null) { 6131 outNames.add(entry.getKey()); 6132 outInfo.add(info); 6133 } 6134 } 6135 } 6136 } 6137 } 6138 6139 @Override 6140 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6141 int uid, int flags) { 6142 final int userId = processName != null ? UserHandle.getUserId(uid) 6143 : UserHandle.getCallingUserId(); 6144 if (!sUserManager.exists(userId)) return null; 6145 flags = updateFlagsForComponent(flags, userId, processName); 6146 6147 ArrayList<ProviderInfo> finalList = null; 6148 // reader 6149 synchronized (mPackages) { 6150 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6151 while (i.hasNext()) { 6152 final PackageParser.Provider p = i.next(); 6153 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6154 if (ps != null && p.info.authority != null 6155 && (processName == null 6156 || (p.info.processName.equals(processName) 6157 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6158 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6159 if (finalList == null) { 6160 finalList = new ArrayList<ProviderInfo>(3); 6161 } 6162 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6163 ps.readUserState(userId), userId); 6164 if (info != null) { 6165 finalList.add(info); 6166 } 6167 } 6168 } 6169 } 6170 6171 if (finalList != null) { 6172 Collections.sort(finalList, mProviderInitOrderSorter); 6173 return new ParceledListSlice<ProviderInfo>(finalList); 6174 } 6175 6176 return null; 6177 } 6178 6179 @Override 6180 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6181 // reader 6182 synchronized (mPackages) { 6183 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6184 return PackageParser.generateInstrumentationInfo(i, flags); 6185 } 6186 } 6187 6188 @Override 6189 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6190 int flags) { 6191 ArrayList<InstrumentationInfo> finalList = 6192 new ArrayList<InstrumentationInfo>(); 6193 6194 // reader 6195 synchronized (mPackages) { 6196 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6197 while (i.hasNext()) { 6198 final PackageParser.Instrumentation p = i.next(); 6199 if (targetPackage == null 6200 || targetPackage.equals(p.info.targetPackage)) { 6201 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6202 flags); 6203 if (ii != null) { 6204 finalList.add(ii); 6205 } 6206 } 6207 } 6208 } 6209 6210 return finalList; 6211 } 6212 6213 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6214 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6215 if (overlays == null) { 6216 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6217 return; 6218 } 6219 for (PackageParser.Package opkg : overlays.values()) { 6220 // Not much to do if idmap fails: we already logged the error 6221 // and we certainly don't want to abort installation of pkg simply 6222 // because an overlay didn't fit properly. For these reasons, 6223 // ignore the return value of createIdmapForPackagePairLI. 6224 createIdmapForPackagePairLI(pkg, opkg); 6225 } 6226 } 6227 6228 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6229 PackageParser.Package opkg) { 6230 if (!opkg.mTrustedOverlay) { 6231 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6232 opkg.baseCodePath + ": overlay not trusted"); 6233 return false; 6234 } 6235 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6236 if (overlaySet == null) { 6237 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6238 opkg.baseCodePath + " but target package has no known overlays"); 6239 return false; 6240 } 6241 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6242 // TODO: generate idmap for split APKs 6243 try { 6244 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6245 } catch (InstallerException e) { 6246 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6247 + opkg.baseCodePath); 6248 return false; 6249 } 6250 PackageParser.Package[] overlayArray = 6251 overlaySet.values().toArray(new PackageParser.Package[0]); 6252 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6253 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6254 return p1.mOverlayPriority - p2.mOverlayPriority; 6255 } 6256 }; 6257 Arrays.sort(overlayArray, cmp); 6258 6259 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6260 int i = 0; 6261 for (PackageParser.Package p : overlayArray) { 6262 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6263 } 6264 return true; 6265 } 6266 6267 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6268 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6269 try { 6270 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6271 } finally { 6272 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6273 } 6274 } 6275 6276 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6277 final File[] files = dir.listFiles(); 6278 if (ArrayUtils.isEmpty(files)) { 6279 Log.d(TAG, "No files in app dir " + dir); 6280 return; 6281 } 6282 6283 if (DEBUG_PACKAGE_SCANNING) { 6284 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6285 + " flags=0x" + Integer.toHexString(parseFlags)); 6286 } 6287 6288 for (File file : files) { 6289 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6290 && !PackageInstallerService.isStageName(file.getName()); 6291 if (!isPackage) { 6292 // Ignore entries which are not packages 6293 continue; 6294 } 6295 try { 6296 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6297 scanFlags, currentTime, null); 6298 } catch (PackageManagerException e) { 6299 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6300 6301 // Delete invalid userdata apps 6302 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6303 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6304 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6305 removeCodePathLI(file); 6306 } 6307 } 6308 } 6309 } 6310 6311 private static File getSettingsProblemFile() { 6312 File dataDir = Environment.getDataDirectory(); 6313 File systemDir = new File(dataDir, "system"); 6314 File fname = new File(systemDir, "uiderrors.txt"); 6315 return fname; 6316 } 6317 6318 static void reportSettingsProblem(int priority, String msg) { 6319 logCriticalInfo(priority, msg); 6320 } 6321 6322 static void logCriticalInfo(int priority, String msg) { 6323 Slog.println(priority, TAG, msg); 6324 EventLogTags.writePmCriticalInfo(msg); 6325 try { 6326 File fname = getSettingsProblemFile(); 6327 FileOutputStream out = new FileOutputStream(fname, true); 6328 PrintWriter pw = new FastPrintWriter(out); 6329 SimpleDateFormat formatter = new SimpleDateFormat(); 6330 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6331 pw.println(dateString + ": " + msg); 6332 pw.close(); 6333 FileUtils.setPermissions( 6334 fname.toString(), 6335 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6336 -1, -1); 6337 } catch (java.io.IOException e) { 6338 } 6339 } 6340 6341 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6342 int parseFlags) throws PackageManagerException { 6343 if (ps != null 6344 && ps.codePath.equals(srcFile) 6345 && ps.timeStamp == srcFile.lastModified() 6346 && !isCompatSignatureUpdateNeeded(pkg) 6347 && !isRecoverSignatureUpdateNeeded(pkg)) { 6348 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6349 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6350 ArraySet<PublicKey> signingKs; 6351 synchronized (mPackages) { 6352 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6353 } 6354 if (ps.signatures.mSignatures != null 6355 && ps.signatures.mSignatures.length != 0 6356 && signingKs != null) { 6357 // Optimization: reuse the existing cached certificates 6358 // if the package appears to be unchanged. 6359 pkg.mSignatures = ps.signatures.mSignatures; 6360 pkg.mSigningKeys = signingKs; 6361 return; 6362 } 6363 6364 Slog.w(TAG, "PackageSetting for " + ps.name 6365 + " is missing signatures. Collecting certs again to recover them."); 6366 } else { 6367 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6368 } 6369 6370 try { 6371 PackageParser.collectCertificates(pkg, parseFlags); 6372 } catch (PackageParserException e) { 6373 throw PackageManagerException.from(e); 6374 } 6375 } 6376 6377 /** 6378 * Traces a package scan. 6379 * @see #scanPackageLI(File, int, int, long, UserHandle) 6380 */ 6381 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6382 long currentTime, UserHandle user) throws PackageManagerException { 6383 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6384 try { 6385 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6386 } finally { 6387 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6388 } 6389 } 6390 6391 /** 6392 * Scans a package and returns the newly parsed package. 6393 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6394 */ 6395 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6396 long currentTime, UserHandle user) throws PackageManagerException { 6397 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6398 parseFlags |= mDefParseFlags; 6399 PackageParser pp = new PackageParser(); 6400 pp.setSeparateProcesses(mSeparateProcesses); 6401 pp.setOnlyCoreApps(mOnlyCore); 6402 pp.setDisplayMetrics(mMetrics); 6403 6404 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6405 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6406 } 6407 6408 final PackageParser.Package pkg; 6409 try { 6410 pkg = pp.parsePackage(scanFile, parseFlags); 6411 } catch (PackageParserException e) { 6412 throw PackageManagerException.from(e); 6413 } 6414 6415 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6416 } 6417 6418 /** 6419 * Scans a package and returns the newly parsed package. 6420 * @throws PackageManagerException on a parse error. 6421 */ 6422 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6423 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6424 throws PackageManagerException { 6425 // If the package has children and this is the first dive in the function 6426 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6427 // packages (parent and children) would be successfully scanned before the 6428 // actual scan since scanning mutates internal state and we want to atomically 6429 // install the package and its children. 6430 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6431 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6432 scanFlags |= SCAN_CHECK_ONLY; 6433 } 6434 } else { 6435 scanFlags &= ~SCAN_CHECK_ONLY; 6436 } 6437 6438 // Scan the parent 6439 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6440 scanFlags, currentTime, user); 6441 6442 // Scan the children 6443 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6444 for (int i = 0; i < childCount; i++) { 6445 PackageParser.Package childPackage = pkg.childPackages.get(i); 6446 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6447 currentTime, user); 6448 } 6449 6450 6451 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6452 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6453 } 6454 6455 return scannedPkg; 6456 } 6457 6458 /** 6459 * Scans a package and returns the newly parsed package. 6460 * @throws PackageManagerException on a parse error. 6461 */ 6462 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6463 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6464 throws PackageManagerException { 6465 PackageSetting ps = null; 6466 PackageSetting updatedPkg; 6467 // reader 6468 synchronized (mPackages) { 6469 // Look to see if we already know about this package. 6470 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6471 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6472 // This package has been renamed to its original name. Let's 6473 // use that. 6474 ps = mSettings.peekPackageLPr(oldName); 6475 } 6476 // If there was no original package, see one for the real package name. 6477 if (ps == null) { 6478 ps = mSettings.peekPackageLPr(pkg.packageName); 6479 } 6480 // Check to see if this package could be hiding/updating a system 6481 // package. Must look for it either under the original or real 6482 // package name depending on our state. 6483 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6484 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6485 6486 // If this is a package we don't know about on the system partition, we 6487 // may need to remove disabled child packages on the system partition 6488 // or may need to not add child packages if the parent apk is updated 6489 // on the data partition and no longer defines this child package. 6490 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6491 // If this is a parent package for an updated system app and this system 6492 // app got an OTA update which no longer defines some of the child packages 6493 // we have to prune them from the disabled system packages. 6494 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6495 if (disabledPs != null) { 6496 final int scannedChildCount = (pkg.childPackages != null) 6497 ? pkg.childPackages.size() : 0; 6498 final int disabledChildCount = disabledPs.childPackageNames != null 6499 ? disabledPs.childPackageNames.size() : 0; 6500 for (int i = 0; i < disabledChildCount; i++) { 6501 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6502 boolean disabledPackageAvailable = false; 6503 for (int j = 0; j < scannedChildCount; j++) { 6504 PackageParser.Package childPkg = pkg.childPackages.get(j); 6505 if (childPkg.packageName.equals(disabledChildPackageName)) { 6506 disabledPackageAvailable = true; 6507 break; 6508 } 6509 } 6510 if (!disabledPackageAvailable) { 6511 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6512 } 6513 } 6514 } 6515 } 6516 } 6517 6518 boolean updatedPkgBetter = false; 6519 // First check if this is a system package that may involve an update 6520 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6521 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6522 // it needs to drop FLAG_PRIVILEGED. 6523 if (locationIsPrivileged(scanFile)) { 6524 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6525 } else { 6526 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6527 } 6528 6529 if (ps != null && !ps.codePath.equals(scanFile)) { 6530 // The path has changed from what was last scanned... check the 6531 // version of the new path against what we have stored to determine 6532 // what to do. 6533 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6534 if (pkg.mVersionCode <= ps.versionCode) { 6535 // The system package has been updated and the code path does not match 6536 // Ignore entry. Skip it. 6537 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6538 + " ignored: updated version " + ps.versionCode 6539 + " better than this " + pkg.mVersionCode); 6540 if (!updatedPkg.codePath.equals(scanFile)) { 6541 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6542 + ps.name + " changing from " + updatedPkg.codePathString 6543 + " to " + scanFile); 6544 updatedPkg.codePath = scanFile; 6545 updatedPkg.codePathString = scanFile.toString(); 6546 updatedPkg.resourcePath = scanFile; 6547 updatedPkg.resourcePathString = scanFile.toString(); 6548 } 6549 updatedPkg.pkg = pkg; 6550 updatedPkg.versionCode = pkg.mVersionCode; 6551 6552 // Update the disabled system child packages to point to the package too. 6553 final int childCount = updatedPkg.childPackageNames != null 6554 ? updatedPkg.childPackageNames.size() : 0; 6555 for (int i = 0; i < childCount; i++) { 6556 String childPackageName = updatedPkg.childPackageNames.get(i); 6557 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6558 childPackageName); 6559 if (updatedChildPkg != null) { 6560 updatedChildPkg.pkg = pkg; 6561 updatedChildPkg.versionCode = pkg.mVersionCode; 6562 } 6563 } 6564 6565 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6566 + scanFile + " ignored: updated version " + ps.versionCode 6567 + " better than this " + pkg.mVersionCode); 6568 } else { 6569 // The current app on the system partition is better than 6570 // what we have updated to on the data partition; switch 6571 // back to the system partition version. 6572 // At this point, its safely assumed that package installation for 6573 // apps in system partition will go through. If not there won't be a working 6574 // version of the app 6575 // writer 6576 synchronized (mPackages) { 6577 // Just remove the loaded entries from package lists. 6578 mPackages.remove(ps.name); 6579 } 6580 6581 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6582 + " reverting from " + ps.codePathString 6583 + ": new version " + pkg.mVersionCode 6584 + " better than installed " + ps.versionCode); 6585 6586 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6587 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6588 synchronized (mInstallLock) { 6589 args.cleanUpResourcesLI(); 6590 } 6591 synchronized (mPackages) { 6592 mSettings.enableSystemPackageLPw(ps.name); 6593 } 6594 updatedPkgBetter = true; 6595 } 6596 } 6597 } 6598 6599 if (updatedPkg != null) { 6600 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6601 // initially 6602 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6603 6604 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6605 // flag set initially 6606 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6607 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6608 } 6609 } 6610 6611 // Verify certificates against what was last scanned 6612 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6613 6614 /* 6615 * A new system app appeared, but we already had a non-system one of the 6616 * same name installed earlier. 6617 */ 6618 boolean shouldHideSystemApp = false; 6619 if (updatedPkg == null && ps != null 6620 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6621 /* 6622 * Check to make sure the signatures match first. If they don't, 6623 * wipe the installed application and its data. 6624 */ 6625 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6626 != PackageManager.SIGNATURE_MATCH) { 6627 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6628 + " signatures don't match existing userdata copy; removing"); 6629 deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null); 6630 ps = null; 6631 } else { 6632 /* 6633 * If the newly-added system app is an older version than the 6634 * already installed version, hide it. It will be scanned later 6635 * and re-added like an update. 6636 */ 6637 if (pkg.mVersionCode <= ps.versionCode) { 6638 shouldHideSystemApp = true; 6639 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6640 + " but new version " + pkg.mVersionCode + " better than installed " 6641 + ps.versionCode + "; hiding system"); 6642 } else { 6643 /* 6644 * The newly found system app is a newer version that the 6645 * one previously installed. Simply remove the 6646 * already-installed application and replace it with our own 6647 * while keeping the application data. 6648 */ 6649 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6650 + " reverting from " + ps.codePathString + ": new version " 6651 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6652 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6653 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6654 synchronized (mInstallLock) { 6655 args.cleanUpResourcesLI(); 6656 } 6657 } 6658 } 6659 } 6660 6661 // The apk is forward locked (not public) if its code and resources 6662 // are kept in different files. (except for app in either system or 6663 // vendor path). 6664 // TODO grab this value from PackageSettings 6665 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6666 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6667 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6668 } 6669 } 6670 6671 // TODO: extend to support forward-locked splits 6672 String resourcePath = null; 6673 String baseResourcePath = null; 6674 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6675 if (ps != null && ps.resourcePathString != null) { 6676 resourcePath = ps.resourcePathString; 6677 baseResourcePath = ps.resourcePathString; 6678 } else { 6679 // Should not happen at all. Just log an error. 6680 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6681 } 6682 } else { 6683 resourcePath = pkg.codePath; 6684 baseResourcePath = pkg.baseCodePath; 6685 } 6686 6687 // Set application objects path explicitly. 6688 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6689 pkg.setApplicationInfoCodePath(pkg.codePath); 6690 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6691 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6692 pkg.setApplicationInfoResourcePath(resourcePath); 6693 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6694 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6695 6696 // Note that we invoke the following method only if we are about to unpack an application 6697 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6698 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6699 6700 /* 6701 * If the system app should be overridden by a previously installed 6702 * data, hide the system app now and let the /data/app scan pick it up 6703 * again. 6704 */ 6705 if (shouldHideSystemApp) { 6706 synchronized (mPackages) { 6707 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6708 } 6709 } 6710 6711 return scannedPkg; 6712 } 6713 6714 private static String fixProcessName(String defProcessName, 6715 String processName, int uid) { 6716 if (processName == null) { 6717 return defProcessName; 6718 } 6719 return processName; 6720 } 6721 6722 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6723 throws PackageManagerException { 6724 if (pkgSetting.signatures.mSignatures != null) { 6725 // Already existing package. Make sure signatures match 6726 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6727 == PackageManager.SIGNATURE_MATCH; 6728 if (!match) { 6729 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6730 == PackageManager.SIGNATURE_MATCH; 6731 } 6732 if (!match) { 6733 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6734 == PackageManager.SIGNATURE_MATCH; 6735 } 6736 if (!match) { 6737 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6738 + pkg.packageName + " signatures do not match the " 6739 + "previously installed version; ignoring!"); 6740 } 6741 } 6742 6743 // Check for shared user signatures 6744 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6745 // Already existing package. Make sure signatures match 6746 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6747 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6748 if (!match) { 6749 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6750 == PackageManager.SIGNATURE_MATCH; 6751 } 6752 if (!match) { 6753 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6754 == PackageManager.SIGNATURE_MATCH; 6755 } 6756 if (!match) { 6757 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6758 "Package " + pkg.packageName 6759 + " has no signatures that match those in shared user " 6760 + pkgSetting.sharedUser.name + "; ignoring!"); 6761 } 6762 } 6763 } 6764 6765 /** 6766 * Enforces that only the system UID or root's UID can call a method exposed 6767 * via Binder. 6768 * 6769 * @param message used as message if SecurityException is thrown 6770 * @throws SecurityException if the caller is not system or root 6771 */ 6772 private static final void enforceSystemOrRoot(String message) { 6773 final int uid = Binder.getCallingUid(); 6774 if (uid != Process.SYSTEM_UID && uid != 0) { 6775 throw new SecurityException(message); 6776 } 6777 } 6778 6779 @Override 6780 public void performFstrimIfNeeded() { 6781 enforceSystemOrRoot("Only the system can request fstrim"); 6782 6783 // Before everything else, see whether we need to fstrim. 6784 try { 6785 IMountService ms = PackageHelper.getMountService(); 6786 if (ms != null) { 6787 final boolean isUpgrade = isUpgrade(); 6788 boolean doTrim = isUpgrade; 6789 if (doTrim) { 6790 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6791 } else { 6792 final long interval = android.provider.Settings.Global.getLong( 6793 mContext.getContentResolver(), 6794 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6795 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6796 if (interval > 0) { 6797 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6798 if (timeSinceLast > interval) { 6799 doTrim = true; 6800 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6801 + "; running immediately"); 6802 } 6803 } 6804 } 6805 if (doTrim) { 6806 if (!isFirstBoot()) { 6807 try { 6808 ActivityManagerNative.getDefault().showBootMessage( 6809 mContext.getResources().getString( 6810 R.string.android_upgrading_fstrim), true); 6811 } catch (RemoteException e) { 6812 } 6813 } 6814 ms.runMaintenance(); 6815 } 6816 } else { 6817 Slog.e(TAG, "Mount service unavailable!"); 6818 } 6819 } catch (RemoteException e) { 6820 // Can't happen; MountService is local 6821 } 6822 } 6823 6824 @Override 6825 public void extractPackagesIfNeeded() { 6826 enforceSystemOrRoot("Only the system can request package extraction"); 6827 6828 // Extract pacakges only if profile-guided compilation is enabled because 6829 // otherwise BackgroundDexOptService will not dexopt them later. 6830 if (!isUpgrade()) { 6831 return; 6832 } 6833 6834 List<PackageParser.Package> pkgs; 6835 synchronized (mPackages) { 6836 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 6837 } 6838 6839 int curr = 0; 6840 int total = pkgs.size(); 6841 for (PackageParser.Package pkg : pkgs) { 6842 curr++; 6843 6844 if (DEBUG_DEXOPT) { 6845 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 6846 } 6847 6848 if (!isFirstBoot()) { 6849 try { 6850 ActivityManagerNative.getDefault().showBootMessage( 6851 mContext.getResources().getString(R.string.android_upgrading_apk, 6852 curr, total), true); 6853 } catch (RemoteException e) { 6854 } 6855 } 6856 6857 if (PackageDexOptimizer.canOptimizePackage(pkg)) { 6858 performDexOpt(pkg.packageName, null /* instructionSet */, 6859 false /* useProfiles */, true /* extractOnly */, false /* force */); 6860 } 6861 } 6862 } 6863 6864 @Override 6865 public void notifyPackageUse(String packageName) { 6866 synchronized (mPackages) { 6867 PackageParser.Package p = mPackages.get(packageName); 6868 if (p == null) { 6869 return; 6870 } 6871 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6872 } 6873 } 6874 6875 // TODO: this is not used nor needed. Delete it. 6876 @Override 6877 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6878 return performDexOptTraced(packageName, instructionSet, false /* useProfiles */, 6879 false /* extractOnly */, false /* force */); 6880 } 6881 6882 @Override 6883 public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles, 6884 boolean extractOnly, boolean force) { 6885 return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force); 6886 } 6887 6888 private boolean performDexOptTraced(String packageName, String instructionSet, 6889 boolean useProfiles, boolean extractOnly, boolean force) { 6890 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6891 try { 6892 return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly, 6893 force); 6894 } finally { 6895 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6896 } 6897 } 6898 6899 private boolean performDexOptInternal(String packageName, String instructionSet, 6900 boolean useProfiles, boolean extractOnly, boolean force) { 6901 PackageParser.Package p; 6902 final String targetInstructionSet; 6903 synchronized (mPackages) { 6904 p = mPackages.get(packageName); 6905 if (p == null) { 6906 return false; 6907 } 6908 mPackageUsage.write(false); 6909 6910 targetInstructionSet = instructionSet != null ? instructionSet : 6911 getPrimaryInstructionSet(p.applicationInfo); 6912 } 6913 long callingId = Binder.clearCallingIdentity(); 6914 try { 6915 synchronized (mInstallLock) { 6916 final String[] instructionSets = new String[] { targetInstructionSet }; 6917 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 6918 useProfiles, extractOnly, force); 6919 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6920 } 6921 } finally { 6922 Binder.restoreCallingIdentity(callingId); 6923 } 6924 } 6925 6926 public ArraySet<String> getOptimizablePackages() { 6927 ArraySet<String> pkgs = new ArraySet<String>(); 6928 synchronized (mPackages) { 6929 for (PackageParser.Package p : mPackages.values()) { 6930 if (PackageDexOptimizer.canOptimizePackage(p)) { 6931 pkgs.add(p.packageName); 6932 } 6933 } 6934 } 6935 return pkgs; 6936 } 6937 6938 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 6939 String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) { 6940 // Select the dex optimizer based on the force parameter. 6941 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 6942 // allocate an object here. 6943 PackageDexOptimizer pdo = force 6944 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 6945 : mPackageDexOptimizer; 6946 6947 // Optimize all dependencies first. Note: we ignore the return value and march on 6948 // on errors. 6949 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 6950 if (!deps.isEmpty()) { 6951 for (PackageParser.Package depPackage : deps) { 6952 // TODO: Analyze and investigate if we (should) profile libraries. 6953 // Currently this will do a full compilation of the library. 6954 pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */, 6955 false /* extractOnly */); 6956 } 6957 } 6958 6959 return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly); 6960 } 6961 6962 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 6963 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 6964 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 6965 Set<String> collectedNames = new HashSet<>(); 6966 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 6967 6968 retValue.remove(p); 6969 6970 return retValue; 6971 } else { 6972 return Collections.emptyList(); 6973 } 6974 } 6975 6976 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 6977 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 6978 if (!collectedNames.contains(p.packageName)) { 6979 collectedNames.add(p.packageName); 6980 collected.add(p); 6981 6982 if (p.usesLibraries != null) { 6983 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 6984 } 6985 if (p.usesOptionalLibraries != null) { 6986 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 6987 collectedNames); 6988 } 6989 } 6990 } 6991 6992 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 6993 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 6994 for (String libName : libs) { 6995 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 6996 if (libPkg != null) { 6997 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 6998 } 6999 } 7000 } 7001 7002 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7003 synchronized (mPackages) { 7004 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7005 if (lib != null && lib.apk != null) { 7006 return mPackages.get(lib.apk); 7007 } 7008 } 7009 return null; 7010 } 7011 7012 public void shutdown() { 7013 mPackageUsage.write(true); 7014 } 7015 7016 @Override 7017 public void forceDexOpt(String packageName) { 7018 enforceSystemOrRoot("forceDexOpt"); 7019 7020 PackageParser.Package pkg; 7021 synchronized (mPackages) { 7022 pkg = mPackages.get(packageName); 7023 if (pkg == null) { 7024 throw new IllegalArgumentException("Unknown package: " + packageName); 7025 } 7026 } 7027 7028 synchronized (mInstallLock) { 7029 final String[] instructionSets = new String[] { 7030 getPrimaryInstructionSet(pkg.applicationInfo) }; 7031 7032 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7033 7034 // Whoever is calling forceDexOpt wants a fully compiled package. 7035 // Don't use profiles since that may cause compilation to be skipped. 7036 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7037 false /* useProfiles */, false /* extractOnly */, true /* force */); 7038 7039 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7040 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7041 throw new IllegalStateException("Failed to dexopt: " + res); 7042 } 7043 } 7044 } 7045 7046 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7047 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7048 Slog.w(TAG, "Unable to update from " + oldPkg.name 7049 + " to " + newPkg.packageName 7050 + ": old package not in system partition"); 7051 return false; 7052 } else if (mPackages.get(oldPkg.name) != null) { 7053 Slog.w(TAG, "Unable to update from " + oldPkg.name 7054 + " to " + newPkg.packageName 7055 + ": old package still exists"); 7056 return false; 7057 } 7058 return true; 7059 } 7060 7061 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 7062 // TODO: triage flags as part of 26466827 7063 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7064 7065 boolean res = true; 7066 final int[] users = sUserManager.getUserIds(); 7067 for (int user : users) { 7068 try { 7069 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7070 } catch (InstallerException e) { 7071 Slog.w(TAG, "Failed to delete data directory", e); 7072 res = false; 7073 } 7074 } 7075 return res; 7076 } 7077 7078 void removeCodePathLI(File codePath) { 7079 if (codePath.isDirectory()) { 7080 try { 7081 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7082 } catch (InstallerException e) { 7083 Slog.w(TAG, "Failed to remove code path", e); 7084 } 7085 } else { 7086 codePath.delete(); 7087 } 7088 } 7089 7090 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7091 try { 7092 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7093 } catch (InstallerException e) { 7094 Slog.w(TAG, "Failed to destroy app data", e); 7095 } 7096 } 7097 7098 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7099 int appId, String seinfo) { 7100 try { 7101 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7102 } catch (InstallerException e) { 7103 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7104 } 7105 } 7106 7107 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7108 final PackageParser.Package pkg; 7109 synchronized (mPackages) { 7110 pkg = mPackages.get(packageName); 7111 } 7112 if (pkg == null) { 7113 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7114 return; 7115 } 7116 deleteCodeCacheDirsLI(pkg); 7117 } 7118 7119 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7120 // TODO: triage flags as part of 26466827 7121 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7122 7123 int[] users = sUserManager.getUserIds(); 7124 int res = 0; 7125 for (int user : users) { 7126 // Remove the parent code cache 7127 try { 7128 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7129 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7130 } catch (InstallerException e) { 7131 Slog.w(TAG, "Failed to delete code cache directory", e); 7132 } 7133 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7134 for (int i = 0; i < childCount; i++) { 7135 PackageParser.Package childPkg = pkg.childPackages.get(i); 7136 // Remove the child code cache 7137 try { 7138 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7139 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7140 } catch (InstallerException e) { 7141 Slog.w(TAG, "Failed to delete code cache directory", e); 7142 } 7143 } 7144 } 7145 } 7146 7147 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7148 long lastUpdateTime) { 7149 // Set parent install/update time 7150 PackageSetting ps = (PackageSetting) pkg.mExtras; 7151 if (ps != null) { 7152 ps.firstInstallTime = firstInstallTime; 7153 ps.lastUpdateTime = lastUpdateTime; 7154 } 7155 // Set children install/update time 7156 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7157 for (int i = 0; i < childCount; i++) { 7158 PackageParser.Package childPkg = pkg.childPackages.get(i); 7159 ps = (PackageSetting) childPkg.mExtras; 7160 if (ps != null) { 7161 ps.firstInstallTime = firstInstallTime; 7162 ps.lastUpdateTime = lastUpdateTime; 7163 } 7164 } 7165 } 7166 7167 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7168 PackageParser.Package changingLib) { 7169 if (file.path != null) { 7170 usesLibraryFiles.add(file.path); 7171 return; 7172 } 7173 PackageParser.Package p = mPackages.get(file.apk); 7174 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7175 // If we are doing this while in the middle of updating a library apk, 7176 // then we need to make sure to use that new apk for determining the 7177 // dependencies here. (We haven't yet finished committing the new apk 7178 // to the package manager state.) 7179 if (p == null || p.packageName.equals(changingLib.packageName)) { 7180 p = changingLib; 7181 } 7182 } 7183 if (p != null) { 7184 usesLibraryFiles.addAll(p.getAllCodePaths()); 7185 } 7186 } 7187 7188 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7189 PackageParser.Package changingLib) throws PackageManagerException { 7190 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7191 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7192 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7193 for (int i=0; i<N; i++) { 7194 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7195 if (file == null) { 7196 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7197 "Package " + pkg.packageName + " requires unavailable shared library " 7198 + pkg.usesLibraries.get(i) + "; failing!"); 7199 } 7200 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7201 } 7202 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7203 for (int i=0; i<N; i++) { 7204 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7205 if (file == null) { 7206 Slog.w(TAG, "Package " + pkg.packageName 7207 + " desires unavailable shared library " 7208 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7209 } else { 7210 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7211 } 7212 } 7213 N = usesLibraryFiles.size(); 7214 if (N > 0) { 7215 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7216 } else { 7217 pkg.usesLibraryFiles = null; 7218 } 7219 } 7220 } 7221 7222 private static boolean hasString(List<String> list, List<String> which) { 7223 if (list == null) { 7224 return false; 7225 } 7226 for (int i=list.size()-1; i>=0; i--) { 7227 for (int j=which.size()-1; j>=0; j--) { 7228 if (which.get(j).equals(list.get(i))) { 7229 return true; 7230 } 7231 } 7232 } 7233 return false; 7234 } 7235 7236 private void updateAllSharedLibrariesLPw() { 7237 for (PackageParser.Package pkg : mPackages.values()) { 7238 try { 7239 updateSharedLibrariesLPw(pkg, null); 7240 } catch (PackageManagerException e) { 7241 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7242 } 7243 } 7244 } 7245 7246 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7247 PackageParser.Package changingPkg) { 7248 ArrayList<PackageParser.Package> res = null; 7249 for (PackageParser.Package pkg : mPackages.values()) { 7250 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7251 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7252 if (res == null) { 7253 res = new ArrayList<PackageParser.Package>(); 7254 } 7255 res.add(pkg); 7256 try { 7257 updateSharedLibrariesLPw(pkg, changingPkg); 7258 } catch (PackageManagerException e) { 7259 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7260 } 7261 } 7262 } 7263 return res; 7264 } 7265 7266 /** 7267 * Derive the value of the {@code cpuAbiOverride} based on the provided 7268 * value and an optional stored value from the package settings. 7269 */ 7270 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7271 String cpuAbiOverride = null; 7272 7273 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7274 cpuAbiOverride = null; 7275 } else if (abiOverride != null) { 7276 cpuAbiOverride = abiOverride; 7277 } else if (settings != null) { 7278 cpuAbiOverride = settings.cpuAbiOverrideString; 7279 } 7280 7281 return cpuAbiOverride; 7282 } 7283 7284 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7285 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7286 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7287 // If the package has children and this is the first dive in the function 7288 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7289 // whether all packages (parent and children) would be successfully scanned 7290 // before the actual scan since scanning mutates internal state and we want 7291 // to atomically install the package and its children. 7292 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7293 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7294 scanFlags |= SCAN_CHECK_ONLY; 7295 } 7296 } else { 7297 scanFlags &= ~SCAN_CHECK_ONLY; 7298 } 7299 7300 final PackageParser.Package scannedPkg; 7301 try { 7302 // Scan the parent 7303 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7304 // Scan the children 7305 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7306 for (int i = 0; i < childCount; i++) { 7307 PackageParser.Package childPkg = pkg.childPackages.get(i); 7308 scanPackageLI(childPkg, parseFlags, 7309 scanFlags, currentTime, user); 7310 } 7311 } finally { 7312 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7313 } 7314 7315 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7316 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7317 } 7318 7319 return scannedPkg; 7320 } 7321 7322 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7323 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7324 boolean success = false; 7325 try { 7326 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7327 currentTime, user); 7328 success = true; 7329 return res; 7330 } finally { 7331 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7332 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7333 } 7334 } 7335 } 7336 7337 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7338 int scanFlags, long currentTime, UserHandle user) 7339 throws PackageManagerException { 7340 final File scanFile = new File(pkg.codePath); 7341 if (pkg.applicationInfo.getCodePath() == null || 7342 pkg.applicationInfo.getResourcePath() == null) { 7343 // Bail out. The resource and code paths haven't been set. 7344 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7345 "Code and resource paths haven't been set correctly"); 7346 } 7347 7348 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7349 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7350 } else { 7351 // Only allow system apps to be flagged as core apps. 7352 pkg.coreApp = false; 7353 } 7354 7355 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7356 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7357 } 7358 7359 if (mCustomResolverComponentName != null && 7360 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7361 setUpCustomResolverActivity(pkg); 7362 } 7363 7364 if (pkg.packageName.equals("android")) { 7365 synchronized (mPackages) { 7366 if (mAndroidApplication != null) { 7367 Slog.w(TAG, "*************************************************"); 7368 Slog.w(TAG, "Core android package being redefined. Skipping."); 7369 Slog.w(TAG, " file=" + scanFile); 7370 Slog.w(TAG, "*************************************************"); 7371 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7372 "Core android package being redefined. Skipping."); 7373 } 7374 7375 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7376 // Set up information for our fall-back user intent resolution activity. 7377 mPlatformPackage = pkg; 7378 pkg.mVersionCode = mSdkVersion; 7379 mAndroidApplication = pkg.applicationInfo; 7380 7381 if (!mResolverReplaced) { 7382 mResolveActivity.applicationInfo = mAndroidApplication; 7383 mResolveActivity.name = ResolverActivity.class.getName(); 7384 mResolveActivity.packageName = mAndroidApplication.packageName; 7385 mResolveActivity.processName = "system:ui"; 7386 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7387 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7388 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7389 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7390 mResolveActivity.exported = true; 7391 mResolveActivity.enabled = true; 7392 mResolveInfo.activityInfo = mResolveActivity; 7393 mResolveInfo.priority = 0; 7394 mResolveInfo.preferredOrder = 0; 7395 mResolveInfo.match = 0; 7396 mResolveComponentName = new ComponentName( 7397 mAndroidApplication.packageName, mResolveActivity.name); 7398 } 7399 } 7400 } 7401 } 7402 7403 if (DEBUG_PACKAGE_SCANNING) { 7404 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7405 Log.d(TAG, "Scanning package " + pkg.packageName); 7406 } 7407 7408 synchronized (mPackages) { 7409 if (mPackages.containsKey(pkg.packageName) 7410 || mSharedLibraries.containsKey(pkg.packageName)) { 7411 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7412 "Application package " + pkg.packageName 7413 + " already installed. Skipping duplicate."); 7414 } 7415 7416 // If we're only installing presumed-existing packages, require that the 7417 // scanned APK is both already known and at the path previously established 7418 // for it. Previously unknown packages we pick up normally, but if we have an 7419 // a priori expectation about this package's install presence, enforce it. 7420 // With a singular exception for new system packages. When an OTA contains 7421 // a new system package, we allow the codepath to change from a system location 7422 // to the user-installed location. If we don't allow this change, any newer, 7423 // user-installed version of the application will be ignored. 7424 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7425 if (mExpectingBetter.containsKey(pkg.packageName)) { 7426 logCriticalInfo(Log.WARN, 7427 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7428 } else { 7429 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7430 if (known != null) { 7431 if (DEBUG_PACKAGE_SCANNING) { 7432 Log.d(TAG, "Examining " + pkg.codePath 7433 + " and requiring known paths " + known.codePathString 7434 + " & " + known.resourcePathString); 7435 } 7436 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7437 || !pkg.applicationInfo.getResourcePath().equals( 7438 known.resourcePathString)) { 7439 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7440 "Application package " + pkg.packageName 7441 + " found at " + pkg.applicationInfo.getCodePath() 7442 + " but expected at " + known.codePathString 7443 + "; ignoring."); 7444 } 7445 } 7446 } 7447 } 7448 } 7449 7450 // Initialize package source and resource directories 7451 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7452 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7453 7454 SharedUserSetting suid = null; 7455 PackageSetting pkgSetting = null; 7456 7457 if (!isSystemApp(pkg)) { 7458 // Only system apps can use these features. 7459 pkg.mOriginalPackages = null; 7460 pkg.mRealPackage = null; 7461 pkg.mAdoptPermissions = null; 7462 } 7463 7464 // Getting the package setting may have a side-effect, so if we 7465 // are only checking if scan would succeed, stash a copy of the 7466 // old setting to restore at the end. 7467 PackageSetting nonMutatedPs = null; 7468 7469 // writer 7470 synchronized (mPackages) { 7471 if (pkg.mSharedUserId != null) { 7472 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7473 if (suid == null) { 7474 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7475 "Creating application package " + pkg.packageName 7476 + " for shared user failed"); 7477 } 7478 if (DEBUG_PACKAGE_SCANNING) { 7479 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7480 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7481 + "): packages=" + suid.packages); 7482 } 7483 } 7484 7485 // Check if we are renaming from an original package name. 7486 PackageSetting origPackage = null; 7487 String realName = null; 7488 if (pkg.mOriginalPackages != null) { 7489 // This package may need to be renamed to a previously 7490 // installed name. Let's check on that... 7491 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7492 if (pkg.mOriginalPackages.contains(renamed)) { 7493 // This package had originally been installed as the 7494 // original name, and we have already taken care of 7495 // transitioning to the new one. Just update the new 7496 // one to continue using the old name. 7497 realName = pkg.mRealPackage; 7498 if (!pkg.packageName.equals(renamed)) { 7499 // Callers into this function may have already taken 7500 // care of renaming the package; only do it here if 7501 // it is not already done. 7502 pkg.setPackageName(renamed); 7503 } 7504 7505 } else { 7506 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7507 if ((origPackage = mSettings.peekPackageLPr( 7508 pkg.mOriginalPackages.get(i))) != null) { 7509 // We do have the package already installed under its 7510 // original name... should we use it? 7511 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7512 // New package is not compatible with original. 7513 origPackage = null; 7514 continue; 7515 } else if (origPackage.sharedUser != null) { 7516 // Make sure uid is compatible between packages. 7517 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7518 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7519 + " to " + pkg.packageName + ": old uid " 7520 + origPackage.sharedUser.name 7521 + " differs from " + pkg.mSharedUserId); 7522 origPackage = null; 7523 continue; 7524 } 7525 } else { 7526 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7527 + pkg.packageName + " to old name " + origPackage.name); 7528 } 7529 break; 7530 } 7531 } 7532 } 7533 } 7534 7535 if (mTransferedPackages.contains(pkg.packageName)) { 7536 Slog.w(TAG, "Package " + pkg.packageName 7537 + " was transferred to another, but its .apk remains"); 7538 } 7539 7540 // See comments in nonMutatedPs declaration 7541 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7542 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7543 if (foundPs != null) { 7544 nonMutatedPs = new PackageSetting(foundPs); 7545 } 7546 } 7547 7548 // Just create the setting, don't add it yet. For already existing packages 7549 // the PkgSetting exists already and doesn't have to be created. 7550 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7551 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7552 pkg.applicationInfo.primaryCpuAbi, 7553 pkg.applicationInfo.secondaryCpuAbi, 7554 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7555 user, false); 7556 if (pkgSetting == null) { 7557 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7558 "Creating application package " + pkg.packageName + " failed"); 7559 } 7560 7561 if (pkgSetting.origPackage != null) { 7562 // If we are first transitioning from an original package, 7563 // fix up the new package's name now. We need to do this after 7564 // looking up the package under its new name, so getPackageLP 7565 // can take care of fiddling things correctly. 7566 pkg.setPackageName(origPackage.name); 7567 7568 // File a report about this. 7569 String msg = "New package " + pkgSetting.realName 7570 + " renamed to replace old package " + pkgSetting.name; 7571 reportSettingsProblem(Log.WARN, msg); 7572 7573 // Make a note of it. 7574 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7575 mTransferedPackages.add(origPackage.name); 7576 } 7577 7578 // No longer need to retain this. 7579 pkgSetting.origPackage = null; 7580 } 7581 7582 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7583 // Make a note of it. 7584 mTransferedPackages.add(pkg.packageName); 7585 } 7586 7587 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7588 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7589 } 7590 7591 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7592 // Check all shared libraries and map to their actual file path. 7593 // We only do this here for apps not on a system dir, because those 7594 // are the only ones that can fail an install due to this. We 7595 // will take care of the system apps by updating all of their 7596 // library paths after the scan is done. 7597 updateSharedLibrariesLPw(pkg, null); 7598 } 7599 7600 if (mFoundPolicyFile) { 7601 SELinuxMMAC.assignSeinfoValue(pkg); 7602 } 7603 7604 pkg.applicationInfo.uid = pkgSetting.appId; 7605 pkg.mExtras = pkgSetting; 7606 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7607 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7608 // We just determined the app is signed correctly, so bring 7609 // over the latest parsed certs. 7610 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7611 } else { 7612 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7613 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7614 "Package " + pkg.packageName + " upgrade keys do not match the " 7615 + "previously installed version"); 7616 } else { 7617 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7618 String msg = "System package " + pkg.packageName 7619 + " signature changed; retaining data."; 7620 reportSettingsProblem(Log.WARN, msg); 7621 } 7622 } 7623 } else { 7624 try { 7625 verifySignaturesLP(pkgSetting, pkg); 7626 // We just determined the app is signed correctly, so bring 7627 // over the latest parsed certs. 7628 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7629 } catch (PackageManagerException e) { 7630 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7631 throw e; 7632 } 7633 // The signature has changed, but this package is in the system 7634 // image... let's recover! 7635 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7636 // However... if this package is part of a shared user, but it 7637 // doesn't match the signature of the shared user, let's fail. 7638 // What this means is that you can't change the signatures 7639 // associated with an overall shared user, which doesn't seem all 7640 // that unreasonable. 7641 if (pkgSetting.sharedUser != null) { 7642 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7643 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7644 throw new PackageManagerException( 7645 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7646 "Signature mismatch for shared user: " 7647 + pkgSetting.sharedUser); 7648 } 7649 } 7650 // File a report about this. 7651 String msg = "System package " + pkg.packageName 7652 + " signature changed; retaining data."; 7653 reportSettingsProblem(Log.WARN, msg); 7654 } 7655 } 7656 // Verify that this new package doesn't have any content providers 7657 // that conflict with existing packages. Only do this if the 7658 // package isn't already installed, since we don't want to break 7659 // things that are installed. 7660 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7661 final int N = pkg.providers.size(); 7662 int i; 7663 for (i=0; i<N; i++) { 7664 PackageParser.Provider p = pkg.providers.get(i); 7665 if (p.info.authority != null) { 7666 String names[] = p.info.authority.split(";"); 7667 for (int j = 0; j < names.length; j++) { 7668 if (mProvidersByAuthority.containsKey(names[j])) { 7669 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7670 final String otherPackageName = 7671 ((other != null && other.getComponentName() != null) ? 7672 other.getComponentName().getPackageName() : "?"); 7673 throw new PackageManagerException( 7674 INSTALL_FAILED_CONFLICTING_PROVIDER, 7675 "Can't install because provider name " + names[j] 7676 + " (in package " + pkg.applicationInfo.packageName 7677 + ") is already used by " + otherPackageName); 7678 } 7679 } 7680 } 7681 } 7682 } 7683 7684 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7685 // This package wants to adopt ownership of permissions from 7686 // another package. 7687 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7688 final String origName = pkg.mAdoptPermissions.get(i); 7689 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7690 if (orig != null) { 7691 if (verifyPackageUpdateLPr(orig, pkg)) { 7692 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7693 + pkg.packageName); 7694 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7695 } 7696 } 7697 } 7698 } 7699 } 7700 7701 final String pkgName = pkg.packageName; 7702 7703 final long scanFileTime = scanFile.lastModified(); 7704 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7705 pkg.applicationInfo.processName = fixProcessName( 7706 pkg.applicationInfo.packageName, 7707 pkg.applicationInfo.processName, 7708 pkg.applicationInfo.uid); 7709 7710 if (pkg != mPlatformPackage) { 7711 // Get all of our default paths setup 7712 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7713 } 7714 7715 final String path = scanFile.getPath(); 7716 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7717 7718 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7719 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7720 7721 // Some system apps still use directory structure for native libraries 7722 // in which case we might end up not detecting abi solely based on apk 7723 // structure. Try to detect abi based on directory structure. 7724 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7725 pkg.applicationInfo.primaryCpuAbi == null) { 7726 setBundledAppAbisAndRoots(pkg, pkgSetting); 7727 setNativeLibraryPaths(pkg); 7728 } 7729 7730 } else { 7731 if ((scanFlags & SCAN_MOVE) != 0) { 7732 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7733 // but we already have this packages package info in the PackageSetting. We just 7734 // use that and derive the native library path based on the new codepath. 7735 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7736 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7737 } 7738 7739 // Set native library paths again. For moves, the path will be updated based on the 7740 // ABIs we've determined above. For non-moves, the path will be updated based on the 7741 // ABIs we determined during compilation, but the path will depend on the final 7742 // package path (after the rename away from the stage path). 7743 setNativeLibraryPaths(pkg); 7744 } 7745 7746 // This is a special case for the "system" package, where the ABI is 7747 // dictated by the zygote configuration (and init.rc). We should keep track 7748 // of this ABI so that we can deal with "normal" applications that run under 7749 // the same UID correctly. 7750 if (mPlatformPackage == pkg) { 7751 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7752 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7753 } 7754 7755 // If there's a mismatch between the abi-override in the package setting 7756 // and the abiOverride specified for the install. Warn about this because we 7757 // would've already compiled the app without taking the package setting into 7758 // account. 7759 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7760 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7761 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7762 " for package " + pkg.packageName); 7763 } 7764 } 7765 7766 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7767 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7768 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7769 7770 // Copy the derived override back to the parsed package, so that we can 7771 // update the package settings accordingly. 7772 pkg.cpuAbiOverride = cpuAbiOverride; 7773 7774 if (DEBUG_ABI_SELECTION) { 7775 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7776 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7777 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7778 } 7779 7780 // Push the derived path down into PackageSettings so we know what to 7781 // clean up at uninstall time. 7782 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7783 7784 if (DEBUG_ABI_SELECTION) { 7785 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7786 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7787 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7788 } 7789 7790 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7791 // We don't do this here during boot because we can do it all 7792 // at once after scanning all existing packages. 7793 // 7794 // We also do this *before* we perform dexopt on this package, so that 7795 // we can avoid redundant dexopts, and also to make sure we've got the 7796 // code and package path correct. 7797 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7798 pkg, true /* boot complete */); 7799 } 7800 7801 if (mFactoryTest && pkg.requestedPermissions.contains( 7802 android.Manifest.permission.FACTORY_TEST)) { 7803 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7804 } 7805 7806 ArrayList<PackageParser.Package> clientLibPkgs = null; 7807 7808 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7809 if (nonMutatedPs != null) { 7810 synchronized (mPackages) { 7811 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 7812 } 7813 } 7814 return pkg; 7815 } 7816 7817 // Only privileged apps and updated privileged apps can add child packages. 7818 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 7819 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 7820 throw new PackageManagerException("Only privileged apps and updated " 7821 + "privileged apps can add child packages. Ignoring package " 7822 + pkg.packageName); 7823 } 7824 final int childCount = pkg.childPackages.size(); 7825 for (int i = 0; i < childCount; i++) { 7826 PackageParser.Package childPkg = pkg.childPackages.get(i); 7827 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 7828 childPkg.packageName)) { 7829 throw new PackageManagerException("Cannot override a child package of " 7830 + "another disabled system app. Ignoring package " + pkg.packageName); 7831 } 7832 } 7833 } 7834 7835 // writer 7836 synchronized (mPackages) { 7837 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7838 // Only system apps can add new shared libraries. 7839 if (pkg.libraryNames != null) { 7840 for (int i=0; i<pkg.libraryNames.size(); i++) { 7841 String name = pkg.libraryNames.get(i); 7842 boolean allowed = false; 7843 if (pkg.isUpdatedSystemApp()) { 7844 // New library entries can only be added through the 7845 // system image. This is important to get rid of a lot 7846 // of nasty edge cases: for example if we allowed a non- 7847 // system update of the app to add a library, then uninstalling 7848 // the update would make the library go away, and assumptions 7849 // we made such as through app install filtering would now 7850 // have allowed apps on the device which aren't compatible 7851 // with it. Better to just have the restriction here, be 7852 // conservative, and create many fewer cases that can negatively 7853 // impact the user experience. 7854 final PackageSetting sysPs = mSettings 7855 .getDisabledSystemPkgLPr(pkg.packageName); 7856 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7857 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7858 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7859 allowed = true; 7860 break; 7861 } 7862 } 7863 } 7864 } else { 7865 allowed = true; 7866 } 7867 if (allowed) { 7868 if (!mSharedLibraries.containsKey(name)) { 7869 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7870 } else if (!name.equals(pkg.packageName)) { 7871 Slog.w(TAG, "Package " + pkg.packageName + " library " 7872 + name + " already exists; skipping"); 7873 } 7874 } else { 7875 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7876 + name + " that is not declared on system image; skipping"); 7877 } 7878 } 7879 if ((scanFlags & SCAN_BOOTING) == 0) { 7880 // If we are not booting, we need to update any applications 7881 // that are clients of our shared library. If we are booting, 7882 // this will all be done once the scan is complete. 7883 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7884 } 7885 } 7886 } 7887 } 7888 7889 // Request the ActivityManager to kill the process(only for existing packages) 7890 // so that we do not end up in a confused state while the user is still using the older 7891 // version of the application while the new one gets installed. 7892 if ((scanFlags & SCAN_REPLACING) != 0) { 7893 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7894 7895 killApplication(pkg.applicationInfo.packageName, 7896 pkg.applicationInfo.uid, "replace pkg"); 7897 7898 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7899 } 7900 7901 // Also need to kill any apps that are dependent on the library. 7902 if (clientLibPkgs != null) { 7903 for (int i=0; i<clientLibPkgs.size(); i++) { 7904 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7905 killApplication(clientPkg.applicationInfo.packageName, 7906 clientPkg.applicationInfo.uid, "update lib"); 7907 } 7908 } 7909 7910 // Make sure we're not adding any bogus keyset info 7911 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7912 ksms.assertScannedPackageValid(pkg); 7913 7914 // writer 7915 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7916 7917 boolean createIdmapFailed = false; 7918 synchronized (mPackages) { 7919 // We don't expect installation to fail beyond this point 7920 7921 // Add the new setting to mSettings 7922 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7923 // Add the new setting to mPackages 7924 mPackages.put(pkg.applicationInfo.packageName, pkg); 7925 // Make sure we don't accidentally delete its data. 7926 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7927 while (iter.hasNext()) { 7928 PackageCleanItem item = iter.next(); 7929 if (pkgName.equals(item.packageName)) { 7930 iter.remove(); 7931 } 7932 } 7933 7934 // Take care of first install / last update times. 7935 if (currentTime != 0) { 7936 if (pkgSetting.firstInstallTime == 0) { 7937 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7938 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7939 pkgSetting.lastUpdateTime = currentTime; 7940 } 7941 } else if (pkgSetting.firstInstallTime == 0) { 7942 // We need *something*. Take time time stamp of the file. 7943 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7944 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7945 if (scanFileTime != pkgSetting.timeStamp) { 7946 // A package on the system image has changed; consider this 7947 // to be an update. 7948 pkgSetting.lastUpdateTime = scanFileTime; 7949 } 7950 } 7951 7952 // Add the package's KeySets to the global KeySetManagerService 7953 ksms.addScannedPackageLPw(pkg); 7954 7955 int N = pkg.providers.size(); 7956 StringBuilder r = null; 7957 int i; 7958 for (i=0; i<N; i++) { 7959 PackageParser.Provider p = pkg.providers.get(i); 7960 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7961 p.info.processName, pkg.applicationInfo.uid); 7962 mProviders.addProvider(p); 7963 p.syncable = p.info.isSyncable; 7964 if (p.info.authority != null) { 7965 String names[] = p.info.authority.split(";"); 7966 p.info.authority = null; 7967 for (int j = 0; j < names.length; j++) { 7968 if (j == 1 && p.syncable) { 7969 // We only want the first authority for a provider to possibly be 7970 // syncable, so if we already added this provider using a different 7971 // authority clear the syncable flag. We copy the provider before 7972 // changing it because the mProviders object contains a reference 7973 // to a provider that we don't want to change. 7974 // Only do this for the second authority since the resulting provider 7975 // object can be the same for all future authorities for this provider. 7976 p = new PackageParser.Provider(p); 7977 p.syncable = false; 7978 } 7979 if (!mProvidersByAuthority.containsKey(names[j])) { 7980 mProvidersByAuthority.put(names[j], p); 7981 if (p.info.authority == null) { 7982 p.info.authority = names[j]; 7983 } else { 7984 p.info.authority = p.info.authority + ";" + names[j]; 7985 } 7986 if (DEBUG_PACKAGE_SCANNING) { 7987 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7988 Log.d(TAG, "Registered content provider: " + names[j] 7989 + ", className = " + p.info.name + ", isSyncable = " 7990 + p.info.isSyncable); 7991 } 7992 } else { 7993 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7994 Slog.w(TAG, "Skipping provider name " + names[j] + 7995 " (in package " + pkg.applicationInfo.packageName + 7996 "): name already used by " 7997 + ((other != null && other.getComponentName() != null) 7998 ? other.getComponentName().getPackageName() : "?")); 7999 } 8000 } 8001 } 8002 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8003 if (r == null) { 8004 r = new StringBuilder(256); 8005 } else { 8006 r.append(' '); 8007 } 8008 r.append(p.info.name); 8009 } 8010 } 8011 if (r != null) { 8012 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8013 } 8014 8015 N = pkg.services.size(); 8016 r = null; 8017 for (i=0; i<N; i++) { 8018 PackageParser.Service s = pkg.services.get(i); 8019 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8020 s.info.processName, pkg.applicationInfo.uid); 8021 mServices.addService(s); 8022 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8023 if (r == null) { 8024 r = new StringBuilder(256); 8025 } else { 8026 r.append(' '); 8027 } 8028 r.append(s.info.name); 8029 } 8030 } 8031 if (r != null) { 8032 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8033 } 8034 8035 N = pkg.receivers.size(); 8036 r = null; 8037 for (i=0; i<N; i++) { 8038 PackageParser.Activity a = pkg.receivers.get(i); 8039 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8040 a.info.processName, pkg.applicationInfo.uid); 8041 mReceivers.addActivity(a, "receiver"); 8042 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8043 if (r == null) { 8044 r = new StringBuilder(256); 8045 } else { 8046 r.append(' '); 8047 } 8048 r.append(a.info.name); 8049 } 8050 } 8051 if (r != null) { 8052 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8053 } 8054 8055 N = pkg.activities.size(); 8056 r = null; 8057 for (i=0; i<N; i++) { 8058 PackageParser.Activity a = pkg.activities.get(i); 8059 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8060 a.info.processName, pkg.applicationInfo.uid); 8061 mActivities.addActivity(a, "activity"); 8062 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8063 if (r == null) { 8064 r = new StringBuilder(256); 8065 } else { 8066 r.append(' '); 8067 } 8068 r.append(a.info.name); 8069 } 8070 } 8071 if (r != null) { 8072 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8073 } 8074 8075 N = pkg.permissionGroups.size(); 8076 r = null; 8077 for (i=0; i<N; i++) { 8078 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8079 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8080 if (cur == null) { 8081 mPermissionGroups.put(pg.info.name, pg); 8082 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8083 if (r == null) { 8084 r = new StringBuilder(256); 8085 } else { 8086 r.append(' '); 8087 } 8088 r.append(pg.info.name); 8089 } 8090 } else { 8091 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8092 + pg.info.packageName + " ignored: original from " 8093 + cur.info.packageName); 8094 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8095 if (r == null) { 8096 r = new StringBuilder(256); 8097 } else { 8098 r.append(' '); 8099 } 8100 r.append("DUP:"); 8101 r.append(pg.info.name); 8102 } 8103 } 8104 } 8105 if (r != null) { 8106 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8107 } 8108 8109 N = pkg.permissions.size(); 8110 r = null; 8111 for (i=0; i<N; i++) { 8112 PackageParser.Permission p = pkg.permissions.get(i); 8113 8114 // Assume by default that we did not install this permission into the system. 8115 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8116 8117 // Now that permission groups have a special meaning, we ignore permission 8118 // groups for legacy apps to prevent unexpected behavior. In particular, 8119 // permissions for one app being granted to someone just becase they happen 8120 // to be in a group defined by another app (before this had no implications). 8121 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8122 p.group = mPermissionGroups.get(p.info.group); 8123 // Warn for a permission in an unknown group. 8124 if (p.info.group != null && p.group == null) { 8125 Slog.w(TAG, "Permission " + p.info.name + " from package " 8126 + p.info.packageName + " in an unknown group " + p.info.group); 8127 } 8128 } 8129 8130 ArrayMap<String, BasePermission> permissionMap = 8131 p.tree ? mSettings.mPermissionTrees 8132 : mSettings.mPermissions; 8133 BasePermission bp = permissionMap.get(p.info.name); 8134 8135 // Allow system apps to redefine non-system permissions 8136 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8137 final boolean currentOwnerIsSystem = (bp.perm != null 8138 && isSystemApp(bp.perm.owner)); 8139 if (isSystemApp(p.owner)) { 8140 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8141 // It's a built-in permission and no owner, take ownership now 8142 bp.packageSetting = pkgSetting; 8143 bp.perm = p; 8144 bp.uid = pkg.applicationInfo.uid; 8145 bp.sourcePackage = p.info.packageName; 8146 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8147 } else if (!currentOwnerIsSystem) { 8148 String msg = "New decl " + p.owner + " of permission " 8149 + p.info.name + " is system; overriding " + bp.sourcePackage; 8150 reportSettingsProblem(Log.WARN, msg); 8151 bp = null; 8152 } 8153 } 8154 } 8155 8156 if (bp == null) { 8157 bp = new BasePermission(p.info.name, p.info.packageName, 8158 BasePermission.TYPE_NORMAL); 8159 permissionMap.put(p.info.name, bp); 8160 } 8161 8162 if (bp.perm == null) { 8163 if (bp.sourcePackage == null 8164 || bp.sourcePackage.equals(p.info.packageName)) { 8165 BasePermission tree = findPermissionTreeLP(p.info.name); 8166 if (tree == null 8167 || tree.sourcePackage.equals(p.info.packageName)) { 8168 bp.packageSetting = pkgSetting; 8169 bp.perm = p; 8170 bp.uid = pkg.applicationInfo.uid; 8171 bp.sourcePackage = p.info.packageName; 8172 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8173 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8174 if (r == null) { 8175 r = new StringBuilder(256); 8176 } else { 8177 r.append(' '); 8178 } 8179 r.append(p.info.name); 8180 } 8181 } else { 8182 Slog.w(TAG, "Permission " + p.info.name + " from package " 8183 + p.info.packageName + " ignored: base tree " 8184 + tree.name + " is from package " 8185 + tree.sourcePackage); 8186 } 8187 } else { 8188 Slog.w(TAG, "Permission " + p.info.name + " from package " 8189 + p.info.packageName + " ignored: original from " 8190 + bp.sourcePackage); 8191 } 8192 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8193 if (r == null) { 8194 r = new StringBuilder(256); 8195 } else { 8196 r.append(' '); 8197 } 8198 r.append("DUP:"); 8199 r.append(p.info.name); 8200 } 8201 if (bp.perm == p) { 8202 bp.protectionLevel = p.info.protectionLevel; 8203 } 8204 } 8205 8206 if (r != null) { 8207 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8208 } 8209 8210 N = pkg.instrumentation.size(); 8211 r = null; 8212 for (i=0; i<N; i++) { 8213 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8214 a.info.packageName = pkg.applicationInfo.packageName; 8215 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8216 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8217 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8218 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8219 a.info.dataDir = pkg.applicationInfo.dataDir; 8220 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 8221 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 8222 8223 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8224 // need other information about the application, like the ABI and what not ? 8225 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8226 mInstrumentation.put(a.getComponentName(), a); 8227 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8228 if (r == null) { 8229 r = new StringBuilder(256); 8230 } else { 8231 r.append(' '); 8232 } 8233 r.append(a.info.name); 8234 } 8235 } 8236 if (r != null) { 8237 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8238 } 8239 8240 if (pkg.protectedBroadcasts != null) { 8241 N = pkg.protectedBroadcasts.size(); 8242 for (i=0; i<N; i++) { 8243 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8244 } 8245 } 8246 8247 pkgSetting.setTimeStamp(scanFileTime); 8248 8249 // Create idmap files for pairs of (packages, overlay packages). 8250 // Note: "android", ie framework-res.apk, is handled by native layers. 8251 if (pkg.mOverlayTarget != null) { 8252 // This is an overlay package. 8253 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8254 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8255 mOverlays.put(pkg.mOverlayTarget, 8256 new ArrayMap<String, PackageParser.Package>()); 8257 } 8258 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8259 map.put(pkg.packageName, pkg); 8260 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8261 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8262 createIdmapFailed = true; 8263 } 8264 } 8265 } else if (mOverlays.containsKey(pkg.packageName) && 8266 !pkg.packageName.equals("android")) { 8267 // This is a regular package, with one or more known overlay packages. 8268 createIdmapsForPackageLI(pkg); 8269 } 8270 } 8271 8272 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8273 8274 if (createIdmapFailed) { 8275 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8276 "scanPackageLI failed to createIdmap"); 8277 } 8278 return pkg; 8279 } 8280 8281 /** 8282 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8283 * is derived purely on the basis of the contents of {@code scanFile} and 8284 * {@code cpuAbiOverride}. 8285 * 8286 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8287 */ 8288 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8289 String cpuAbiOverride, boolean extractLibs) 8290 throws PackageManagerException { 8291 // TODO: We can probably be smarter about this stuff. For installed apps, 8292 // we can calculate this information at install time once and for all. For 8293 // system apps, we can probably assume that this information doesn't change 8294 // after the first boot scan. As things stand, we do lots of unnecessary work. 8295 8296 // Give ourselves some initial paths; we'll come back for another 8297 // pass once we've determined ABI below. 8298 setNativeLibraryPaths(pkg); 8299 8300 // We would never need to extract libs for forward-locked and external packages, 8301 // since the container service will do it for us. We shouldn't attempt to 8302 // extract libs from system app when it was not updated. 8303 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8304 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8305 extractLibs = false; 8306 } 8307 8308 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8309 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8310 8311 NativeLibraryHelper.Handle handle = null; 8312 try { 8313 handle = NativeLibraryHelper.Handle.create(pkg); 8314 // TODO(multiArch): This can be null for apps that didn't go through the 8315 // usual installation process. We can calculate it again, like we 8316 // do during install time. 8317 // 8318 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8319 // unnecessary. 8320 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8321 8322 // Null out the abis so that they can be recalculated. 8323 pkg.applicationInfo.primaryCpuAbi = null; 8324 pkg.applicationInfo.secondaryCpuAbi = null; 8325 if (isMultiArch(pkg.applicationInfo)) { 8326 // Warn if we've set an abiOverride for multi-lib packages.. 8327 // By definition, we need to copy both 32 and 64 bit libraries for 8328 // such packages. 8329 if (pkg.cpuAbiOverride != null 8330 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8331 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8332 } 8333 8334 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8335 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8336 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8337 if (extractLibs) { 8338 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8339 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8340 useIsaSpecificSubdirs); 8341 } else { 8342 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8343 } 8344 } 8345 8346 maybeThrowExceptionForMultiArchCopy( 8347 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8348 8349 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8350 if (extractLibs) { 8351 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8352 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8353 useIsaSpecificSubdirs); 8354 } else { 8355 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8356 } 8357 } 8358 8359 maybeThrowExceptionForMultiArchCopy( 8360 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8361 8362 if (abi64 >= 0) { 8363 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8364 } 8365 8366 if (abi32 >= 0) { 8367 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8368 if (abi64 >= 0) { 8369 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8370 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8371 pkg.applicationInfo.primaryCpuAbi = abi; 8372 } else { 8373 pkg.applicationInfo.secondaryCpuAbi = abi; 8374 } 8375 } else { 8376 pkg.applicationInfo.primaryCpuAbi = abi; 8377 } 8378 } 8379 8380 } else { 8381 String[] abiList = (cpuAbiOverride != null) ? 8382 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8383 8384 // Enable gross and lame hacks for apps that are built with old 8385 // SDK tools. We must scan their APKs for renderscript bitcode and 8386 // not launch them if it's present. Don't bother checking on devices 8387 // that don't have 64 bit support. 8388 boolean needsRenderScriptOverride = false; 8389 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8390 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8391 abiList = Build.SUPPORTED_32_BIT_ABIS; 8392 needsRenderScriptOverride = true; 8393 } 8394 8395 final int copyRet; 8396 if (extractLibs) { 8397 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8398 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8399 } else { 8400 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8401 } 8402 8403 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8404 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8405 "Error unpackaging native libs for app, errorCode=" + copyRet); 8406 } 8407 8408 if (copyRet >= 0) { 8409 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8410 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8411 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8412 } else if (needsRenderScriptOverride) { 8413 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8414 } 8415 } 8416 } catch (IOException ioe) { 8417 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8418 } finally { 8419 IoUtils.closeQuietly(handle); 8420 } 8421 8422 // Now that we've calculated the ABIs and determined if it's an internal app, 8423 // we will go ahead and populate the nativeLibraryPath. 8424 setNativeLibraryPaths(pkg); 8425 } 8426 8427 /** 8428 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8429 * i.e, so that all packages can be run inside a single process if required. 8430 * 8431 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8432 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8433 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8434 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8435 * updating a package that belongs to a shared user. 8436 * 8437 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8438 * adds unnecessary complexity. 8439 */ 8440 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8441 PackageParser.Package scannedPackage, boolean bootComplete) { 8442 String requiredInstructionSet = null; 8443 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8444 requiredInstructionSet = VMRuntime.getInstructionSet( 8445 scannedPackage.applicationInfo.primaryCpuAbi); 8446 } 8447 8448 PackageSetting requirer = null; 8449 for (PackageSetting ps : packagesForUser) { 8450 // If packagesForUser contains scannedPackage, we skip it. This will happen 8451 // when scannedPackage is an update of an existing package. Without this check, 8452 // we will never be able to change the ABI of any package belonging to a shared 8453 // user, even if it's compatible with other packages. 8454 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8455 if (ps.primaryCpuAbiString == null) { 8456 continue; 8457 } 8458 8459 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8460 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8461 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8462 // this but there's not much we can do. 8463 String errorMessage = "Instruction set mismatch, " 8464 + ((requirer == null) ? "[caller]" : requirer) 8465 + " requires " + requiredInstructionSet + " whereas " + ps 8466 + " requires " + instructionSet; 8467 Slog.w(TAG, errorMessage); 8468 } 8469 8470 if (requiredInstructionSet == null) { 8471 requiredInstructionSet = instructionSet; 8472 requirer = ps; 8473 } 8474 } 8475 } 8476 8477 if (requiredInstructionSet != null) { 8478 String adjustedAbi; 8479 if (requirer != null) { 8480 // requirer != null implies that either scannedPackage was null or that scannedPackage 8481 // did not require an ABI, in which case we have to adjust scannedPackage to match 8482 // the ABI of the set (which is the same as requirer's ABI) 8483 adjustedAbi = requirer.primaryCpuAbiString; 8484 if (scannedPackage != null) { 8485 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8486 } 8487 } else { 8488 // requirer == null implies that we're updating all ABIs in the set to 8489 // match scannedPackage. 8490 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8491 } 8492 8493 for (PackageSetting ps : packagesForUser) { 8494 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8495 if (ps.primaryCpuAbiString != null) { 8496 continue; 8497 } 8498 8499 ps.primaryCpuAbiString = adjustedAbi; 8500 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8501 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8502 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8503 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8504 + " (requirer=" 8505 + (requirer == null ? "null" : requirer.pkg.packageName) 8506 + ", scannedPackage=" 8507 + (scannedPackage != null ? scannedPackage.packageName : "null") 8508 + ")"); 8509 try { 8510 mInstaller.rmdex(ps.codePathString, 8511 getDexCodeInstructionSet(getPreferredInstructionSet())); 8512 } catch (InstallerException ignored) { 8513 } 8514 } 8515 } 8516 } 8517 } 8518 } 8519 8520 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8521 synchronized (mPackages) { 8522 mResolverReplaced = true; 8523 // Set up information for custom user intent resolution activity. 8524 mResolveActivity.applicationInfo = pkg.applicationInfo; 8525 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8526 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8527 mResolveActivity.processName = pkg.applicationInfo.packageName; 8528 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8529 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8530 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8531 mResolveActivity.theme = 0; 8532 mResolveActivity.exported = true; 8533 mResolveActivity.enabled = true; 8534 mResolveInfo.activityInfo = mResolveActivity; 8535 mResolveInfo.priority = 0; 8536 mResolveInfo.preferredOrder = 0; 8537 mResolveInfo.match = 0; 8538 mResolveComponentName = mCustomResolverComponentName; 8539 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8540 mResolveComponentName); 8541 } 8542 } 8543 8544 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8545 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8546 8547 // Set up information for ephemeral installer activity 8548 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8549 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8550 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8551 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8552 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8553 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8554 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8555 mEphemeralInstallerActivity.theme = 0; 8556 mEphemeralInstallerActivity.exported = true; 8557 mEphemeralInstallerActivity.enabled = true; 8558 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8559 mEphemeralInstallerInfo.priority = 0; 8560 mEphemeralInstallerInfo.preferredOrder = 0; 8561 mEphemeralInstallerInfo.match = 0; 8562 8563 if (DEBUG_EPHEMERAL) { 8564 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8565 } 8566 } 8567 8568 private static String calculateBundledApkRoot(final String codePathString) { 8569 final File codePath = new File(codePathString); 8570 final File codeRoot; 8571 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8572 codeRoot = Environment.getRootDirectory(); 8573 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8574 codeRoot = Environment.getOemDirectory(); 8575 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8576 codeRoot = Environment.getVendorDirectory(); 8577 } else { 8578 // Unrecognized code path; take its top real segment as the apk root: 8579 // e.g. /something/app/blah.apk => /something 8580 try { 8581 File f = codePath.getCanonicalFile(); 8582 File parent = f.getParentFile(); // non-null because codePath is a file 8583 File tmp; 8584 while ((tmp = parent.getParentFile()) != null) { 8585 f = parent; 8586 parent = tmp; 8587 } 8588 codeRoot = f; 8589 Slog.w(TAG, "Unrecognized code path " 8590 + codePath + " - using " + codeRoot); 8591 } catch (IOException e) { 8592 // Can't canonicalize the code path -- shenanigans? 8593 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8594 return Environment.getRootDirectory().getPath(); 8595 } 8596 } 8597 return codeRoot.getPath(); 8598 } 8599 8600 /** 8601 * Derive and set the location of native libraries for the given package, 8602 * which varies depending on where and how the package was installed. 8603 */ 8604 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8605 final ApplicationInfo info = pkg.applicationInfo; 8606 final String codePath = pkg.codePath; 8607 final File codeFile = new File(codePath); 8608 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8609 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8610 8611 info.nativeLibraryRootDir = null; 8612 info.nativeLibraryRootRequiresIsa = false; 8613 info.nativeLibraryDir = null; 8614 info.secondaryNativeLibraryDir = null; 8615 8616 if (isApkFile(codeFile)) { 8617 // Monolithic install 8618 if (bundledApp) { 8619 // If "/system/lib64/apkname" exists, assume that is the per-package 8620 // native library directory to use; otherwise use "/system/lib/apkname". 8621 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8622 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8623 getPrimaryInstructionSet(info)); 8624 8625 // This is a bundled system app so choose the path based on the ABI. 8626 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8627 // is just the default path. 8628 final String apkName = deriveCodePathName(codePath); 8629 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8630 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8631 apkName).getAbsolutePath(); 8632 8633 if (info.secondaryCpuAbi != null) { 8634 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8635 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8636 secondaryLibDir, apkName).getAbsolutePath(); 8637 } 8638 } else if (asecApp) { 8639 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8640 .getAbsolutePath(); 8641 } else { 8642 final String apkName = deriveCodePathName(codePath); 8643 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8644 .getAbsolutePath(); 8645 } 8646 8647 info.nativeLibraryRootRequiresIsa = false; 8648 info.nativeLibraryDir = info.nativeLibraryRootDir; 8649 } else { 8650 // Cluster install 8651 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8652 info.nativeLibraryRootRequiresIsa = true; 8653 8654 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8655 getPrimaryInstructionSet(info)).getAbsolutePath(); 8656 8657 if (info.secondaryCpuAbi != null) { 8658 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8659 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8660 } 8661 } 8662 } 8663 8664 /** 8665 * Calculate the abis and roots for a bundled app. These can uniquely 8666 * be determined from the contents of the system partition, i.e whether 8667 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8668 * of this information, and instead assume that the system was built 8669 * sensibly. 8670 */ 8671 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8672 PackageSetting pkgSetting) { 8673 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8674 8675 // If "/system/lib64/apkname" exists, assume that is the per-package 8676 // native library directory to use; otherwise use "/system/lib/apkname". 8677 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8678 setBundledAppAbi(pkg, apkRoot, apkName); 8679 // pkgSetting might be null during rescan following uninstall of updates 8680 // to a bundled app, so accommodate that possibility. The settings in 8681 // that case will be established later from the parsed package. 8682 // 8683 // If the settings aren't null, sync them up with what we've just derived. 8684 // note that apkRoot isn't stored in the package settings. 8685 if (pkgSetting != null) { 8686 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8687 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8688 } 8689 } 8690 8691 /** 8692 * Deduces the ABI of a bundled app and sets the relevant fields on the 8693 * parsed pkg object. 8694 * 8695 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8696 * under which system libraries are installed. 8697 * @param apkName the name of the installed package. 8698 */ 8699 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8700 final File codeFile = new File(pkg.codePath); 8701 8702 final boolean has64BitLibs; 8703 final boolean has32BitLibs; 8704 if (isApkFile(codeFile)) { 8705 // Monolithic install 8706 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8707 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8708 } else { 8709 // Cluster install 8710 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8711 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8712 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8713 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8714 has64BitLibs = (new File(rootDir, isa)).exists(); 8715 } else { 8716 has64BitLibs = false; 8717 } 8718 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8719 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8720 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8721 has32BitLibs = (new File(rootDir, isa)).exists(); 8722 } else { 8723 has32BitLibs = false; 8724 } 8725 } 8726 8727 if (has64BitLibs && !has32BitLibs) { 8728 // The package has 64 bit libs, but not 32 bit libs. Its primary 8729 // ABI should be 64 bit. We can safely assume here that the bundled 8730 // native libraries correspond to the most preferred ABI in the list. 8731 8732 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8733 pkg.applicationInfo.secondaryCpuAbi = null; 8734 } else if (has32BitLibs && !has64BitLibs) { 8735 // The package has 32 bit libs but not 64 bit libs. Its primary 8736 // ABI should be 32 bit. 8737 8738 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8739 pkg.applicationInfo.secondaryCpuAbi = null; 8740 } else if (has32BitLibs && has64BitLibs) { 8741 // The application has both 64 and 32 bit bundled libraries. We check 8742 // here that the app declares multiArch support, and warn if it doesn't. 8743 // 8744 // We will be lenient here and record both ABIs. The primary will be the 8745 // ABI that's higher on the list, i.e, a device that's configured to prefer 8746 // 64 bit apps will see a 64 bit primary ABI, 8747 8748 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8749 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8750 } 8751 8752 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8753 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8754 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8755 } else { 8756 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8757 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8758 } 8759 } else { 8760 pkg.applicationInfo.primaryCpuAbi = null; 8761 pkg.applicationInfo.secondaryCpuAbi = null; 8762 } 8763 } 8764 8765 private void killPackage(PackageParser.Package pkg, String reason) { 8766 // Kill the parent package 8767 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8768 // Kill the child packages 8769 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8770 for (int i = 0; i < childCount; i++) { 8771 PackageParser.Package childPkg = pkg.childPackages.get(i); 8772 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8773 } 8774 } 8775 8776 private void killApplication(String pkgName, int appId, String reason) { 8777 // Request the ActivityManager to kill the process(only for existing packages) 8778 // so that we do not end up in a confused state while the user is still using the older 8779 // version of the application while the new one gets installed. 8780 IActivityManager am = ActivityManagerNative.getDefault(); 8781 if (am != null) { 8782 try { 8783 am.killApplicationWithAppId(pkgName, appId, reason); 8784 } catch (RemoteException e) { 8785 } 8786 } 8787 } 8788 8789 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 8790 // Remove the parent package setting 8791 PackageSetting ps = (PackageSetting) pkg.mExtras; 8792 if (ps != null) { 8793 removePackageLI(ps, chatty); 8794 } 8795 // Remove the child package setting 8796 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8797 for (int i = 0; i < childCount; i++) { 8798 PackageParser.Package childPkg = pkg.childPackages.get(i); 8799 ps = (PackageSetting) childPkg.mExtras; 8800 if (ps != null) { 8801 removePackageLI(ps, chatty); 8802 } 8803 } 8804 } 8805 8806 void removePackageLI(PackageSetting ps, boolean chatty) { 8807 if (DEBUG_INSTALL) { 8808 if (chatty) 8809 Log.d(TAG, "Removing package " + ps.name); 8810 } 8811 8812 // writer 8813 synchronized (mPackages) { 8814 mPackages.remove(ps.name); 8815 final PackageParser.Package pkg = ps.pkg; 8816 if (pkg != null) { 8817 cleanPackageDataStructuresLILPw(pkg, chatty); 8818 } 8819 } 8820 } 8821 8822 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8823 if (DEBUG_INSTALL) { 8824 if (chatty) 8825 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8826 } 8827 8828 // writer 8829 synchronized (mPackages) { 8830 // Remove the parent package 8831 mPackages.remove(pkg.applicationInfo.packageName); 8832 cleanPackageDataStructuresLILPw(pkg, chatty); 8833 8834 // Remove the child packages 8835 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8836 for (int i = 0; i < childCount; i++) { 8837 PackageParser.Package childPkg = pkg.childPackages.get(i); 8838 mPackages.remove(childPkg.applicationInfo.packageName); 8839 cleanPackageDataStructuresLILPw(childPkg, chatty); 8840 } 8841 } 8842 } 8843 8844 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8845 int N = pkg.providers.size(); 8846 StringBuilder r = null; 8847 int i; 8848 for (i=0; i<N; i++) { 8849 PackageParser.Provider p = pkg.providers.get(i); 8850 mProviders.removeProvider(p); 8851 if (p.info.authority == null) { 8852 8853 /* There was another ContentProvider with this authority when 8854 * this app was installed so this authority is null, 8855 * Ignore it as we don't have to unregister the provider. 8856 */ 8857 continue; 8858 } 8859 String names[] = p.info.authority.split(";"); 8860 for (int j = 0; j < names.length; j++) { 8861 if (mProvidersByAuthority.get(names[j]) == p) { 8862 mProvidersByAuthority.remove(names[j]); 8863 if (DEBUG_REMOVE) { 8864 if (chatty) 8865 Log.d(TAG, "Unregistered content provider: " + names[j] 8866 + ", className = " + p.info.name + ", isSyncable = " 8867 + p.info.isSyncable); 8868 } 8869 } 8870 } 8871 if (DEBUG_REMOVE && chatty) { 8872 if (r == null) { 8873 r = new StringBuilder(256); 8874 } else { 8875 r.append(' '); 8876 } 8877 r.append(p.info.name); 8878 } 8879 } 8880 if (r != null) { 8881 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8882 } 8883 8884 N = pkg.services.size(); 8885 r = null; 8886 for (i=0; i<N; i++) { 8887 PackageParser.Service s = pkg.services.get(i); 8888 mServices.removeService(s); 8889 if (chatty) { 8890 if (r == null) { 8891 r = new StringBuilder(256); 8892 } else { 8893 r.append(' '); 8894 } 8895 r.append(s.info.name); 8896 } 8897 } 8898 if (r != null) { 8899 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8900 } 8901 8902 N = pkg.receivers.size(); 8903 r = null; 8904 for (i=0; i<N; i++) { 8905 PackageParser.Activity a = pkg.receivers.get(i); 8906 mReceivers.removeActivity(a, "receiver"); 8907 if (DEBUG_REMOVE && chatty) { 8908 if (r == null) { 8909 r = new StringBuilder(256); 8910 } else { 8911 r.append(' '); 8912 } 8913 r.append(a.info.name); 8914 } 8915 } 8916 if (r != null) { 8917 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8918 } 8919 8920 N = pkg.activities.size(); 8921 r = null; 8922 for (i=0; i<N; i++) { 8923 PackageParser.Activity a = pkg.activities.get(i); 8924 mActivities.removeActivity(a, "activity"); 8925 if (DEBUG_REMOVE && chatty) { 8926 if (r == null) { 8927 r = new StringBuilder(256); 8928 } else { 8929 r.append(' '); 8930 } 8931 r.append(a.info.name); 8932 } 8933 } 8934 if (r != null) { 8935 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8936 } 8937 8938 N = pkg.permissions.size(); 8939 r = null; 8940 for (i=0; i<N; i++) { 8941 PackageParser.Permission p = pkg.permissions.get(i); 8942 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8943 if (bp == null) { 8944 bp = mSettings.mPermissionTrees.get(p.info.name); 8945 } 8946 if (bp != null && bp.perm == p) { 8947 bp.perm = null; 8948 if (DEBUG_REMOVE && chatty) { 8949 if (r == null) { 8950 r = new StringBuilder(256); 8951 } else { 8952 r.append(' '); 8953 } 8954 r.append(p.info.name); 8955 } 8956 } 8957 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8958 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8959 if (appOpPkgs != null) { 8960 appOpPkgs.remove(pkg.packageName); 8961 } 8962 } 8963 } 8964 if (r != null) { 8965 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8966 } 8967 8968 N = pkg.requestedPermissions.size(); 8969 r = null; 8970 for (i=0; i<N; i++) { 8971 String perm = pkg.requestedPermissions.get(i); 8972 BasePermission bp = mSettings.mPermissions.get(perm); 8973 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8974 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8975 if (appOpPkgs != null) { 8976 appOpPkgs.remove(pkg.packageName); 8977 if (appOpPkgs.isEmpty()) { 8978 mAppOpPermissionPackages.remove(perm); 8979 } 8980 } 8981 } 8982 } 8983 if (r != null) { 8984 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8985 } 8986 8987 N = pkg.instrumentation.size(); 8988 r = null; 8989 for (i=0; i<N; i++) { 8990 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8991 mInstrumentation.remove(a.getComponentName()); 8992 if (DEBUG_REMOVE && chatty) { 8993 if (r == null) { 8994 r = new StringBuilder(256); 8995 } else { 8996 r.append(' '); 8997 } 8998 r.append(a.info.name); 8999 } 9000 } 9001 if (r != null) { 9002 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9003 } 9004 9005 r = null; 9006 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9007 // Only system apps can hold shared libraries. 9008 if (pkg.libraryNames != null) { 9009 for (i=0; i<pkg.libraryNames.size(); i++) { 9010 String name = pkg.libraryNames.get(i); 9011 SharedLibraryEntry cur = mSharedLibraries.get(name); 9012 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9013 mSharedLibraries.remove(name); 9014 if (DEBUG_REMOVE && chatty) { 9015 if (r == null) { 9016 r = new StringBuilder(256); 9017 } else { 9018 r.append(' '); 9019 } 9020 r.append(name); 9021 } 9022 } 9023 } 9024 } 9025 } 9026 if (r != null) { 9027 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9028 } 9029 } 9030 9031 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9032 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9033 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9034 return true; 9035 } 9036 } 9037 return false; 9038 } 9039 9040 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9041 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9042 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9043 9044 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9045 // Update the parent permissions 9046 updatePermissionsLPw(pkg.packageName, pkg, flags); 9047 // Update the child permissions 9048 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9049 for (int i = 0; i < childCount; i++) { 9050 PackageParser.Package childPkg = pkg.childPackages.get(i); 9051 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9052 } 9053 } 9054 9055 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9056 int flags) { 9057 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9058 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9059 } 9060 9061 private void updatePermissionsLPw(String changingPkg, 9062 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9063 // Make sure there are no dangling permission trees. 9064 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9065 while (it.hasNext()) { 9066 final BasePermission bp = it.next(); 9067 if (bp.packageSetting == null) { 9068 // We may not yet have parsed the package, so just see if 9069 // we still know about its settings. 9070 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9071 } 9072 if (bp.packageSetting == null) { 9073 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9074 + " from package " + bp.sourcePackage); 9075 it.remove(); 9076 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9077 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9078 Slog.i(TAG, "Removing old permission tree: " + bp.name 9079 + " from package " + bp.sourcePackage); 9080 flags |= UPDATE_PERMISSIONS_ALL; 9081 it.remove(); 9082 } 9083 } 9084 } 9085 9086 // Make sure all dynamic permissions have been assigned to a package, 9087 // and make sure there are no dangling permissions. 9088 it = mSettings.mPermissions.values().iterator(); 9089 while (it.hasNext()) { 9090 final BasePermission bp = it.next(); 9091 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9092 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9093 + bp.name + " pkg=" + bp.sourcePackage 9094 + " info=" + bp.pendingInfo); 9095 if (bp.packageSetting == null && bp.pendingInfo != null) { 9096 final BasePermission tree = findPermissionTreeLP(bp.name); 9097 if (tree != null && tree.perm != null) { 9098 bp.packageSetting = tree.packageSetting; 9099 bp.perm = new PackageParser.Permission(tree.perm.owner, 9100 new PermissionInfo(bp.pendingInfo)); 9101 bp.perm.info.packageName = tree.perm.info.packageName; 9102 bp.perm.info.name = bp.name; 9103 bp.uid = tree.uid; 9104 } 9105 } 9106 } 9107 if (bp.packageSetting == null) { 9108 // We may not yet have parsed the package, so just see if 9109 // we still know about its settings. 9110 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9111 } 9112 if (bp.packageSetting == null) { 9113 Slog.w(TAG, "Removing dangling permission: " + bp.name 9114 + " from package " + bp.sourcePackage); 9115 it.remove(); 9116 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9117 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9118 Slog.i(TAG, "Removing old permission: " + bp.name 9119 + " from package " + bp.sourcePackage); 9120 flags |= UPDATE_PERMISSIONS_ALL; 9121 it.remove(); 9122 } 9123 } 9124 } 9125 9126 // Now update the permissions for all packages, in particular 9127 // replace the granted permissions of the system packages. 9128 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9129 for (PackageParser.Package pkg : mPackages.values()) { 9130 if (pkg != pkgInfo) { 9131 // Only replace for packages on requested volume 9132 final String volumeUuid = getVolumeUuidForPackage(pkg); 9133 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9134 && Objects.equals(replaceVolumeUuid, volumeUuid); 9135 grantPermissionsLPw(pkg, replace, changingPkg); 9136 } 9137 } 9138 } 9139 9140 if (pkgInfo != null) { 9141 // Only replace for packages on requested volume 9142 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9143 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9144 && Objects.equals(replaceVolumeUuid, volumeUuid); 9145 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9146 } 9147 } 9148 9149 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9150 String packageOfInterest) { 9151 // IMPORTANT: There are two types of permissions: install and runtime. 9152 // Install time permissions are granted when the app is installed to 9153 // all device users and users added in the future. Runtime permissions 9154 // are granted at runtime explicitly to specific users. Normal and signature 9155 // protected permissions are install time permissions. Dangerous permissions 9156 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9157 // otherwise they are runtime permissions. This function does not manage 9158 // runtime permissions except for the case an app targeting Lollipop MR1 9159 // being upgraded to target a newer SDK, in which case dangerous permissions 9160 // are transformed from install time to runtime ones. 9161 9162 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9163 if (ps == null) { 9164 return; 9165 } 9166 9167 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9168 9169 PermissionsState permissionsState = ps.getPermissionsState(); 9170 PermissionsState origPermissions = permissionsState; 9171 9172 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9173 9174 boolean runtimePermissionsRevoked = false; 9175 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9176 9177 boolean changedInstallPermission = false; 9178 9179 if (replace) { 9180 ps.installPermissionsFixed = false; 9181 if (!ps.isSharedUser()) { 9182 origPermissions = new PermissionsState(permissionsState); 9183 permissionsState.reset(); 9184 } else { 9185 // We need to know only about runtime permission changes since the 9186 // calling code always writes the install permissions state but 9187 // the runtime ones are written only if changed. The only cases of 9188 // changed runtime permissions here are promotion of an install to 9189 // runtime and revocation of a runtime from a shared user. 9190 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9191 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9192 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9193 runtimePermissionsRevoked = true; 9194 } 9195 } 9196 } 9197 9198 permissionsState.setGlobalGids(mGlobalGids); 9199 9200 final int N = pkg.requestedPermissions.size(); 9201 for (int i=0; i<N; i++) { 9202 final String name = pkg.requestedPermissions.get(i); 9203 final BasePermission bp = mSettings.mPermissions.get(name); 9204 9205 if (DEBUG_INSTALL) { 9206 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9207 } 9208 9209 if (bp == null || bp.packageSetting == null) { 9210 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9211 Slog.w(TAG, "Unknown permission " + name 9212 + " in package " + pkg.packageName); 9213 } 9214 continue; 9215 } 9216 9217 final String perm = bp.name; 9218 boolean allowedSig = false; 9219 int grant = GRANT_DENIED; 9220 9221 // Keep track of app op permissions. 9222 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9223 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9224 if (pkgs == null) { 9225 pkgs = new ArraySet<>(); 9226 mAppOpPermissionPackages.put(bp.name, pkgs); 9227 } 9228 pkgs.add(pkg.packageName); 9229 } 9230 9231 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9232 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9233 >= Build.VERSION_CODES.M; 9234 switch (level) { 9235 case PermissionInfo.PROTECTION_NORMAL: { 9236 // For all apps normal permissions are install time ones. 9237 grant = GRANT_INSTALL; 9238 } break; 9239 9240 case PermissionInfo.PROTECTION_DANGEROUS: { 9241 // If a permission review is required for legacy apps we represent 9242 // their permissions as always granted runtime ones since we need 9243 // to keep the review required permission flag per user while an 9244 // install permission's state is shared across all users. 9245 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9246 // For legacy apps dangerous permissions are install time ones. 9247 grant = GRANT_INSTALL; 9248 } else if (origPermissions.hasInstallPermission(bp.name)) { 9249 // For legacy apps that became modern, install becomes runtime. 9250 grant = GRANT_UPGRADE; 9251 } else if (mPromoteSystemApps 9252 && isSystemApp(ps) 9253 && mExistingSystemPackages.contains(ps.name)) { 9254 // For legacy system apps, install becomes runtime. 9255 // We cannot check hasInstallPermission() for system apps since those 9256 // permissions were granted implicitly and not persisted pre-M. 9257 grant = GRANT_UPGRADE; 9258 } else { 9259 // For modern apps keep runtime permissions unchanged. 9260 grant = GRANT_RUNTIME; 9261 } 9262 } break; 9263 9264 case PermissionInfo.PROTECTION_SIGNATURE: { 9265 // For all apps signature permissions are install time ones. 9266 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9267 if (allowedSig) { 9268 grant = GRANT_INSTALL; 9269 } 9270 } break; 9271 } 9272 9273 if (DEBUG_INSTALL) { 9274 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9275 } 9276 9277 if (grant != GRANT_DENIED) { 9278 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9279 // If this is an existing, non-system package, then 9280 // we can't add any new permissions to it. 9281 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9282 // Except... if this is a permission that was added 9283 // to the platform (note: need to only do this when 9284 // updating the platform). 9285 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9286 grant = GRANT_DENIED; 9287 } 9288 } 9289 } 9290 9291 switch (grant) { 9292 case GRANT_INSTALL: { 9293 // Revoke this as runtime permission to handle the case of 9294 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9295 for (int userId : UserManagerService.getInstance().getUserIds()) { 9296 if (origPermissions.getRuntimePermissionState( 9297 bp.name, userId) != null) { 9298 // Revoke the runtime permission and clear the flags. 9299 origPermissions.revokeRuntimePermission(bp, userId); 9300 origPermissions.updatePermissionFlags(bp, userId, 9301 PackageManager.MASK_PERMISSION_FLAGS, 0); 9302 // If we revoked a permission permission, we have to write. 9303 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9304 changedRuntimePermissionUserIds, userId); 9305 } 9306 } 9307 // Grant an install permission. 9308 if (permissionsState.grantInstallPermission(bp) != 9309 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9310 changedInstallPermission = true; 9311 } 9312 } break; 9313 9314 case GRANT_RUNTIME: { 9315 // Grant previously granted runtime permissions. 9316 for (int userId : UserManagerService.getInstance().getUserIds()) { 9317 PermissionState permissionState = origPermissions 9318 .getRuntimePermissionState(bp.name, userId); 9319 int flags = permissionState != null 9320 ? permissionState.getFlags() : 0; 9321 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9322 if (permissionsState.grantRuntimePermission(bp, userId) == 9323 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9324 // If we cannot put the permission as it was, we have to write. 9325 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9326 changedRuntimePermissionUserIds, userId); 9327 } 9328 // If the app supports runtime permissions no need for a review. 9329 if (Build.PERMISSIONS_REVIEW_REQUIRED 9330 && appSupportsRuntimePermissions 9331 && (flags & PackageManager 9332 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9333 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9334 // Since we changed the flags, we have to write. 9335 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9336 changedRuntimePermissionUserIds, userId); 9337 } 9338 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9339 && !appSupportsRuntimePermissions) { 9340 // For legacy apps that need a permission review, every new 9341 // runtime permission is granted but it is pending a review. 9342 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9343 permissionsState.grantRuntimePermission(bp, userId); 9344 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9345 // We changed the permission and flags, hence have to write. 9346 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9347 changedRuntimePermissionUserIds, userId); 9348 } 9349 } 9350 // Propagate the permission flags. 9351 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9352 } 9353 } break; 9354 9355 case GRANT_UPGRADE: { 9356 // Grant runtime permissions for a previously held install permission. 9357 PermissionState permissionState = origPermissions 9358 .getInstallPermissionState(bp.name); 9359 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9360 9361 if (origPermissions.revokeInstallPermission(bp) 9362 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9363 // We will be transferring the permission flags, so clear them. 9364 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9365 PackageManager.MASK_PERMISSION_FLAGS, 0); 9366 changedInstallPermission = true; 9367 } 9368 9369 // If the permission is not to be promoted to runtime we ignore it and 9370 // also its other flags as they are not applicable to install permissions. 9371 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9372 for (int userId : currentUserIds) { 9373 if (permissionsState.grantRuntimePermission(bp, userId) != 9374 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9375 // Transfer the permission flags. 9376 permissionsState.updatePermissionFlags(bp, userId, 9377 flags, flags); 9378 // If we granted the permission, we have to write. 9379 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9380 changedRuntimePermissionUserIds, userId); 9381 } 9382 } 9383 } 9384 } break; 9385 9386 default: { 9387 if (packageOfInterest == null 9388 || packageOfInterest.equals(pkg.packageName)) { 9389 Slog.w(TAG, "Not granting permission " + perm 9390 + " to package " + pkg.packageName 9391 + " because it was previously installed without"); 9392 } 9393 } break; 9394 } 9395 } else { 9396 if (permissionsState.revokeInstallPermission(bp) != 9397 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9398 // Also drop the permission flags. 9399 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9400 PackageManager.MASK_PERMISSION_FLAGS, 0); 9401 changedInstallPermission = true; 9402 Slog.i(TAG, "Un-granting permission " + perm 9403 + " from package " + pkg.packageName 9404 + " (protectionLevel=" + bp.protectionLevel 9405 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9406 + ")"); 9407 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9408 // Don't print warning for app op permissions, since it is fine for them 9409 // not to be granted, there is a UI for the user to decide. 9410 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9411 Slog.w(TAG, "Not granting permission " + perm 9412 + " to package " + pkg.packageName 9413 + " (protectionLevel=" + bp.protectionLevel 9414 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9415 + ")"); 9416 } 9417 } 9418 } 9419 } 9420 9421 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9422 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9423 // This is the first that we have heard about this package, so the 9424 // permissions we have now selected are fixed until explicitly 9425 // changed. 9426 ps.installPermissionsFixed = true; 9427 } 9428 9429 // Persist the runtime permissions state for users with changes. If permissions 9430 // were revoked because no app in the shared user declares them we have to 9431 // write synchronously to avoid losing runtime permissions state. 9432 for (int userId : changedRuntimePermissionUserIds) { 9433 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9434 } 9435 9436 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9437 } 9438 9439 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9440 boolean allowed = false; 9441 final int NP = PackageParser.NEW_PERMISSIONS.length; 9442 for (int ip=0; ip<NP; ip++) { 9443 final PackageParser.NewPermissionInfo npi 9444 = PackageParser.NEW_PERMISSIONS[ip]; 9445 if (npi.name.equals(perm) 9446 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9447 allowed = true; 9448 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9449 + pkg.packageName); 9450 break; 9451 } 9452 } 9453 return allowed; 9454 } 9455 9456 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9457 BasePermission bp, PermissionsState origPermissions) { 9458 boolean allowed; 9459 allowed = (compareSignatures( 9460 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9461 == PackageManager.SIGNATURE_MATCH) 9462 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9463 == PackageManager.SIGNATURE_MATCH); 9464 if (!allowed && (bp.protectionLevel 9465 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9466 if (isSystemApp(pkg)) { 9467 // For updated system applications, a system permission 9468 // is granted only if it had been defined by the original application. 9469 if (pkg.isUpdatedSystemApp()) { 9470 final PackageSetting sysPs = mSettings 9471 .getDisabledSystemPkgLPr(pkg.packageName); 9472 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9473 // If the original was granted this permission, we take 9474 // that grant decision as read and propagate it to the 9475 // update. 9476 if (sysPs.isPrivileged()) { 9477 allowed = true; 9478 } 9479 } else { 9480 // The system apk may have been updated with an older 9481 // version of the one on the data partition, but which 9482 // granted a new system permission that it didn't have 9483 // before. In this case we do want to allow the app to 9484 // now get the new permission if the ancestral apk is 9485 // privileged to get it. 9486 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9487 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9488 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9489 allowed = true; 9490 break; 9491 } 9492 } 9493 } 9494 // Also if a privileged parent package on the system image or any of 9495 // its children requested a privileged permission, the updated child 9496 // packages can also get the permission. 9497 if (pkg.parentPackage != null) { 9498 final PackageSetting disabledSysParentPs = mSettings 9499 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9500 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9501 && disabledSysParentPs.isPrivileged()) { 9502 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9503 allowed = true; 9504 } else if (disabledSysParentPs.pkg.childPackages != null) { 9505 final int count = disabledSysParentPs.pkg.childPackages.size(); 9506 for (int i = 0; i < count; i++) { 9507 PackageParser.Package disabledSysChildPkg = 9508 disabledSysParentPs.pkg.childPackages.get(i); 9509 if (isPackageRequestingPermission(disabledSysChildPkg, 9510 perm)) { 9511 allowed = true; 9512 break; 9513 } 9514 } 9515 } 9516 } 9517 } 9518 } 9519 } else { 9520 allowed = isPrivilegedApp(pkg); 9521 } 9522 } 9523 } 9524 if (!allowed) { 9525 if (!allowed && (bp.protectionLevel 9526 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9527 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9528 // If this was a previously normal/dangerous permission that got moved 9529 // to a system permission as part of the runtime permission redesign, then 9530 // we still want to blindly grant it to old apps. 9531 allowed = true; 9532 } 9533 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9534 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9535 // If this permission is to be granted to the system installer and 9536 // this app is an installer, then it gets the permission. 9537 allowed = true; 9538 } 9539 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9540 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9541 // If this permission is to be granted to the system verifier and 9542 // this app is a verifier, then it gets the permission. 9543 allowed = true; 9544 } 9545 if (!allowed && (bp.protectionLevel 9546 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9547 && isSystemApp(pkg)) { 9548 // Any pre-installed system app is allowed to get this permission. 9549 allowed = true; 9550 } 9551 if (!allowed && (bp.protectionLevel 9552 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9553 // For development permissions, a development permission 9554 // is granted only if it was already granted. 9555 allowed = origPermissions.hasInstallPermission(perm); 9556 } 9557 } 9558 return allowed; 9559 } 9560 9561 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9562 final int permCount = pkg.requestedPermissions.size(); 9563 for (int j = 0; j < permCount; j++) { 9564 String requestedPermission = pkg.requestedPermissions.get(j); 9565 if (permission.equals(requestedPermission)) { 9566 return true; 9567 } 9568 } 9569 return false; 9570 } 9571 9572 final class ActivityIntentResolver 9573 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9574 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9575 boolean defaultOnly, int userId) { 9576 if (!sUserManager.exists(userId)) return null; 9577 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9578 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9579 } 9580 9581 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9582 int userId) { 9583 if (!sUserManager.exists(userId)) return null; 9584 mFlags = flags; 9585 return super.queryIntent(intent, resolvedType, 9586 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9587 } 9588 9589 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9590 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9591 if (!sUserManager.exists(userId)) return null; 9592 if (packageActivities == null) { 9593 return null; 9594 } 9595 mFlags = flags; 9596 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9597 final int N = packageActivities.size(); 9598 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9599 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9600 9601 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9602 for (int i = 0; i < N; ++i) { 9603 intentFilters = packageActivities.get(i).intents; 9604 if (intentFilters != null && intentFilters.size() > 0) { 9605 PackageParser.ActivityIntentInfo[] array = 9606 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9607 intentFilters.toArray(array); 9608 listCut.add(array); 9609 } 9610 } 9611 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9612 } 9613 9614 public final void addActivity(PackageParser.Activity a, String type) { 9615 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9616 mActivities.put(a.getComponentName(), a); 9617 if (DEBUG_SHOW_INFO) 9618 Log.v( 9619 TAG, " " + type + " " + 9620 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9621 if (DEBUG_SHOW_INFO) 9622 Log.v(TAG, " Class=" + a.info.name); 9623 final int NI = a.intents.size(); 9624 for (int j=0; j<NI; j++) { 9625 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9626 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9627 intent.setPriority(0); 9628 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9629 + a.className + " with priority > 0, forcing to 0"); 9630 } 9631 if (DEBUG_SHOW_INFO) { 9632 Log.v(TAG, " IntentFilter:"); 9633 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9634 } 9635 if (!intent.debugCheck()) { 9636 Log.w(TAG, "==> For Activity " + a.info.name); 9637 } 9638 addFilter(intent); 9639 } 9640 } 9641 9642 public final void removeActivity(PackageParser.Activity a, String type) { 9643 mActivities.remove(a.getComponentName()); 9644 if (DEBUG_SHOW_INFO) { 9645 Log.v(TAG, " " + type + " " 9646 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9647 : a.info.name) + ":"); 9648 Log.v(TAG, " Class=" + a.info.name); 9649 } 9650 final int NI = a.intents.size(); 9651 for (int j=0; j<NI; j++) { 9652 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9653 if (DEBUG_SHOW_INFO) { 9654 Log.v(TAG, " IntentFilter:"); 9655 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9656 } 9657 removeFilter(intent); 9658 } 9659 } 9660 9661 @Override 9662 protected boolean allowFilterResult( 9663 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9664 ActivityInfo filterAi = filter.activity.info; 9665 for (int i=dest.size()-1; i>=0; i--) { 9666 ActivityInfo destAi = dest.get(i).activityInfo; 9667 if (destAi.name == filterAi.name 9668 && destAi.packageName == filterAi.packageName) { 9669 return false; 9670 } 9671 } 9672 return true; 9673 } 9674 9675 @Override 9676 protected ActivityIntentInfo[] newArray(int size) { 9677 return new ActivityIntentInfo[size]; 9678 } 9679 9680 @Override 9681 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9682 if (!sUserManager.exists(userId)) return true; 9683 PackageParser.Package p = filter.activity.owner; 9684 if (p != null) { 9685 PackageSetting ps = (PackageSetting)p.mExtras; 9686 if (ps != null) { 9687 // System apps are never considered stopped for purposes of 9688 // filtering, because there may be no way for the user to 9689 // actually re-launch them. 9690 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9691 && ps.getStopped(userId); 9692 } 9693 } 9694 return false; 9695 } 9696 9697 @Override 9698 protected boolean isPackageForFilter(String packageName, 9699 PackageParser.ActivityIntentInfo info) { 9700 return packageName.equals(info.activity.owner.packageName); 9701 } 9702 9703 @Override 9704 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9705 int match, int userId) { 9706 if (!sUserManager.exists(userId)) return null; 9707 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9708 return null; 9709 } 9710 final PackageParser.Activity activity = info.activity; 9711 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9712 if (ps == null) { 9713 return null; 9714 } 9715 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9716 ps.readUserState(userId), userId); 9717 if (ai == null) { 9718 return null; 9719 } 9720 final ResolveInfo res = new ResolveInfo(); 9721 res.activityInfo = ai; 9722 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9723 res.filter = info; 9724 } 9725 if (info != null) { 9726 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9727 } 9728 res.priority = info.getPriority(); 9729 res.preferredOrder = activity.owner.mPreferredOrder; 9730 //System.out.println("Result: " + res.activityInfo.className + 9731 // " = " + res.priority); 9732 res.match = match; 9733 res.isDefault = info.hasDefault; 9734 res.labelRes = info.labelRes; 9735 res.nonLocalizedLabel = info.nonLocalizedLabel; 9736 if (userNeedsBadging(userId)) { 9737 res.noResourceId = true; 9738 } else { 9739 res.icon = info.icon; 9740 } 9741 res.iconResourceId = info.icon; 9742 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9743 return res; 9744 } 9745 9746 @Override 9747 protected void sortResults(List<ResolveInfo> results) { 9748 Collections.sort(results, mResolvePrioritySorter); 9749 } 9750 9751 @Override 9752 protected void dumpFilter(PrintWriter out, String prefix, 9753 PackageParser.ActivityIntentInfo filter) { 9754 out.print(prefix); out.print( 9755 Integer.toHexString(System.identityHashCode(filter.activity))); 9756 out.print(' '); 9757 filter.activity.printComponentShortName(out); 9758 out.print(" filter "); 9759 out.println(Integer.toHexString(System.identityHashCode(filter))); 9760 } 9761 9762 @Override 9763 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9764 return filter.activity; 9765 } 9766 9767 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9768 PackageParser.Activity activity = (PackageParser.Activity)label; 9769 out.print(prefix); out.print( 9770 Integer.toHexString(System.identityHashCode(activity))); 9771 out.print(' '); 9772 activity.printComponentShortName(out); 9773 if (count > 1) { 9774 out.print(" ("); out.print(count); out.print(" filters)"); 9775 } 9776 out.println(); 9777 } 9778 9779// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9780// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9781// final List<ResolveInfo> retList = Lists.newArrayList(); 9782// while (i.hasNext()) { 9783// final ResolveInfo resolveInfo = i.next(); 9784// if (isEnabledLP(resolveInfo.activityInfo)) { 9785// retList.add(resolveInfo); 9786// } 9787// } 9788// return retList; 9789// } 9790 9791 // Keys are String (activity class name), values are Activity. 9792 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9793 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9794 private int mFlags; 9795 } 9796 9797 private final class ServiceIntentResolver 9798 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9799 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9800 boolean defaultOnly, int userId) { 9801 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9802 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9803 } 9804 9805 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9806 int userId) { 9807 if (!sUserManager.exists(userId)) return null; 9808 mFlags = flags; 9809 return super.queryIntent(intent, resolvedType, 9810 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9811 } 9812 9813 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9814 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9815 if (!sUserManager.exists(userId)) return null; 9816 if (packageServices == null) { 9817 return null; 9818 } 9819 mFlags = flags; 9820 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9821 final int N = packageServices.size(); 9822 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9823 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9824 9825 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9826 for (int i = 0; i < N; ++i) { 9827 intentFilters = packageServices.get(i).intents; 9828 if (intentFilters != null && intentFilters.size() > 0) { 9829 PackageParser.ServiceIntentInfo[] array = 9830 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9831 intentFilters.toArray(array); 9832 listCut.add(array); 9833 } 9834 } 9835 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9836 } 9837 9838 public final void addService(PackageParser.Service s) { 9839 mServices.put(s.getComponentName(), s); 9840 if (DEBUG_SHOW_INFO) { 9841 Log.v(TAG, " " 9842 + (s.info.nonLocalizedLabel != null 9843 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9844 Log.v(TAG, " Class=" + s.info.name); 9845 } 9846 final int NI = s.intents.size(); 9847 int j; 9848 for (j=0; j<NI; j++) { 9849 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9850 if (DEBUG_SHOW_INFO) { 9851 Log.v(TAG, " IntentFilter:"); 9852 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9853 } 9854 if (!intent.debugCheck()) { 9855 Log.w(TAG, "==> For Service " + s.info.name); 9856 } 9857 addFilter(intent); 9858 } 9859 } 9860 9861 public final void removeService(PackageParser.Service s) { 9862 mServices.remove(s.getComponentName()); 9863 if (DEBUG_SHOW_INFO) { 9864 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9865 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9866 Log.v(TAG, " Class=" + s.info.name); 9867 } 9868 final int NI = s.intents.size(); 9869 int j; 9870 for (j=0; j<NI; j++) { 9871 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9872 if (DEBUG_SHOW_INFO) { 9873 Log.v(TAG, " IntentFilter:"); 9874 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9875 } 9876 removeFilter(intent); 9877 } 9878 } 9879 9880 @Override 9881 protected boolean allowFilterResult( 9882 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9883 ServiceInfo filterSi = filter.service.info; 9884 for (int i=dest.size()-1; i>=0; i--) { 9885 ServiceInfo destAi = dest.get(i).serviceInfo; 9886 if (destAi.name == filterSi.name 9887 && destAi.packageName == filterSi.packageName) { 9888 return false; 9889 } 9890 } 9891 return true; 9892 } 9893 9894 @Override 9895 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9896 return new PackageParser.ServiceIntentInfo[size]; 9897 } 9898 9899 @Override 9900 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9901 if (!sUserManager.exists(userId)) return true; 9902 PackageParser.Package p = filter.service.owner; 9903 if (p != null) { 9904 PackageSetting ps = (PackageSetting)p.mExtras; 9905 if (ps != null) { 9906 // System apps are never considered stopped for purposes of 9907 // filtering, because there may be no way for the user to 9908 // actually re-launch them. 9909 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9910 && ps.getStopped(userId); 9911 } 9912 } 9913 return false; 9914 } 9915 9916 @Override 9917 protected boolean isPackageForFilter(String packageName, 9918 PackageParser.ServiceIntentInfo info) { 9919 return packageName.equals(info.service.owner.packageName); 9920 } 9921 9922 @Override 9923 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9924 int match, int userId) { 9925 if (!sUserManager.exists(userId)) return null; 9926 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9927 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9928 return null; 9929 } 9930 final PackageParser.Service service = info.service; 9931 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9932 if (ps == null) { 9933 return null; 9934 } 9935 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9936 ps.readUserState(userId), userId); 9937 if (si == null) { 9938 return null; 9939 } 9940 final ResolveInfo res = new ResolveInfo(); 9941 res.serviceInfo = si; 9942 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9943 res.filter = filter; 9944 } 9945 res.priority = info.getPriority(); 9946 res.preferredOrder = service.owner.mPreferredOrder; 9947 res.match = match; 9948 res.isDefault = info.hasDefault; 9949 res.labelRes = info.labelRes; 9950 res.nonLocalizedLabel = info.nonLocalizedLabel; 9951 res.icon = info.icon; 9952 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9953 return res; 9954 } 9955 9956 @Override 9957 protected void sortResults(List<ResolveInfo> results) { 9958 Collections.sort(results, mResolvePrioritySorter); 9959 } 9960 9961 @Override 9962 protected void dumpFilter(PrintWriter out, String prefix, 9963 PackageParser.ServiceIntentInfo filter) { 9964 out.print(prefix); out.print( 9965 Integer.toHexString(System.identityHashCode(filter.service))); 9966 out.print(' '); 9967 filter.service.printComponentShortName(out); 9968 out.print(" filter "); 9969 out.println(Integer.toHexString(System.identityHashCode(filter))); 9970 } 9971 9972 @Override 9973 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9974 return filter.service; 9975 } 9976 9977 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9978 PackageParser.Service service = (PackageParser.Service)label; 9979 out.print(prefix); out.print( 9980 Integer.toHexString(System.identityHashCode(service))); 9981 out.print(' '); 9982 service.printComponentShortName(out); 9983 if (count > 1) { 9984 out.print(" ("); out.print(count); out.print(" filters)"); 9985 } 9986 out.println(); 9987 } 9988 9989// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9990// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9991// final List<ResolveInfo> retList = Lists.newArrayList(); 9992// while (i.hasNext()) { 9993// final ResolveInfo resolveInfo = (ResolveInfo) i; 9994// if (isEnabledLP(resolveInfo.serviceInfo)) { 9995// retList.add(resolveInfo); 9996// } 9997// } 9998// return retList; 9999// } 10000 10001 // Keys are String (activity class name), values are Activity. 10002 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10003 = new ArrayMap<ComponentName, PackageParser.Service>(); 10004 private int mFlags; 10005 }; 10006 10007 private final class ProviderIntentResolver 10008 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10009 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10010 boolean defaultOnly, int userId) { 10011 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10012 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10013 } 10014 10015 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10016 int userId) { 10017 if (!sUserManager.exists(userId)) 10018 return null; 10019 mFlags = flags; 10020 return super.queryIntent(intent, resolvedType, 10021 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10022 } 10023 10024 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10025 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10026 if (!sUserManager.exists(userId)) 10027 return null; 10028 if (packageProviders == null) { 10029 return null; 10030 } 10031 mFlags = flags; 10032 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10033 final int N = packageProviders.size(); 10034 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10035 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10036 10037 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10038 for (int i = 0; i < N; ++i) { 10039 intentFilters = packageProviders.get(i).intents; 10040 if (intentFilters != null && intentFilters.size() > 0) { 10041 PackageParser.ProviderIntentInfo[] array = 10042 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10043 intentFilters.toArray(array); 10044 listCut.add(array); 10045 } 10046 } 10047 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10048 } 10049 10050 public final void addProvider(PackageParser.Provider p) { 10051 if (mProviders.containsKey(p.getComponentName())) { 10052 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10053 return; 10054 } 10055 10056 mProviders.put(p.getComponentName(), p); 10057 if (DEBUG_SHOW_INFO) { 10058 Log.v(TAG, " " 10059 + (p.info.nonLocalizedLabel != null 10060 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10061 Log.v(TAG, " Class=" + p.info.name); 10062 } 10063 final int NI = p.intents.size(); 10064 int j; 10065 for (j = 0; j < NI; j++) { 10066 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10067 if (DEBUG_SHOW_INFO) { 10068 Log.v(TAG, " IntentFilter:"); 10069 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10070 } 10071 if (!intent.debugCheck()) { 10072 Log.w(TAG, "==> For Provider " + p.info.name); 10073 } 10074 addFilter(intent); 10075 } 10076 } 10077 10078 public final void removeProvider(PackageParser.Provider p) { 10079 mProviders.remove(p.getComponentName()); 10080 if (DEBUG_SHOW_INFO) { 10081 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10082 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10083 Log.v(TAG, " Class=" + p.info.name); 10084 } 10085 final int NI = p.intents.size(); 10086 int j; 10087 for (j = 0; j < NI; j++) { 10088 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10089 if (DEBUG_SHOW_INFO) { 10090 Log.v(TAG, " IntentFilter:"); 10091 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10092 } 10093 removeFilter(intent); 10094 } 10095 } 10096 10097 @Override 10098 protected boolean allowFilterResult( 10099 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10100 ProviderInfo filterPi = filter.provider.info; 10101 for (int i = dest.size() - 1; i >= 0; i--) { 10102 ProviderInfo destPi = dest.get(i).providerInfo; 10103 if (destPi.name == filterPi.name 10104 && destPi.packageName == filterPi.packageName) { 10105 return false; 10106 } 10107 } 10108 return true; 10109 } 10110 10111 @Override 10112 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10113 return new PackageParser.ProviderIntentInfo[size]; 10114 } 10115 10116 @Override 10117 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10118 if (!sUserManager.exists(userId)) 10119 return true; 10120 PackageParser.Package p = filter.provider.owner; 10121 if (p != null) { 10122 PackageSetting ps = (PackageSetting) p.mExtras; 10123 if (ps != null) { 10124 // System apps are never considered stopped for purposes of 10125 // filtering, because there may be no way for the user to 10126 // actually re-launch them. 10127 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10128 && ps.getStopped(userId); 10129 } 10130 } 10131 return false; 10132 } 10133 10134 @Override 10135 protected boolean isPackageForFilter(String packageName, 10136 PackageParser.ProviderIntentInfo info) { 10137 return packageName.equals(info.provider.owner.packageName); 10138 } 10139 10140 @Override 10141 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10142 int match, int userId) { 10143 if (!sUserManager.exists(userId)) 10144 return null; 10145 final PackageParser.ProviderIntentInfo info = filter; 10146 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10147 return null; 10148 } 10149 final PackageParser.Provider provider = info.provider; 10150 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10151 if (ps == null) { 10152 return null; 10153 } 10154 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10155 ps.readUserState(userId), userId); 10156 if (pi == null) { 10157 return null; 10158 } 10159 final ResolveInfo res = new ResolveInfo(); 10160 res.providerInfo = pi; 10161 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10162 res.filter = filter; 10163 } 10164 res.priority = info.getPriority(); 10165 res.preferredOrder = provider.owner.mPreferredOrder; 10166 res.match = match; 10167 res.isDefault = info.hasDefault; 10168 res.labelRes = info.labelRes; 10169 res.nonLocalizedLabel = info.nonLocalizedLabel; 10170 res.icon = info.icon; 10171 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10172 return res; 10173 } 10174 10175 @Override 10176 protected void sortResults(List<ResolveInfo> results) { 10177 Collections.sort(results, mResolvePrioritySorter); 10178 } 10179 10180 @Override 10181 protected void dumpFilter(PrintWriter out, String prefix, 10182 PackageParser.ProviderIntentInfo filter) { 10183 out.print(prefix); 10184 out.print( 10185 Integer.toHexString(System.identityHashCode(filter.provider))); 10186 out.print(' '); 10187 filter.provider.printComponentShortName(out); 10188 out.print(" filter "); 10189 out.println(Integer.toHexString(System.identityHashCode(filter))); 10190 } 10191 10192 @Override 10193 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10194 return filter.provider; 10195 } 10196 10197 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10198 PackageParser.Provider provider = (PackageParser.Provider)label; 10199 out.print(prefix); out.print( 10200 Integer.toHexString(System.identityHashCode(provider))); 10201 out.print(' '); 10202 provider.printComponentShortName(out); 10203 if (count > 1) { 10204 out.print(" ("); out.print(count); out.print(" filters)"); 10205 } 10206 out.println(); 10207 } 10208 10209 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10210 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10211 private int mFlags; 10212 } 10213 10214 private static final class EphemeralIntentResolver 10215 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10216 @Override 10217 protected EphemeralResolveIntentInfo[] newArray(int size) { 10218 return new EphemeralResolveIntentInfo[size]; 10219 } 10220 10221 @Override 10222 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10223 return true; 10224 } 10225 10226 @Override 10227 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10228 int userId) { 10229 if (!sUserManager.exists(userId)) { 10230 return null; 10231 } 10232 return info.getEphemeralResolveInfo(); 10233 } 10234 } 10235 10236 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10237 new Comparator<ResolveInfo>() { 10238 public int compare(ResolveInfo r1, ResolveInfo r2) { 10239 int v1 = r1.priority; 10240 int v2 = r2.priority; 10241 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10242 if (v1 != v2) { 10243 return (v1 > v2) ? -1 : 1; 10244 } 10245 v1 = r1.preferredOrder; 10246 v2 = r2.preferredOrder; 10247 if (v1 != v2) { 10248 return (v1 > v2) ? -1 : 1; 10249 } 10250 if (r1.isDefault != r2.isDefault) { 10251 return r1.isDefault ? -1 : 1; 10252 } 10253 v1 = r1.match; 10254 v2 = r2.match; 10255 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10256 if (v1 != v2) { 10257 return (v1 > v2) ? -1 : 1; 10258 } 10259 if (r1.system != r2.system) { 10260 return r1.system ? -1 : 1; 10261 } 10262 if (r1.activityInfo != null) { 10263 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10264 } 10265 if (r1.serviceInfo != null) { 10266 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10267 } 10268 if (r1.providerInfo != null) { 10269 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10270 } 10271 return 0; 10272 } 10273 }; 10274 10275 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10276 new Comparator<ProviderInfo>() { 10277 public int compare(ProviderInfo p1, ProviderInfo p2) { 10278 final int v1 = p1.initOrder; 10279 final int v2 = p2.initOrder; 10280 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10281 } 10282 }; 10283 10284 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10285 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10286 final int[] userIds) { 10287 mHandler.post(new Runnable() { 10288 @Override 10289 public void run() { 10290 try { 10291 final IActivityManager am = ActivityManagerNative.getDefault(); 10292 if (am == null) return; 10293 final int[] resolvedUserIds; 10294 if (userIds == null) { 10295 resolvedUserIds = am.getRunningUserIds(); 10296 } else { 10297 resolvedUserIds = userIds; 10298 } 10299 for (int id : resolvedUserIds) { 10300 final Intent intent = new Intent(action, 10301 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10302 if (extras != null) { 10303 intent.putExtras(extras); 10304 } 10305 if (targetPkg != null) { 10306 intent.setPackage(targetPkg); 10307 } 10308 // Modify the UID when posting to other users 10309 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10310 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10311 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10312 intent.putExtra(Intent.EXTRA_UID, uid); 10313 } 10314 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10315 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10316 if (DEBUG_BROADCASTS) { 10317 RuntimeException here = new RuntimeException("here"); 10318 here.fillInStackTrace(); 10319 Slog.d(TAG, "Sending to user " + id + ": " 10320 + intent.toShortString(false, true, false, false) 10321 + " " + intent.getExtras(), here); 10322 } 10323 am.broadcastIntent(null, intent, null, finishedReceiver, 10324 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10325 null, finishedReceiver != null, false, id); 10326 } 10327 } catch (RemoteException ex) { 10328 } 10329 } 10330 }); 10331 } 10332 10333 /** 10334 * Check if the external storage media is available. This is true if there 10335 * is a mounted external storage medium or if the external storage is 10336 * emulated. 10337 */ 10338 private boolean isExternalMediaAvailable() { 10339 return mMediaMounted || Environment.isExternalStorageEmulated(); 10340 } 10341 10342 @Override 10343 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10344 // writer 10345 synchronized (mPackages) { 10346 if (!isExternalMediaAvailable()) { 10347 // If the external storage is no longer mounted at this point, 10348 // the caller may not have been able to delete all of this 10349 // packages files and can not delete any more. Bail. 10350 return null; 10351 } 10352 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10353 if (lastPackage != null) { 10354 pkgs.remove(lastPackage); 10355 } 10356 if (pkgs.size() > 0) { 10357 return pkgs.get(0); 10358 } 10359 } 10360 return null; 10361 } 10362 10363 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10364 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10365 userId, andCode ? 1 : 0, packageName); 10366 if (mSystemReady) { 10367 msg.sendToTarget(); 10368 } else { 10369 if (mPostSystemReadyMessages == null) { 10370 mPostSystemReadyMessages = new ArrayList<>(); 10371 } 10372 mPostSystemReadyMessages.add(msg); 10373 } 10374 } 10375 10376 void startCleaningPackages() { 10377 // reader 10378 synchronized (mPackages) { 10379 if (!isExternalMediaAvailable()) { 10380 return; 10381 } 10382 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10383 return; 10384 } 10385 } 10386 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10387 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10388 IActivityManager am = ActivityManagerNative.getDefault(); 10389 if (am != null) { 10390 try { 10391 am.startService(null, intent, null, mContext.getOpPackageName(), 10392 UserHandle.USER_SYSTEM); 10393 } catch (RemoteException e) { 10394 } 10395 } 10396 } 10397 10398 @Override 10399 public void installPackage(String originPath, IPackageInstallObserver2 observer, 10400 int installFlags, String installerPackageName, VerificationParams verificationParams, 10401 String packageAbiOverride) { 10402 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 10403 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 10404 } 10405 10406 @Override 10407 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10408 int installFlags, String installerPackageName, VerificationParams verificationParams, 10409 String packageAbiOverride, int userId) { 10410 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10411 10412 final int callingUid = Binder.getCallingUid(); 10413 enforceCrossUserPermission(callingUid, userId, 10414 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 10415 10416 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10417 try { 10418 if (observer != null) { 10419 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10420 } 10421 } catch (RemoteException re) { 10422 } 10423 return; 10424 } 10425 10426 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10427 installFlags |= PackageManager.INSTALL_FROM_ADB; 10428 10429 } else { 10430 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10431 // about installerPackageName. 10432 10433 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10434 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10435 } 10436 10437 UserHandle user; 10438 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10439 user = UserHandle.ALL; 10440 } else { 10441 user = new UserHandle(userId); 10442 } 10443 10444 // Only system components can circumvent runtime permissions when installing. 10445 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10446 && mContext.checkCallingOrSelfPermission(Manifest.permission 10447 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10448 throw new SecurityException("You need the " 10449 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10450 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10451 } 10452 10453 verificationParams.setInstallerUid(callingUid); 10454 10455 final File originFile = new File(originPath); 10456 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10457 10458 final Message msg = mHandler.obtainMessage(INIT_COPY); 10459 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 10460 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 10461 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10462 msg.obj = params; 10463 10464 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10465 System.identityHashCode(msg.obj)); 10466 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10467 System.identityHashCode(msg.obj)); 10468 10469 mHandler.sendMessage(msg); 10470 } 10471 10472 void installStage(String packageName, File stagedDir, String stagedCid, 10473 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10474 String installerPackageName, int installerUid, UserHandle user) { 10475 if (DEBUG_EPHEMERAL) { 10476 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10477 Slog.d(TAG, "Ephemeral install of " + packageName); 10478 } 10479 } 10480 final VerificationParams verifParams = new VerificationParams( 10481 null, sessionParams.originatingUri, sessionParams.referrerUri, 10482 sessionParams.originatingUid); 10483 verifParams.setInstallerUid(installerUid); 10484 10485 final OriginInfo origin; 10486 if (stagedDir != null) { 10487 origin = OriginInfo.fromStagedFile(stagedDir); 10488 } else { 10489 origin = OriginInfo.fromStagedContainer(stagedCid); 10490 } 10491 10492 final Message msg = mHandler.obtainMessage(INIT_COPY); 10493 final InstallParams params = new InstallParams(origin, null, observer, 10494 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10495 verifParams, user, sessionParams.abiOverride, 10496 sessionParams.grantedRuntimePermissions); 10497 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10498 msg.obj = params; 10499 10500 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10501 System.identityHashCode(msg.obj)); 10502 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10503 System.identityHashCode(msg.obj)); 10504 10505 mHandler.sendMessage(msg); 10506 } 10507 10508 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 10509 int userId) { 10510 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10511 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 10512 } 10513 10514 private void sendPackageAddedForUser(String packageName, boolean isSystem, 10515 int appId, int userId) { 10516 Bundle extras = new Bundle(1); 10517 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 10518 10519 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10520 packageName, extras, 0, null, null, new int[] {userId}); 10521 try { 10522 IActivityManager am = ActivityManagerNative.getDefault(); 10523 if (isSystem && am.isUserRunning(userId, 0)) { 10524 // The just-installed/enabled app is bundled on the system, so presumed 10525 // to be able to run automatically without needing an explicit launch. 10526 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10527 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10528 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10529 .setPackage(packageName); 10530 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10531 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10532 } 10533 } catch (RemoteException e) { 10534 // shouldn't happen 10535 Slog.w(TAG, "Unable to bootstrap installed package", e); 10536 } 10537 } 10538 10539 @Override 10540 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10541 int userId) { 10542 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10543 PackageSetting pkgSetting; 10544 final int uid = Binder.getCallingUid(); 10545 enforceCrossUserPermission(uid, userId, 10546 true /* requireFullPermission */, true /* checkShell */, 10547 "setApplicationHiddenSetting for user " + userId); 10548 10549 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10550 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10551 return false; 10552 } 10553 10554 long callingId = Binder.clearCallingIdentity(); 10555 try { 10556 boolean sendAdded = false; 10557 boolean sendRemoved = false; 10558 // writer 10559 synchronized (mPackages) { 10560 pkgSetting = mSettings.mPackages.get(packageName); 10561 if (pkgSetting == null) { 10562 return false; 10563 } 10564 if (pkgSetting.getHidden(userId) != hidden) { 10565 pkgSetting.setHidden(hidden, userId); 10566 mSettings.writePackageRestrictionsLPr(userId); 10567 if (hidden) { 10568 sendRemoved = true; 10569 } else { 10570 sendAdded = true; 10571 } 10572 } 10573 } 10574 if (sendAdded) { 10575 sendPackageAddedForUser(packageName, pkgSetting, userId); 10576 return true; 10577 } 10578 if (sendRemoved) { 10579 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10580 "hiding pkg"); 10581 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10582 return true; 10583 } 10584 } finally { 10585 Binder.restoreCallingIdentity(callingId); 10586 } 10587 return false; 10588 } 10589 10590 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10591 int userId) { 10592 final PackageRemovedInfo info = new PackageRemovedInfo(); 10593 info.removedPackage = packageName; 10594 info.removedUsers = new int[] {userId}; 10595 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10596 info.sendPackageRemovedBroadcasts(); 10597 } 10598 10599 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10600 if (pkgList.length > 0) { 10601 Bundle extras = new Bundle(1); 10602 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10603 10604 sendPackageBroadcast( 10605 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10606 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10607 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10608 new int[] {userId}); 10609 } 10610 } 10611 10612 /** 10613 * Returns true if application is not found or there was an error. Otherwise it returns 10614 * the hidden state of the package for the given user. 10615 */ 10616 @Override 10617 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10618 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10619 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10620 true /* requireFullPermission */, false /* checkShell */, 10621 "getApplicationHidden for user " + userId); 10622 PackageSetting pkgSetting; 10623 long callingId = Binder.clearCallingIdentity(); 10624 try { 10625 // writer 10626 synchronized (mPackages) { 10627 pkgSetting = mSettings.mPackages.get(packageName); 10628 if (pkgSetting == null) { 10629 return true; 10630 } 10631 return pkgSetting.getHidden(userId); 10632 } 10633 } finally { 10634 Binder.restoreCallingIdentity(callingId); 10635 } 10636 } 10637 10638 /** 10639 * @hide 10640 */ 10641 @Override 10642 public int installExistingPackageAsUser(String packageName, int userId) { 10643 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10644 null); 10645 PackageSetting pkgSetting; 10646 final int uid = Binder.getCallingUid(); 10647 enforceCrossUserPermission(uid, userId, 10648 true /* requireFullPermission */, true /* checkShell */, 10649 "installExistingPackage for user " + userId); 10650 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10651 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10652 } 10653 10654 long callingId = Binder.clearCallingIdentity(); 10655 try { 10656 boolean installed = false; 10657 10658 // writer 10659 synchronized (mPackages) { 10660 pkgSetting = mSettings.mPackages.get(packageName); 10661 if (pkgSetting == null) { 10662 return PackageManager.INSTALL_FAILED_INVALID_URI; 10663 } 10664 if (!pkgSetting.getInstalled(userId)) { 10665 pkgSetting.setInstalled(true, userId); 10666 pkgSetting.setHidden(false, userId); 10667 mSettings.writePackageRestrictionsLPr(userId); 10668 installed = true; 10669 } 10670 } 10671 10672 if (installed) { 10673 if (pkgSetting.pkg != null) { 10674 prepareAppDataAfterInstall(pkgSetting.pkg); 10675 } 10676 sendPackageAddedForUser(packageName, pkgSetting, userId); 10677 } 10678 } finally { 10679 Binder.restoreCallingIdentity(callingId); 10680 } 10681 10682 return PackageManager.INSTALL_SUCCEEDED; 10683 } 10684 10685 boolean isUserRestricted(int userId, String restrictionKey) { 10686 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10687 if (restrictions.getBoolean(restrictionKey, false)) { 10688 Log.w(TAG, "User is restricted: " + restrictionKey); 10689 return true; 10690 } 10691 return false; 10692 } 10693 10694 @Override 10695 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 10696 int userId) { 10697 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10698 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10699 true /* requireFullPermission */, true /* checkShell */, 10700 "setPackagesSuspended for user " + userId); 10701 10702 if (ArrayUtils.isEmpty(packageNames)) { 10703 return packageNames; 10704 } 10705 10706 // List of package names for whom the suspended state has changed. 10707 List<String> changedPackages = new ArrayList<>(packageNames.length); 10708 // List of package names for whom the suspended state is not set as requested in this 10709 // method. 10710 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 10711 for (int i = 0; i < packageNames.length; i++) { 10712 String packageName = packageNames[i]; 10713 long callingId = Binder.clearCallingIdentity(); 10714 try { 10715 boolean changed = false; 10716 final int appId; 10717 synchronized (mPackages) { 10718 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10719 if (pkgSetting == null) { 10720 Slog.w(TAG, "Could not find package setting for package \"" + packageName 10721 + "\". Skipping suspending/un-suspending."); 10722 unactionedPackages.add(packageName); 10723 continue; 10724 } 10725 appId = pkgSetting.appId; 10726 if (pkgSetting.getSuspended(userId) != suspended) { 10727 if (!canSuspendPackageForUserLocked(packageName, userId)) { 10728 unactionedPackages.add(packageName); 10729 continue; 10730 } 10731 pkgSetting.setSuspended(suspended, userId); 10732 mSettings.writePackageRestrictionsLPr(userId); 10733 changed = true; 10734 changedPackages.add(packageName); 10735 } 10736 } 10737 10738 if (changed && suspended) { 10739 killApplication(packageName, UserHandle.getUid(userId, appId), 10740 "suspending package"); 10741 } 10742 } finally { 10743 Binder.restoreCallingIdentity(callingId); 10744 } 10745 } 10746 10747 if (!changedPackages.isEmpty()) { 10748 sendPackagesSuspendedForUser(changedPackages.toArray( 10749 new String[changedPackages.size()]), userId, suspended); 10750 } 10751 10752 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 10753 } 10754 10755 @Override 10756 public boolean isPackageSuspendedForUser(String packageName, int userId) { 10757 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10758 true /* requireFullPermission */, false /* checkShell */, 10759 "isPackageSuspendedForUser for user " + userId); 10760 synchronized (mPackages) { 10761 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10762 return pkgSetting != null && pkgSetting.getSuspended(userId); 10763 } 10764 } 10765 10766 // TODO: investigate and add more restrictions for suspending crucial packages. 10767 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 10768 if (isPackageDeviceAdmin(packageName, userId)) { 10769 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10770 + "\": has active device admin"); 10771 return false; 10772 } 10773 10774 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 10775 if (packageName.equals(activeLauncherPackageName)) { 10776 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10777 + "\" because it is set as the active launcher"); 10778 return false; 10779 } 10780 10781 final PackageParser.Package pkg = mPackages.get(packageName); 10782 if (pkg != null && isPrivilegedApp(pkg)) { 10783 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10784 + "\" because it is a privileged app"); 10785 return false; 10786 } 10787 10788 return true; 10789 } 10790 10791 private String getActiveLauncherPackageName(int userId) { 10792 Intent intent = new Intent(Intent.ACTION_MAIN); 10793 intent.addCategory(Intent.CATEGORY_HOME); 10794 ResolveInfo resolveInfo = resolveIntent( 10795 intent, 10796 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 10797 PackageManager.MATCH_DEFAULT_ONLY, 10798 userId); 10799 10800 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 10801 } 10802 10803 @Override 10804 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10805 mContext.enforceCallingOrSelfPermission( 10806 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10807 "Only package verification agents can verify applications"); 10808 10809 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10810 final PackageVerificationResponse response = new PackageVerificationResponse( 10811 verificationCode, Binder.getCallingUid()); 10812 msg.arg1 = id; 10813 msg.obj = response; 10814 mHandler.sendMessage(msg); 10815 } 10816 10817 @Override 10818 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10819 long millisecondsToDelay) { 10820 mContext.enforceCallingOrSelfPermission( 10821 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10822 "Only package verification agents can extend verification timeouts"); 10823 10824 final PackageVerificationState state = mPendingVerification.get(id); 10825 final PackageVerificationResponse response = new PackageVerificationResponse( 10826 verificationCodeAtTimeout, Binder.getCallingUid()); 10827 10828 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10829 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10830 } 10831 if (millisecondsToDelay < 0) { 10832 millisecondsToDelay = 0; 10833 } 10834 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10835 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10836 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10837 } 10838 10839 if ((state != null) && !state.timeoutExtended()) { 10840 state.extendTimeout(); 10841 10842 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10843 msg.arg1 = id; 10844 msg.obj = response; 10845 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10846 } 10847 } 10848 10849 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10850 int verificationCode, UserHandle user) { 10851 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10852 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10853 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10854 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10855 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10856 10857 mContext.sendBroadcastAsUser(intent, user, 10858 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10859 } 10860 10861 private ComponentName matchComponentForVerifier(String packageName, 10862 List<ResolveInfo> receivers) { 10863 ActivityInfo targetReceiver = null; 10864 10865 final int NR = receivers.size(); 10866 for (int i = 0; i < NR; i++) { 10867 final ResolveInfo info = receivers.get(i); 10868 if (info.activityInfo == null) { 10869 continue; 10870 } 10871 10872 if (packageName.equals(info.activityInfo.packageName)) { 10873 targetReceiver = info.activityInfo; 10874 break; 10875 } 10876 } 10877 10878 if (targetReceiver == null) { 10879 return null; 10880 } 10881 10882 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10883 } 10884 10885 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10886 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10887 if (pkgInfo.verifiers.length == 0) { 10888 return null; 10889 } 10890 10891 final int N = pkgInfo.verifiers.length; 10892 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10893 for (int i = 0; i < N; i++) { 10894 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10895 10896 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10897 receivers); 10898 if (comp == null) { 10899 continue; 10900 } 10901 10902 final int verifierUid = getUidForVerifier(verifierInfo); 10903 if (verifierUid == -1) { 10904 continue; 10905 } 10906 10907 if (DEBUG_VERIFY) { 10908 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10909 + " with the correct signature"); 10910 } 10911 sufficientVerifiers.add(comp); 10912 verificationState.addSufficientVerifier(verifierUid); 10913 } 10914 10915 return sufficientVerifiers; 10916 } 10917 10918 private int getUidForVerifier(VerifierInfo verifierInfo) { 10919 synchronized (mPackages) { 10920 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10921 if (pkg == null) { 10922 return -1; 10923 } else if (pkg.mSignatures.length != 1) { 10924 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10925 + " has more than one signature; ignoring"); 10926 return -1; 10927 } 10928 10929 /* 10930 * If the public key of the package's signature does not match 10931 * our expected public key, then this is a different package and 10932 * we should skip. 10933 */ 10934 10935 final byte[] expectedPublicKey; 10936 try { 10937 final Signature verifierSig = pkg.mSignatures[0]; 10938 final PublicKey publicKey = verifierSig.getPublicKey(); 10939 expectedPublicKey = publicKey.getEncoded(); 10940 } catch (CertificateException e) { 10941 return -1; 10942 } 10943 10944 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10945 10946 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10947 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10948 + " does not have the expected public key; ignoring"); 10949 return -1; 10950 } 10951 10952 return pkg.applicationInfo.uid; 10953 } 10954 } 10955 10956 @Override 10957 public void finishPackageInstall(int token) { 10958 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10959 10960 if (DEBUG_INSTALL) { 10961 Slog.v(TAG, "BM finishing package install for " + token); 10962 } 10963 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10964 10965 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10966 mHandler.sendMessage(msg); 10967 } 10968 10969 /** 10970 * Get the verification agent timeout. 10971 * 10972 * @return verification timeout in milliseconds 10973 */ 10974 private long getVerificationTimeout() { 10975 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10976 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10977 DEFAULT_VERIFICATION_TIMEOUT); 10978 } 10979 10980 /** 10981 * Get the default verification agent response code. 10982 * 10983 * @return default verification response code 10984 */ 10985 private int getDefaultVerificationResponse() { 10986 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10987 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10988 DEFAULT_VERIFICATION_RESPONSE); 10989 } 10990 10991 /** 10992 * Check whether or not package verification has been enabled. 10993 * 10994 * @return true if verification should be performed 10995 */ 10996 private boolean isVerificationEnabled(int userId, int installFlags) { 10997 if (!DEFAULT_VERIFY_ENABLE) { 10998 return false; 10999 } 11000 // Ephemeral apps don't get the full verification treatment 11001 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11002 if (DEBUG_EPHEMERAL) { 11003 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11004 } 11005 return false; 11006 } 11007 11008 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11009 11010 // Check if installing from ADB 11011 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11012 // Do not run verification in a test harness environment 11013 if (ActivityManager.isRunningInTestHarness()) { 11014 return false; 11015 } 11016 if (ensureVerifyAppsEnabled) { 11017 return true; 11018 } 11019 // Check if the developer does not want package verification for ADB installs 11020 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11021 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11022 return false; 11023 } 11024 } 11025 11026 if (ensureVerifyAppsEnabled) { 11027 return true; 11028 } 11029 11030 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11031 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11032 } 11033 11034 @Override 11035 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11036 throws RemoteException { 11037 mContext.enforceCallingOrSelfPermission( 11038 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11039 "Only intentfilter verification agents can verify applications"); 11040 11041 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11042 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11043 Binder.getCallingUid(), verificationCode, failedDomains); 11044 msg.arg1 = id; 11045 msg.obj = response; 11046 mHandler.sendMessage(msg); 11047 } 11048 11049 @Override 11050 public int getIntentVerificationStatus(String packageName, int userId) { 11051 synchronized (mPackages) { 11052 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11053 } 11054 } 11055 11056 @Override 11057 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11058 mContext.enforceCallingOrSelfPermission( 11059 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11060 11061 boolean result = false; 11062 synchronized (mPackages) { 11063 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11064 } 11065 if (result) { 11066 scheduleWritePackageRestrictionsLocked(userId); 11067 } 11068 return result; 11069 } 11070 11071 @Override 11072 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 11073 synchronized (mPackages) { 11074 return mSettings.getIntentFilterVerificationsLPr(packageName); 11075 } 11076 } 11077 11078 @Override 11079 public List<IntentFilter> getAllIntentFilters(String packageName) { 11080 if (TextUtils.isEmpty(packageName)) { 11081 return Collections.<IntentFilter>emptyList(); 11082 } 11083 synchronized (mPackages) { 11084 PackageParser.Package pkg = mPackages.get(packageName); 11085 if (pkg == null || pkg.activities == null) { 11086 return Collections.<IntentFilter>emptyList(); 11087 } 11088 final int count = pkg.activities.size(); 11089 ArrayList<IntentFilter> result = new ArrayList<>(); 11090 for (int n=0; n<count; n++) { 11091 PackageParser.Activity activity = pkg.activities.get(n); 11092 if (activity.intents != null && activity.intents.size() > 0) { 11093 result.addAll(activity.intents); 11094 } 11095 } 11096 return result; 11097 } 11098 } 11099 11100 @Override 11101 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11102 mContext.enforceCallingOrSelfPermission( 11103 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11104 11105 synchronized (mPackages) { 11106 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11107 if (packageName != null) { 11108 result |= updateIntentVerificationStatus(packageName, 11109 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11110 userId); 11111 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11112 packageName, userId); 11113 } 11114 return result; 11115 } 11116 } 11117 11118 @Override 11119 public String getDefaultBrowserPackageName(int userId) { 11120 synchronized (mPackages) { 11121 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11122 } 11123 } 11124 11125 /** 11126 * Get the "allow unknown sources" setting. 11127 * 11128 * @return the current "allow unknown sources" setting 11129 */ 11130 private int getUnknownSourcesSettings() { 11131 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11132 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 11133 -1); 11134 } 11135 11136 @Override 11137 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11138 final int uid = Binder.getCallingUid(); 11139 // writer 11140 synchronized (mPackages) { 11141 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11142 if (targetPackageSetting == null) { 11143 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11144 } 11145 11146 PackageSetting installerPackageSetting; 11147 if (installerPackageName != null) { 11148 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11149 if (installerPackageSetting == null) { 11150 throw new IllegalArgumentException("Unknown installer package: " 11151 + installerPackageName); 11152 } 11153 } else { 11154 installerPackageSetting = null; 11155 } 11156 11157 Signature[] callerSignature; 11158 Object obj = mSettings.getUserIdLPr(uid); 11159 if (obj != null) { 11160 if (obj instanceof SharedUserSetting) { 11161 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11162 } else if (obj instanceof PackageSetting) { 11163 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11164 } else { 11165 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11166 } 11167 } else { 11168 throw new SecurityException("Unknown calling UID: " + uid); 11169 } 11170 11171 // Verify: can't set installerPackageName to a package that is 11172 // not signed with the same cert as the caller. 11173 if (installerPackageSetting != null) { 11174 if (compareSignatures(callerSignature, 11175 installerPackageSetting.signatures.mSignatures) 11176 != PackageManager.SIGNATURE_MATCH) { 11177 throw new SecurityException( 11178 "Caller does not have same cert as new installer package " 11179 + installerPackageName); 11180 } 11181 } 11182 11183 // Verify: if target already has an installer package, it must 11184 // be signed with the same cert as the caller. 11185 if (targetPackageSetting.installerPackageName != null) { 11186 PackageSetting setting = mSettings.mPackages.get( 11187 targetPackageSetting.installerPackageName); 11188 // If the currently set package isn't valid, then it's always 11189 // okay to change it. 11190 if (setting != null) { 11191 if (compareSignatures(callerSignature, 11192 setting.signatures.mSignatures) 11193 != PackageManager.SIGNATURE_MATCH) { 11194 throw new SecurityException( 11195 "Caller does not have same cert as old installer package " 11196 + targetPackageSetting.installerPackageName); 11197 } 11198 } 11199 } 11200 11201 // Okay! 11202 targetPackageSetting.installerPackageName = installerPackageName; 11203 scheduleWriteSettingsLocked(); 11204 } 11205 } 11206 11207 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11208 // Queue up an async operation since the package installation may take a little while. 11209 mHandler.post(new Runnable() { 11210 public void run() { 11211 mHandler.removeCallbacks(this); 11212 // Result object to be returned 11213 PackageInstalledInfo res = new PackageInstalledInfo(); 11214 res.setReturnCode(currentStatus); 11215 res.uid = -1; 11216 res.pkg = null; 11217 res.removedInfo = null; 11218 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11219 args.doPreInstall(res.returnCode); 11220 synchronized (mInstallLock) { 11221 installPackageTracedLI(args, res); 11222 } 11223 args.doPostInstall(res.returnCode, res.uid); 11224 } 11225 11226 // A restore should be performed at this point if (a) the install 11227 // succeeded, (b) the operation is not an update, and (c) the new 11228 // package has not opted out of backup participation. 11229 final boolean update = res.removedInfo != null 11230 && res.removedInfo.removedPackage != null; 11231 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11232 boolean doRestore = !update 11233 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11234 11235 // Set up the post-install work request bookkeeping. This will be used 11236 // and cleaned up by the post-install event handling regardless of whether 11237 // there's a restore pass performed. Token values are >= 1. 11238 int token; 11239 if (mNextInstallToken < 0) mNextInstallToken = 1; 11240 token = mNextInstallToken++; 11241 11242 PostInstallData data = new PostInstallData(args, res); 11243 mRunningInstalls.put(token, data); 11244 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11245 11246 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11247 // Pass responsibility to the Backup Manager. It will perform a 11248 // restore if appropriate, then pass responsibility back to the 11249 // Package Manager to run the post-install observer callbacks 11250 // and broadcasts. 11251 IBackupManager bm = IBackupManager.Stub.asInterface( 11252 ServiceManager.getService(Context.BACKUP_SERVICE)); 11253 if (bm != null) { 11254 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11255 + " to BM for possible restore"); 11256 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11257 try { 11258 // TODO: http://b/22388012 11259 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11260 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11261 } else { 11262 doRestore = false; 11263 } 11264 } catch (RemoteException e) { 11265 // can't happen; the backup manager is local 11266 } catch (Exception e) { 11267 Slog.e(TAG, "Exception trying to enqueue restore", e); 11268 doRestore = false; 11269 } 11270 } else { 11271 Slog.e(TAG, "Backup Manager not found!"); 11272 doRestore = false; 11273 } 11274 } 11275 11276 if (!doRestore) { 11277 // No restore possible, or the Backup Manager was mysteriously not 11278 // available -- just fire the post-install work request directly. 11279 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11280 11281 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11282 11283 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11284 mHandler.sendMessage(msg); 11285 } 11286 } 11287 }); 11288 } 11289 11290 private abstract class HandlerParams { 11291 private static final int MAX_RETRIES = 4; 11292 11293 /** 11294 * Number of times startCopy() has been attempted and had a non-fatal 11295 * error. 11296 */ 11297 private int mRetries = 0; 11298 11299 /** User handle for the user requesting the information or installation. */ 11300 private final UserHandle mUser; 11301 String traceMethod; 11302 int traceCookie; 11303 11304 HandlerParams(UserHandle user) { 11305 mUser = user; 11306 } 11307 11308 UserHandle getUser() { 11309 return mUser; 11310 } 11311 11312 HandlerParams setTraceMethod(String traceMethod) { 11313 this.traceMethod = traceMethod; 11314 return this; 11315 } 11316 11317 HandlerParams setTraceCookie(int traceCookie) { 11318 this.traceCookie = traceCookie; 11319 return this; 11320 } 11321 11322 final boolean startCopy() { 11323 boolean res; 11324 try { 11325 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11326 11327 if (++mRetries > MAX_RETRIES) { 11328 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11329 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11330 handleServiceError(); 11331 return false; 11332 } else { 11333 handleStartCopy(); 11334 res = true; 11335 } 11336 } catch (RemoteException e) { 11337 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11338 mHandler.sendEmptyMessage(MCS_RECONNECT); 11339 res = false; 11340 } 11341 handleReturnCode(); 11342 return res; 11343 } 11344 11345 final void serviceError() { 11346 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11347 handleServiceError(); 11348 handleReturnCode(); 11349 } 11350 11351 abstract void handleStartCopy() throws RemoteException; 11352 abstract void handleServiceError(); 11353 abstract void handleReturnCode(); 11354 } 11355 11356 class MeasureParams extends HandlerParams { 11357 private final PackageStats mStats; 11358 private boolean mSuccess; 11359 11360 private final IPackageStatsObserver mObserver; 11361 11362 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11363 super(new UserHandle(stats.userHandle)); 11364 mObserver = observer; 11365 mStats = stats; 11366 } 11367 11368 @Override 11369 public String toString() { 11370 return "MeasureParams{" 11371 + Integer.toHexString(System.identityHashCode(this)) 11372 + " " + mStats.packageName + "}"; 11373 } 11374 11375 @Override 11376 void handleStartCopy() throws RemoteException { 11377 synchronized (mInstallLock) { 11378 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11379 } 11380 11381 if (mSuccess) { 11382 final boolean mounted; 11383 if (Environment.isExternalStorageEmulated()) { 11384 mounted = true; 11385 } else { 11386 final String status = Environment.getExternalStorageState(); 11387 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11388 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11389 } 11390 11391 if (mounted) { 11392 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11393 11394 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11395 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11396 11397 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11398 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11399 11400 // Always subtract cache size, since it's a subdirectory 11401 mStats.externalDataSize -= mStats.externalCacheSize; 11402 11403 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11404 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11405 11406 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11407 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11408 } 11409 } 11410 } 11411 11412 @Override 11413 void handleReturnCode() { 11414 if (mObserver != null) { 11415 try { 11416 mObserver.onGetStatsCompleted(mStats, mSuccess); 11417 } catch (RemoteException e) { 11418 Slog.i(TAG, "Observer no longer exists."); 11419 } 11420 } 11421 } 11422 11423 @Override 11424 void handleServiceError() { 11425 Slog.e(TAG, "Could not measure application " + mStats.packageName 11426 + " external storage"); 11427 } 11428 } 11429 11430 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11431 throws RemoteException { 11432 long result = 0; 11433 for (File path : paths) { 11434 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11435 } 11436 return result; 11437 } 11438 11439 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11440 for (File path : paths) { 11441 try { 11442 mcs.clearDirectory(path.getAbsolutePath()); 11443 } catch (RemoteException e) { 11444 } 11445 } 11446 } 11447 11448 static class OriginInfo { 11449 /** 11450 * Location where install is coming from, before it has been 11451 * copied/renamed into place. This could be a single monolithic APK 11452 * file, or a cluster directory. This location may be untrusted. 11453 */ 11454 final File file; 11455 final String cid; 11456 11457 /** 11458 * Flag indicating that {@link #file} or {@link #cid} has already been 11459 * staged, meaning downstream users don't need to defensively copy the 11460 * contents. 11461 */ 11462 final boolean staged; 11463 11464 /** 11465 * Flag indicating that {@link #file} or {@link #cid} is an already 11466 * installed app that is being moved. 11467 */ 11468 final boolean existing; 11469 11470 final String resolvedPath; 11471 final File resolvedFile; 11472 11473 static OriginInfo fromNothing() { 11474 return new OriginInfo(null, null, false, false); 11475 } 11476 11477 static OriginInfo fromUntrustedFile(File file) { 11478 return new OriginInfo(file, null, false, false); 11479 } 11480 11481 static OriginInfo fromExistingFile(File file) { 11482 return new OriginInfo(file, null, false, true); 11483 } 11484 11485 static OriginInfo fromStagedFile(File file) { 11486 return new OriginInfo(file, null, true, false); 11487 } 11488 11489 static OriginInfo fromStagedContainer(String cid) { 11490 return new OriginInfo(null, cid, true, false); 11491 } 11492 11493 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 11494 this.file = file; 11495 this.cid = cid; 11496 this.staged = staged; 11497 this.existing = existing; 11498 11499 if (cid != null) { 11500 resolvedPath = PackageHelper.getSdDir(cid); 11501 resolvedFile = new File(resolvedPath); 11502 } else if (file != null) { 11503 resolvedPath = file.getAbsolutePath(); 11504 resolvedFile = file; 11505 } else { 11506 resolvedPath = null; 11507 resolvedFile = null; 11508 } 11509 } 11510 } 11511 11512 static class MoveInfo { 11513 final int moveId; 11514 final String fromUuid; 11515 final String toUuid; 11516 final String packageName; 11517 final String dataAppName; 11518 final int appId; 11519 final String seinfo; 11520 final int targetSdkVersion; 11521 11522 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 11523 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 11524 this.moveId = moveId; 11525 this.fromUuid = fromUuid; 11526 this.toUuid = toUuid; 11527 this.packageName = packageName; 11528 this.dataAppName = dataAppName; 11529 this.appId = appId; 11530 this.seinfo = seinfo; 11531 this.targetSdkVersion = targetSdkVersion; 11532 } 11533 } 11534 11535 class InstallParams extends HandlerParams { 11536 final OriginInfo origin; 11537 final MoveInfo move; 11538 final IPackageInstallObserver2 observer; 11539 int installFlags; 11540 final String installerPackageName; 11541 final String volumeUuid; 11542 final VerificationParams verificationParams; 11543 private InstallArgs mArgs; 11544 private int mRet; 11545 final String packageAbiOverride; 11546 final String[] grantedRuntimePermissions; 11547 11548 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11549 int installFlags, String installerPackageName, String volumeUuid, 11550 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 11551 String[] grantedPermissions) { 11552 super(user); 11553 this.origin = origin; 11554 this.move = move; 11555 this.observer = observer; 11556 this.installFlags = installFlags; 11557 this.installerPackageName = installerPackageName; 11558 this.volumeUuid = volumeUuid; 11559 this.verificationParams = verificationParams; 11560 this.packageAbiOverride = packageAbiOverride; 11561 this.grantedRuntimePermissions = grantedPermissions; 11562 } 11563 11564 @Override 11565 public String toString() { 11566 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11567 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11568 } 11569 11570 private int installLocationPolicy(PackageInfoLite pkgLite) { 11571 String packageName = pkgLite.packageName; 11572 int installLocation = pkgLite.installLocation; 11573 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11574 // reader 11575 synchronized (mPackages) { 11576 // Currently installed package which the new package is attempting to replace or 11577 // null if no such package is installed. 11578 PackageParser.Package installedPkg = mPackages.get(packageName); 11579 // Package which currently owns the data which the new package will own if installed. 11580 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 11581 // will be null whereas dataOwnerPkg will contain information about the package 11582 // which was uninstalled while keeping its data. 11583 PackageParser.Package dataOwnerPkg = installedPkg; 11584 if (dataOwnerPkg == null) { 11585 PackageSetting ps = mSettings.mPackages.get(packageName); 11586 if (ps != null) { 11587 dataOwnerPkg = ps.pkg; 11588 } 11589 } 11590 11591 if (dataOwnerPkg != null) { 11592 // If installed, the package will get access to data left on the device by its 11593 // predecessor. As a security measure, this is permited only if this is not a 11594 // version downgrade or if the predecessor package is marked as debuggable and 11595 // a downgrade is explicitly requested. 11596 if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) 11597 || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) { 11598 try { 11599 checkDowngrade(dataOwnerPkg, pkgLite); 11600 } catch (PackageManagerException e) { 11601 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11602 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11603 } 11604 } 11605 } 11606 11607 if (installedPkg != null) { 11608 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11609 // Check for updated system application. 11610 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11611 if (onSd) { 11612 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11613 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11614 } 11615 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11616 } else { 11617 if (onSd) { 11618 // Install flag overrides everything. 11619 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11620 } 11621 // If current upgrade specifies particular preference 11622 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11623 // Application explicitly specified internal. 11624 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11625 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11626 // App explictly prefers external. Let policy decide 11627 } else { 11628 // Prefer previous location 11629 if (isExternal(installedPkg)) { 11630 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11631 } 11632 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11633 } 11634 } 11635 } else { 11636 // Invalid install. Return error code 11637 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11638 } 11639 } 11640 } 11641 // All the special cases have been taken care of. 11642 // Return result based on recommended install location. 11643 if (onSd) { 11644 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11645 } 11646 return pkgLite.recommendedInstallLocation; 11647 } 11648 11649 /* 11650 * Invoke remote method to get package information and install 11651 * location values. Override install location based on default 11652 * policy if needed and then create install arguments based 11653 * on the install location. 11654 */ 11655 public void handleStartCopy() throws RemoteException { 11656 int ret = PackageManager.INSTALL_SUCCEEDED; 11657 11658 // If we're already staged, we've firmly committed to an install location 11659 if (origin.staged) { 11660 if (origin.file != null) { 11661 installFlags |= PackageManager.INSTALL_INTERNAL; 11662 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11663 } else if (origin.cid != null) { 11664 installFlags |= PackageManager.INSTALL_EXTERNAL; 11665 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11666 } else { 11667 throw new IllegalStateException("Invalid stage location"); 11668 } 11669 } 11670 11671 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11672 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11673 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11674 PackageInfoLite pkgLite = null; 11675 11676 if (onInt && onSd) { 11677 // Check if both bits are set. 11678 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11679 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11680 } else if (onSd && ephemeral) { 11681 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11682 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11683 } else { 11684 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11685 packageAbiOverride); 11686 11687 if (DEBUG_EPHEMERAL && ephemeral) { 11688 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11689 } 11690 11691 /* 11692 * If we have too little free space, try to free cache 11693 * before giving up. 11694 */ 11695 if (!origin.staged && pkgLite.recommendedInstallLocation 11696 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11697 // TODO: focus freeing disk space on the target device 11698 final StorageManager storage = StorageManager.from(mContext); 11699 final long lowThreshold = storage.getStorageLowBytes( 11700 Environment.getDataDirectory()); 11701 11702 final long sizeBytes = mContainerService.calculateInstalledSize( 11703 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11704 11705 try { 11706 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11707 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11708 installFlags, packageAbiOverride); 11709 } catch (InstallerException e) { 11710 Slog.w(TAG, "Failed to free cache", e); 11711 } 11712 11713 /* 11714 * The cache free must have deleted the file we 11715 * downloaded to install. 11716 * 11717 * TODO: fix the "freeCache" call to not delete 11718 * the file we care about. 11719 */ 11720 if (pkgLite.recommendedInstallLocation 11721 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11722 pkgLite.recommendedInstallLocation 11723 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11724 } 11725 } 11726 } 11727 11728 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11729 int loc = pkgLite.recommendedInstallLocation; 11730 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11731 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11732 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11733 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11734 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11735 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11736 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11737 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11738 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11739 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11740 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11741 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11742 } else { 11743 // Override with defaults if needed. 11744 loc = installLocationPolicy(pkgLite); 11745 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11746 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11747 } else if (!onSd && !onInt) { 11748 // Override install location with flags 11749 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11750 // Set the flag to install on external media. 11751 installFlags |= PackageManager.INSTALL_EXTERNAL; 11752 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11753 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11754 if (DEBUG_EPHEMERAL) { 11755 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11756 } 11757 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11758 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11759 |PackageManager.INSTALL_INTERNAL); 11760 } else { 11761 // Make sure the flag for installing on external 11762 // media is unset 11763 installFlags |= PackageManager.INSTALL_INTERNAL; 11764 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11765 } 11766 } 11767 } 11768 } 11769 11770 final InstallArgs args = createInstallArgs(this); 11771 mArgs = args; 11772 11773 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11774 // TODO: http://b/22976637 11775 // Apps installed for "all" users use the device owner to verify the app 11776 UserHandle verifierUser = getUser(); 11777 if (verifierUser == UserHandle.ALL) { 11778 verifierUser = UserHandle.SYSTEM; 11779 } 11780 11781 /* 11782 * Determine if we have any installed package verifiers. If we 11783 * do, then we'll defer to them to verify the packages. 11784 */ 11785 final int requiredUid = mRequiredVerifierPackage == null ? -1 11786 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11787 verifierUser.getIdentifier()); 11788 if (!origin.existing && requiredUid != -1 11789 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11790 final Intent verification = new Intent( 11791 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11792 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11793 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11794 PACKAGE_MIME_TYPE); 11795 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11796 11797 // Query all live verifiers based on current user state 11798 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11799 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11800 11801 if (DEBUG_VERIFY) { 11802 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11803 + verification.toString() + " with " + pkgLite.verifiers.length 11804 + " optional verifiers"); 11805 } 11806 11807 final int verificationId = mPendingVerificationToken++; 11808 11809 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11810 11811 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11812 installerPackageName); 11813 11814 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11815 installFlags); 11816 11817 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11818 pkgLite.packageName); 11819 11820 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11821 pkgLite.versionCode); 11822 11823 if (verificationParams != null) { 11824 if (verificationParams.getVerificationURI() != null) { 11825 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11826 verificationParams.getVerificationURI()); 11827 } 11828 if (verificationParams.getOriginatingURI() != null) { 11829 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11830 verificationParams.getOriginatingURI()); 11831 } 11832 if (verificationParams.getReferrer() != null) { 11833 verification.putExtra(Intent.EXTRA_REFERRER, 11834 verificationParams.getReferrer()); 11835 } 11836 if (verificationParams.getOriginatingUid() >= 0) { 11837 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11838 verificationParams.getOriginatingUid()); 11839 } 11840 if (verificationParams.getInstallerUid() >= 0) { 11841 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11842 verificationParams.getInstallerUid()); 11843 } 11844 } 11845 11846 final PackageVerificationState verificationState = new PackageVerificationState( 11847 requiredUid, args); 11848 11849 mPendingVerification.append(verificationId, verificationState); 11850 11851 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11852 receivers, verificationState); 11853 11854 /* 11855 * If any sufficient verifiers were listed in the package 11856 * manifest, attempt to ask them. 11857 */ 11858 if (sufficientVerifiers != null) { 11859 final int N = sufficientVerifiers.size(); 11860 if (N == 0) { 11861 Slog.i(TAG, "Additional verifiers required, but none installed."); 11862 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11863 } else { 11864 for (int i = 0; i < N; i++) { 11865 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11866 11867 final Intent sufficientIntent = new Intent(verification); 11868 sufficientIntent.setComponent(verifierComponent); 11869 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11870 } 11871 } 11872 } 11873 11874 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11875 mRequiredVerifierPackage, receivers); 11876 if (ret == PackageManager.INSTALL_SUCCEEDED 11877 && mRequiredVerifierPackage != null) { 11878 Trace.asyncTraceBegin( 11879 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11880 /* 11881 * Send the intent to the required verification agent, 11882 * but only start the verification timeout after the 11883 * target BroadcastReceivers have run. 11884 */ 11885 verification.setComponent(requiredVerifierComponent); 11886 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11887 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11888 new BroadcastReceiver() { 11889 @Override 11890 public void onReceive(Context context, Intent intent) { 11891 final Message msg = mHandler 11892 .obtainMessage(CHECK_PENDING_VERIFICATION); 11893 msg.arg1 = verificationId; 11894 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11895 } 11896 }, null, 0, null, null); 11897 11898 /* 11899 * We don't want the copy to proceed until verification 11900 * succeeds, so null out this field. 11901 */ 11902 mArgs = null; 11903 } 11904 } else { 11905 /* 11906 * No package verification is enabled, so immediately start 11907 * the remote call to initiate copy using temporary file. 11908 */ 11909 ret = args.copyApk(mContainerService, true); 11910 } 11911 } 11912 11913 mRet = ret; 11914 } 11915 11916 @Override 11917 void handleReturnCode() { 11918 // If mArgs is null, then MCS couldn't be reached. When it 11919 // reconnects, it will try again to install. At that point, this 11920 // will succeed. 11921 if (mArgs != null) { 11922 processPendingInstall(mArgs, mRet); 11923 } 11924 } 11925 11926 @Override 11927 void handleServiceError() { 11928 mArgs = createInstallArgs(this); 11929 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11930 } 11931 11932 public boolean isForwardLocked() { 11933 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11934 } 11935 } 11936 11937 /** 11938 * Used during creation of InstallArgs 11939 * 11940 * @param installFlags package installation flags 11941 * @return true if should be installed on external storage 11942 */ 11943 private static boolean installOnExternalAsec(int installFlags) { 11944 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11945 return false; 11946 } 11947 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11948 return true; 11949 } 11950 return false; 11951 } 11952 11953 /** 11954 * Used during creation of InstallArgs 11955 * 11956 * @param installFlags package installation flags 11957 * @return true if should be installed as forward locked 11958 */ 11959 private static boolean installForwardLocked(int installFlags) { 11960 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11961 } 11962 11963 private InstallArgs createInstallArgs(InstallParams params) { 11964 if (params.move != null) { 11965 return new MoveInstallArgs(params); 11966 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11967 return new AsecInstallArgs(params); 11968 } else { 11969 return new FileInstallArgs(params); 11970 } 11971 } 11972 11973 /** 11974 * Create args that describe an existing installed package. Typically used 11975 * when cleaning up old installs, or used as a move source. 11976 */ 11977 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11978 String resourcePath, String[] instructionSets) { 11979 final boolean isInAsec; 11980 if (installOnExternalAsec(installFlags)) { 11981 /* Apps on SD card are always in ASEC containers. */ 11982 isInAsec = true; 11983 } else if (installForwardLocked(installFlags) 11984 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11985 /* 11986 * Forward-locked apps are only in ASEC containers if they're the 11987 * new style 11988 */ 11989 isInAsec = true; 11990 } else { 11991 isInAsec = false; 11992 } 11993 11994 if (isInAsec) { 11995 return new AsecInstallArgs(codePath, instructionSets, 11996 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11997 } else { 11998 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11999 } 12000 } 12001 12002 static abstract class InstallArgs { 12003 /** @see InstallParams#origin */ 12004 final OriginInfo origin; 12005 /** @see InstallParams#move */ 12006 final MoveInfo move; 12007 12008 final IPackageInstallObserver2 observer; 12009 // Always refers to PackageManager flags only 12010 final int installFlags; 12011 final String installerPackageName; 12012 final String volumeUuid; 12013 final UserHandle user; 12014 final String abiOverride; 12015 final String[] installGrantPermissions; 12016 /** If non-null, drop an async trace when the install completes */ 12017 final String traceMethod; 12018 final int traceCookie; 12019 12020 // The list of instruction sets supported by this app. This is currently 12021 // only used during the rmdex() phase to clean up resources. We can get rid of this 12022 // if we move dex files under the common app path. 12023 /* nullable */ String[] instructionSets; 12024 12025 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12026 int installFlags, String installerPackageName, String volumeUuid, 12027 UserHandle user, String[] instructionSets, 12028 String abiOverride, String[] installGrantPermissions, 12029 String traceMethod, int traceCookie) { 12030 this.origin = origin; 12031 this.move = move; 12032 this.installFlags = installFlags; 12033 this.observer = observer; 12034 this.installerPackageName = installerPackageName; 12035 this.volumeUuid = volumeUuid; 12036 this.user = user; 12037 this.instructionSets = instructionSets; 12038 this.abiOverride = abiOverride; 12039 this.installGrantPermissions = installGrantPermissions; 12040 this.traceMethod = traceMethod; 12041 this.traceCookie = traceCookie; 12042 } 12043 12044 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12045 abstract int doPreInstall(int status); 12046 12047 /** 12048 * Rename package into final resting place. All paths on the given 12049 * scanned package should be updated to reflect the rename. 12050 */ 12051 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12052 abstract int doPostInstall(int status, int uid); 12053 12054 /** @see PackageSettingBase#codePathString */ 12055 abstract String getCodePath(); 12056 /** @see PackageSettingBase#resourcePathString */ 12057 abstract String getResourcePath(); 12058 12059 // Need installer lock especially for dex file removal. 12060 abstract void cleanUpResourcesLI(); 12061 abstract boolean doPostDeleteLI(boolean delete); 12062 12063 /** 12064 * Called before the source arguments are copied. This is used mostly 12065 * for MoveParams when it needs to read the source file to put it in the 12066 * destination. 12067 */ 12068 int doPreCopy() { 12069 return PackageManager.INSTALL_SUCCEEDED; 12070 } 12071 12072 /** 12073 * Called after the source arguments are copied. This is used mostly for 12074 * MoveParams when it needs to read the source file to put it in the 12075 * destination. 12076 * 12077 * @return 12078 */ 12079 int doPostCopy(int uid) { 12080 return PackageManager.INSTALL_SUCCEEDED; 12081 } 12082 12083 protected boolean isFwdLocked() { 12084 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12085 } 12086 12087 protected boolean isExternalAsec() { 12088 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12089 } 12090 12091 protected boolean isEphemeral() { 12092 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12093 } 12094 12095 UserHandle getUser() { 12096 return user; 12097 } 12098 } 12099 12100 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12101 if (!allCodePaths.isEmpty()) { 12102 if (instructionSets == null) { 12103 throw new IllegalStateException("instructionSet == null"); 12104 } 12105 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12106 for (String codePath : allCodePaths) { 12107 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12108 try { 12109 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12110 } catch (InstallerException ignored) { 12111 } 12112 } 12113 } 12114 } 12115 } 12116 12117 /** 12118 * Logic to handle installation of non-ASEC applications, including copying 12119 * and renaming logic. 12120 */ 12121 class FileInstallArgs extends InstallArgs { 12122 private File codeFile; 12123 private File resourceFile; 12124 12125 // Example topology: 12126 // /data/app/com.example/base.apk 12127 // /data/app/com.example/split_foo.apk 12128 // /data/app/com.example/lib/arm/libfoo.so 12129 // /data/app/com.example/lib/arm64/libfoo.so 12130 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12131 12132 /** New install */ 12133 FileInstallArgs(InstallParams params) { 12134 super(params.origin, params.move, params.observer, params.installFlags, 12135 params.installerPackageName, params.volumeUuid, 12136 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12137 params.grantedRuntimePermissions, 12138 params.traceMethod, params.traceCookie); 12139 if (isFwdLocked()) { 12140 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12141 } 12142 } 12143 12144 /** Existing install */ 12145 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12146 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12147 null, null, null, 0); 12148 this.codeFile = (codePath != null) ? new File(codePath) : null; 12149 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12150 } 12151 12152 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12153 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12154 try { 12155 return doCopyApk(imcs, temp); 12156 } finally { 12157 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12158 } 12159 } 12160 12161 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12162 if (origin.staged) { 12163 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12164 codeFile = origin.file; 12165 resourceFile = origin.file; 12166 return PackageManager.INSTALL_SUCCEEDED; 12167 } 12168 12169 try { 12170 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12171 final File tempDir = 12172 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12173 codeFile = tempDir; 12174 resourceFile = tempDir; 12175 } catch (IOException e) { 12176 Slog.w(TAG, "Failed to create copy file: " + e); 12177 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12178 } 12179 12180 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12181 @Override 12182 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12183 if (!FileUtils.isValidExtFilename(name)) { 12184 throw new IllegalArgumentException("Invalid filename: " + name); 12185 } 12186 try { 12187 final File file = new File(codeFile, name); 12188 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12189 O_RDWR | O_CREAT, 0644); 12190 Os.chmod(file.getAbsolutePath(), 0644); 12191 return new ParcelFileDescriptor(fd); 12192 } catch (ErrnoException e) { 12193 throw new RemoteException("Failed to open: " + e.getMessage()); 12194 } 12195 } 12196 }; 12197 12198 int ret = PackageManager.INSTALL_SUCCEEDED; 12199 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12200 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12201 Slog.e(TAG, "Failed to copy package"); 12202 return ret; 12203 } 12204 12205 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12206 NativeLibraryHelper.Handle handle = null; 12207 try { 12208 handle = NativeLibraryHelper.Handle.create(codeFile); 12209 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12210 abiOverride); 12211 } catch (IOException e) { 12212 Slog.e(TAG, "Copying native libraries failed", e); 12213 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12214 } finally { 12215 IoUtils.closeQuietly(handle); 12216 } 12217 12218 return ret; 12219 } 12220 12221 int doPreInstall(int status) { 12222 if (status != PackageManager.INSTALL_SUCCEEDED) { 12223 cleanUp(); 12224 } 12225 return status; 12226 } 12227 12228 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12229 if (status != PackageManager.INSTALL_SUCCEEDED) { 12230 cleanUp(); 12231 return false; 12232 } 12233 12234 final File targetDir = codeFile.getParentFile(); 12235 final File beforeCodeFile = codeFile; 12236 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12237 12238 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12239 try { 12240 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12241 } catch (ErrnoException e) { 12242 Slog.w(TAG, "Failed to rename", e); 12243 return false; 12244 } 12245 12246 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12247 Slog.w(TAG, "Failed to restorecon"); 12248 return false; 12249 } 12250 12251 // Reflect the rename internally 12252 codeFile = afterCodeFile; 12253 resourceFile = afterCodeFile; 12254 12255 // Reflect the rename in scanned details 12256 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12257 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12258 afterCodeFile, pkg.baseCodePath)); 12259 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12260 afterCodeFile, pkg.splitCodePaths)); 12261 12262 // Reflect the rename in app info 12263 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12264 pkg.setApplicationInfoCodePath(pkg.codePath); 12265 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12266 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12267 pkg.setApplicationInfoResourcePath(pkg.codePath); 12268 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12269 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12270 12271 return true; 12272 } 12273 12274 int doPostInstall(int status, int uid) { 12275 if (status != PackageManager.INSTALL_SUCCEEDED) { 12276 cleanUp(); 12277 } 12278 return status; 12279 } 12280 12281 @Override 12282 String getCodePath() { 12283 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12284 } 12285 12286 @Override 12287 String getResourcePath() { 12288 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12289 } 12290 12291 private boolean cleanUp() { 12292 if (codeFile == null || !codeFile.exists()) { 12293 return false; 12294 } 12295 12296 removeCodePathLI(codeFile); 12297 12298 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12299 resourceFile.delete(); 12300 } 12301 12302 return true; 12303 } 12304 12305 void cleanUpResourcesLI() { 12306 // Try enumerating all code paths before deleting 12307 List<String> allCodePaths = Collections.EMPTY_LIST; 12308 if (codeFile != null && codeFile.exists()) { 12309 try { 12310 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12311 allCodePaths = pkg.getAllCodePaths(); 12312 } catch (PackageParserException e) { 12313 // Ignored; we tried our best 12314 } 12315 } 12316 12317 cleanUp(); 12318 removeDexFiles(allCodePaths, instructionSets); 12319 } 12320 12321 boolean doPostDeleteLI(boolean delete) { 12322 // XXX err, shouldn't we respect the delete flag? 12323 cleanUpResourcesLI(); 12324 return true; 12325 } 12326 } 12327 12328 private boolean isAsecExternal(String cid) { 12329 final String asecPath = PackageHelper.getSdFilesystem(cid); 12330 return !asecPath.startsWith(mAsecInternalPath); 12331 } 12332 12333 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12334 PackageManagerException { 12335 if (copyRet < 0) { 12336 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12337 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12338 throw new PackageManagerException(copyRet, message); 12339 } 12340 } 12341 } 12342 12343 /** 12344 * Extract the MountService "container ID" from the full code path of an 12345 * .apk. 12346 */ 12347 static String cidFromCodePath(String fullCodePath) { 12348 int eidx = fullCodePath.lastIndexOf("/"); 12349 String subStr1 = fullCodePath.substring(0, eidx); 12350 int sidx = subStr1.lastIndexOf("/"); 12351 return subStr1.substring(sidx+1, eidx); 12352 } 12353 12354 /** 12355 * Logic to handle installation of ASEC applications, including copying and 12356 * renaming logic. 12357 */ 12358 class AsecInstallArgs extends InstallArgs { 12359 static final String RES_FILE_NAME = "pkg.apk"; 12360 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12361 12362 String cid; 12363 String packagePath; 12364 String resourcePath; 12365 12366 /** New install */ 12367 AsecInstallArgs(InstallParams params) { 12368 super(params.origin, params.move, params.observer, params.installFlags, 12369 params.installerPackageName, params.volumeUuid, 12370 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12371 params.grantedRuntimePermissions, 12372 params.traceMethod, params.traceCookie); 12373 } 12374 12375 /** Existing install */ 12376 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12377 boolean isExternal, boolean isForwardLocked) { 12378 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12379 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12380 instructionSets, null, null, null, 0); 12381 // Hackily pretend we're still looking at a full code path 12382 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12383 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12384 } 12385 12386 // Extract cid from fullCodePath 12387 int eidx = fullCodePath.lastIndexOf("/"); 12388 String subStr1 = fullCodePath.substring(0, eidx); 12389 int sidx = subStr1.lastIndexOf("/"); 12390 cid = subStr1.substring(sidx+1, eidx); 12391 setMountPath(subStr1); 12392 } 12393 12394 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12395 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12396 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12397 instructionSets, null, null, null, 0); 12398 this.cid = cid; 12399 setMountPath(PackageHelper.getSdDir(cid)); 12400 } 12401 12402 void createCopyFile() { 12403 cid = mInstallerService.allocateExternalStageCidLegacy(); 12404 } 12405 12406 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12407 if (origin.staged && origin.cid != null) { 12408 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12409 cid = origin.cid; 12410 setMountPath(PackageHelper.getSdDir(cid)); 12411 return PackageManager.INSTALL_SUCCEEDED; 12412 } 12413 12414 if (temp) { 12415 createCopyFile(); 12416 } else { 12417 /* 12418 * Pre-emptively destroy the container since it's destroyed if 12419 * copying fails due to it existing anyway. 12420 */ 12421 PackageHelper.destroySdDir(cid); 12422 } 12423 12424 final String newMountPath = imcs.copyPackageToContainer( 12425 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12426 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12427 12428 if (newMountPath != null) { 12429 setMountPath(newMountPath); 12430 return PackageManager.INSTALL_SUCCEEDED; 12431 } else { 12432 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12433 } 12434 } 12435 12436 @Override 12437 String getCodePath() { 12438 return packagePath; 12439 } 12440 12441 @Override 12442 String getResourcePath() { 12443 return resourcePath; 12444 } 12445 12446 int doPreInstall(int status) { 12447 if (status != PackageManager.INSTALL_SUCCEEDED) { 12448 // Destroy container 12449 PackageHelper.destroySdDir(cid); 12450 } else { 12451 boolean mounted = PackageHelper.isContainerMounted(cid); 12452 if (!mounted) { 12453 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 12454 Process.SYSTEM_UID); 12455 if (newMountPath != null) { 12456 setMountPath(newMountPath); 12457 } else { 12458 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12459 } 12460 } 12461 } 12462 return status; 12463 } 12464 12465 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12466 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 12467 String newMountPath = null; 12468 if (PackageHelper.isContainerMounted(cid)) { 12469 // Unmount the container 12470 if (!PackageHelper.unMountSdDir(cid)) { 12471 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 12472 return false; 12473 } 12474 } 12475 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12476 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 12477 " which might be stale. Will try to clean up."); 12478 // Clean up the stale container and proceed to recreate. 12479 if (!PackageHelper.destroySdDir(newCacheId)) { 12480 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 12481 return false; 12482 } 12483 // Successfully cleaned up stale container. Try to rename again. 12484 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12485 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 12486 + " inspite of cleaning it up."); 12487 return false; 12488 } 12489 } 12490 if (!PackageHelper.isContainerMounted(newCacheId)) { 12491 Slog.w(TAG, "Mounting container " + newCacheId); 12492 newMountPath = PackageHelper.mountSdDir(newCacheId, 12493 getEncryptKey(), Process.SYSTEM_UID); 12494 } else { 12495 newMountPath = PackageHelper.getSdDir(newCacheId); 12496 } 12497 if (newMountPath == null) { 12498 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 12499 return false; 12500 } 12501 Log.i(TAG, "Succesfully renamed " + cid + 12502 " to " + newCacheId + 12503 " at new path: " + newMountPath); 12504 cid = newCacheId; 12505 12506 final File beforeCodeFile = new File(packagePath); 12507 setMountPath(newMountPath); 12508 final File afterCodeFile = new File(packagePath); 12509 12510 // Reflect the rename in scanned details 12511 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12512 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12513 afterCodeFile, pkg.baseCodePath)); 12514 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12515 afterCodeFile, pkg.splitCodePaths)); 12516 12517 // Reflect the rename in app info 12518 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12519 pkg.setApplicationInfoCodePath(pkg.codePath); 12520 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12521 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12522 pkg.setApplicationInfoResourcePath(pkg.codePath); 12523 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12524 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12525 12526 return true; 12527 } 12528 12529 private void setMountPath(String mountPath) { 12530 final File mountFile = new File(mountPath); 12531 12532 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 12533 if (monolithicFile.exists()) { 12534 packagePath = monolithicFile.getAbsolutePath(); 12535 if (isFwdLocked()) { 12536 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 12537 } else { 12538 resourcePath = packagePath; 12539 } 12540 } else { 12541 packagePath = mountFile.getAbsolutePath(); 12542 resourcePath = packagePath; 12543 } 12544 } 12545 12546 int doPostInstall(int status, int uid) { 12547 if (status != PackageManager.INSTALL_SUCCEEDED) { 12548 cleanUp(); 12549 } else { 12550 final int groupOwner; 12551 final String protectedFile; 12552 if (isFwdLocked()) { 12553 groupOwner = UserHandle.getSharedAppGid(uid); 12554 protectedFile = RES_FILE_NAME; 12555 } else { 12556 groupOwner = -1; 12557 protectedFile = null; 12558 } 12559 12560 if (uid < Process.FIRST_APPLICATION_UID 12561 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 12562 Slog.e(TAG, "Failed to finalize " + cid); 12563 PackageHelper.destroySdDir(cid); 12564 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12565 } 12566 12567 boolean mounted = PackageHelper.isContainerMounted(cid); 12568 if (!mounted) { 12569 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12570 } 12571 } 12572 return status; 12573 } 12574 12575 private void cleanUp() { 12576 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12577 12578 // Destroy secure container 12579 PackageHelper.destroySdDir(cid); 12580 } 12581 12582 private List<String> getAllCodePaths() { 12583 final File codeFile = new File(getCodePath()); 12584 if (codeFile != null && codeFile.exists()) { 12585 try { 12586 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12587 return pkg.getAllCodePaths(); 12588 } catch (PackageParserException e) { 12589 // Ignored; we tried our best 12590 } 12591 } 12592 return Collections.EMPTY_LIST; 12593 } 12594 12595 void cleanUpResourcesLI() { 12596 // Enumerate all code paths before deleting 12597 cleanUpResourcesLI(getAllCodePaths()); 12598 } 12599 12600 private void cleanUpResourcesLI(List<String> allCodePaths) { 12601 cleanUp(); 12602 removeDexFiles(allCodePaths, instructionSets); 12603 } 12604 12605 String getPackageName() { 12606 return getAsecPackageName(cid); 12607 } 12608 12609 boolean doPostDeleteLI(boolean delete) { 12610 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12611 final List<String> allCodePaths = getAllCodePaths(); 12612 boolean mounted = PackageHelper.isContainerMounted(cid); 12613 if (mounted) { 12614 // Unmount first 12615 if (PackageHelper.unMountSdDir(cid)) { 12616 mounted = false; 12617 } 12618 } 12619 if (!mounted && delete) { 12620 cleanUpResourcesLI(allCodePaths); 12621 } 12622 return !mounted; 12623 } 12624 12625 @Override 12626 int doPreCopy() { 12627 if (isFwdLocked()) { 12628 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12629 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12630 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12631 } 12632 } 12633 12634 return PackageManager.INSTALL_SUCCEEDED; 12635 } 12636 12637 @Override 12638 int doPostCopy(int uid) { 12639 if (isFwdLocked()) { 12640 if (uid < Process.FIRST_APPLICATION_UID 12641 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12642 RES_FILE_NAME)) { 12643 Slog.e(TAG, "Failed to finalize " + cid); 12644 PackageHelper.destroySdDir(cid); 12645 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12646 } 12647 } 12648 12649 return PackageManager.INSTALL_SUCCEEDED; 12650 } 12651 } 12652 12653 /** 12654 * Logic to handle movement of existing installed applications. 12655 */ 12656 class MoveInstallArgs extends InstallArgs { 12657 private File codeFile; 12658 private File resourceFile; 12659 12660 /** New install */ 12661 MoveInstallArgs(InstallParams params) { 12662 super(params.origin, params.move, params.observer, params.installFlags, 12663 params.installerPackageName, params.volumeUuid, 12664 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12665 params.grantedRuntimePermissions, 12666 params.traceMethod, params.traceCookie); 12667 } 12668 12669 int copyApk(IMediaContainerService imcs, boolean temp) { 12670 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12671 + move.fromUuid + " to " + move.toUuid); 12672 synchronized (mInstaller) { 12673 try { 12674 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12675 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12676 } catch (InstallerException e) { 12677 Slog.w(TAG, "Failed to move app", e); 12678 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12679 } 12680 } 12681 12682 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12683 resourceFile = codeFile; 12684 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12685 12686 return PackageManager.INSTALL_SUCCEEDED; 12687 } 12688 12689 int doPreInstall(int status) { 12690 if (status != PackageManager.INSTALL_SUCCEEDED) { 12691 cleanUp(move.toUuid); 12692 } 12693 return status; 12694 } 12695 12696 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12697 if (status != PackageManager.INSTALL_SUCCEEDED) { 12698 cleanUp(move.toUuid); 12699 return false; 12700 } 12701 12702 // Reflect the move in app info 12703 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12704 pkg.setApplicationInfoCodePath(pkg.codePath); 12705 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12706 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12707 pkg.setApplicationInfoResourcePath(pkg.codePath); 12708 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12709 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12710 12711 return true; 12712 } 12713 12714 int doPostInstall(int status, int uid) { 12715 if (status == PackageManager.INSTALL_SUCCEEDED) { 12716 cleanUp(move.fromUuid); 12717 } else { 12718 cleanUp(move.toUuid); 12719 } 12720 return status; 12721 } 12722 12723 @Override 12724 String getCodePath() { 12725 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12726 } 12727 12728 @Override 12729 String getResourcePath() { 12730 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12731 } 12732 12733 private boolean cleanUp(String volumeUuid) { 12734 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12735 move.dataAppName); 12736 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12737 synchronized (mInstallLock) { 12738 // Clean up both app data and code 12739 removeDataDirsLI(volumeUuid, move.packageName); 12740 removeCodePathLI(codeFile); 12741 } 12742 return true; 12743 } 12744 12745 void cleanUpResourcesLI() { 12746 throw new UnsupportedOperationException(); 12747 } 12748 12749 boolean doPostDeleteLI(boolean delete) { 12750 throw new UnsupportedOperationException(); 12751 } 12752 } 12753 12754 static String getAsecPackageName(String packageCid) { 12755 int idx = packageCid.lastIndexOf("-"); 12756 if (idx == -1) { 12757 return packageCid; 12758 } 12759 return packageCid.substring(0, idx); 12760 } 12761 12762 // Utility method used to create code paths based on package name and available index. 12763 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12764 String idxStr = ""; 12765 int idx = 1; 12766 // Fall back to default value of idx=1 if prefix is not 12767 // part of oldCodePath 12768 if (oldCodePath != null) { 12769 String subStr = oldCodePath; 12770 // Drop the suffix right away 12771 if (suffix != null && subStr.endsWith(suffix)) { 12772 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12773 } 12774 // If oldCodePath already contains prefix find out the 12775 // ending index to either increment or decrement. 12776 int sidx = subStr.lastIndexOf(prefix); 12777 if (sidx != -1) { 12778 subStr = subStr.substring(sidx + prefix.length()); 12779 if (subStr != null) { 12780 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12781 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12782 } 12783 try { 12784 idx = Integer.parseInt(subStr); 12785 if (idx <= 1) { 12786 idx++; 12787 } else { 12788 idx--; 12789 } 12790 } catch(NumberFormatException e) { 12791 } 12792 } 12793 } 12794 } 12795 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12796 return prefix + idxStr; 12797 } 12798 12799 private File getNextCodePath(File targetDir, String packageName) { 12800 int suffix = 1; 12801 File result; 12802 do { 12803 result = new File(targetDir, packageName + "-" + suffix); 12804 suffix++; 12805 } while (result.exists()); 12806 return result; 12807 } 12808 12809 // Utility method that returns the relative package path with respect 12810 // to the installation directory. Like say for /data/data/com.test-1.apk 12811 // string com.test-1 is returned. 12812 static String deriveCodePathName(String codePath) { 12813 if (codePath == null) { 12814 return null; 12815 } 12816 final File codeFile = new File(codePath); 12817 final String name = codeFile.getName(); 12818 if (codeFile.isDirectory()) { 12819 return name; 12820 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12821 final int lastDot = name.lastIndexOf('.'); 12822 return name.substring(0, lastDot); 12823 } else { 12824 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12825 return null; 12826 } 12827 } 12828 12829 static class PackageInstalledInfo { 12830 String name; 12831 int uid; 12832 // The set of users that originally had this package installed. 12833 int[] origUsers; 12834 // The set of users that now have this package installed. 12835 int[] newUsers; 12836 PackageParser.Package pkg; 12837 int returnCode; 12838 String returnMsg; 12839 PackageRemovedInfo removedInfo; 12840 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 12841 12842 public void setError(int code, String msg) { 12843 setReturnCode(code); 12844 setReturnMessage(msg); 12845 Slog.w(TAG, msg); 12846 } 12847 12848 public void setError(String msg, PackageParserException e) { 12849 setReturnCode(e.error); 12850 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 12851 Slog.w(TAG, msg, e); 12852 } 12853 12854 public void setError(String msg, PackageManagerException e) { 12855 returnCode = e.error; 12856 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 12857 Slog.w(TAG, msg, e); 12858 } 12859 12860 public void setReturnCode(int returnCode) { 12861 this.returnCode = returnCode; 12862 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 12863 for (int i = 0; i < childCount; i++) { 12864 addedChildPackages.valueAt(i).returnCode = returnCode; 12865 } 12866 } 12867 12868 private void setReturnMessage(String returnMsg) { 12869 this.returnMsg = returnMsg; 12870 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 12871 for (int i = 0; i < childCount; i++) { 12872 addedChildPackages.valueAt(i).returnMsg = returnMsg; 12873 } 12874 } 12875 12876 // In some error cases we want to convey more info back to the observer 12877 String origPackage; 12878 String origPermission; 12879 } 12880 12881 /* 12882 * Install a non-existing package. 12883 */ 12884 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12885 UserHandle user, String installerPackageName, String volumeUuid, 12886 PackageInstalledInfo res) { 12887 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12888 12889 // Remember this for later, in case we need to rollback this install 12890 String pkgName = pkg.packageName; 12891 12892 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12893 12894 synchronized(mPackages) { 12895 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12896 // A package with the same name is already installed, though 12897 // it has been renamed to an older name. The package we 12898 // are trying to install should be installed as an update to 12899 // the existing one, but that has not been requested, so bail. 12900 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12901 + " without first uninstalling package running as " 12902 + mSettings.mRenamedPackages.get(pkgName)); 12903 return; 12904 } 12905 if (mPackages.containsKey(pkgName)) { 12906 // Don't allow installation over an existing package with the same name. 12907 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12908 + " without first uninstalling."); 12909 return; 12910 } 12911 } 12912 12913 try { 12914 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12915 System.currentTimeMillis(), user); 12916 12917 updateSettingsLI(newPackage, installerPackageName, null, res, user); 12918 12919 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12920 prepareAppDataAfterInstall(newPackage); 12921 12922 } else { 12923 // Remove package from internal structures, but keep around any 12924 // data that might have already existed 12925 deletePackageLI(pkgName, UserHandle.ALL, false, null, 12926 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 12927 } 12928 } catch (PackageManagerException e) { 12929 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12930 } 12931 12932 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12933 } 12934 12935 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12936 // Can't rotate keys during boot or if sharedUser. 12937 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12938 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12939 return false; 12940 } 12941 // app is using upgradeKeySets; make sure all are valid 12942 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12943 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12944 for (int i = 0; i < upgradeKeySets.length; i++) { 12945 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12946 Slog.wtf(TAG, "Package " 12947 + (oldPs.name != null ? oldPs.name : "<null>") 12948 + " contains upgrade-key-set reference to unknown key-set: " 12949 + upgradeKeySets[i] 12950 + " reverting to signatures check."); 12951 return false; 12952 } 12953 } 12954 return true; 12955 } 12956 12957 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12958 // Upgrade keysets are being used. Determine if new package has a superset of the 12959 // required keys. 12960 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12961 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12962 for (int i = 0; i < upgradeKeySets.length; i++) { 12963 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12964 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12965 return true; 12966 } 12967 } 12968 return false; 12969 } 12970 12971 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12972 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 12973 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12974 12975 final PackageParser.Package oldPackage; 12976 final String pkgName = pkg.packageName; 12977 final int[] allUsers; 12978 12979 // First find the old package info and check signatures 12980 synchronized(mPackages) { 12981 oldPackage = mPackages.get(pkgName); 12982 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12983 if (isEphemeral && !oldIsEphemeral) { 12984 // can't downgrade from full to ephemeral 12985 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12986 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 12987 return; 12988 } 12989 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12990 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12991 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12992 if (!checkUpgradeKeySetLP(ps, pkg)) { 12993 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12994 "New package not signed by keys specified by upgrade-keysets: " 12995 + pkgName); 12996 return; 12997 } 12998 } else { 12999 // default to original signature matching 13000 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13001 != PackageManager.SIGNATURE_MATCH) { 13002 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13003 "New package has a different signature: " + pkgName); 13004 return; 13005 } 13006 } 13007 13008 // In case of rollback, remember per-user/profile install state 13009 allUsers = sUserManager.getUserIds(); 13010 } 13011 13012 // Update what is removed 13013 res.removedInfo = new PackageRemovedInfo(); 13014 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13015 res.removedInfo.removedPackage = oldPackage.packageName; 13016 res.removedInfo.isUpdate = true; 13017 final int childCount = (oldPackage.childPackages != null) 13018 ? oldPackage.childPackages.size() : 0; 13019 for (int i = 0; i < childCount; i++) { 13020 boolean childPackageUpdated = false; 13021 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13022 if (res.addedChildPackages != null) { 13023 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13024 if (childRes != null) { 13025 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13026 childRes.removedInfo.removedPackage = childPkg.packageName; 13027 childRes.removedInfo.isUpdate = true; 13028 childPackageUpdated = true; 13029 } 13030 } 13031 if (!childPackageUpdated) { 13032 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13033 childRemovedRes.removedPackage = childPkg.packageName; 13034 childRemovedRes.isUpdate = false; 13035 childRemovedRes.dataRemoved = true; 13036 synchronized (mPackages) { 13037 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13038 if (childPs != null) { 13039 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13040 } 13041 } 13042 if (res.removedInfo.removedChildPackages == null) { 13043 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13044 } 13045 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13046 } 13047 } 13048 13049 boolean sysPkg = (isSystemApp(oldPackage)); 13050 if (sysPkg) { 13051 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13052 user, allUsers, installerPackageName, res); 13053 } else { 13054 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13055 user, allUsers, installerPackageName, res); 13056 } 13057 } 13058 13059 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 13060 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13061 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13062 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13063 + deletedPackage); 13064 13065 String pkgName = deletedPackage.packageName; 13066 boolean deletedPkg = true; 13067 boolean addedPkg = false; 13068 13069 final long origUpdateTime = (pkg.mExtras != null) 13070 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13071 13072 // First delete the existing package while retaining the data directory 13073 if (!deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA, 13074 res.removedInfo, true, pkg)) { 13075 // If the existing package wasn't successfully deleted 13076 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13077 deletedPkg = false; 13078 } else { 13079 // Successfully deleted the old package; proceed with replace. 13080 13081 // If deleted package lived in a container, give users a chance to 13082 // relinquish resources before killing. 13083 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13084 if (DEBUG_INSTALL) { 13085 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13086 } 13087 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13088 final ArrayList<String> pkgList = new ArrayList<String>(1); 13089 pkgList.add(deletedPackage.applicationInfo.packageName); 13090 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13091 } 13092 13093 deleteCodeCacheDirsLI(pkg); 13094 13095 try { 13096 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13097 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13098 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13099 prepareAppDataAfterInstall(newPackage); 13100 addedPkg = true; 13101 } catch (PackageManagerException e) { 13102 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13103 } 13104 } 13105 13106 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13107 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13108 13109 // Revert all internal state mutations and added folders for the failed install 13110 if (addedPkg) { 13111 deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA, 13112 res.removedInfo, true, null); 13113 } 13114 13115 // Restore the old package 13116 if (deletedPkg) { 13117 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13118 File restoreFile = new File(deletedPackage.codePath); 13119 // Parse old package 13120 boolean oldExternal = isExternal(deletedPackage); 13121 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13122 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13123 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13124 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13125 try { 13126 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13127 null); 13128 } catch (PackageManagerException e) { 13129 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13130 + e.getMessage()); 13131 return; 13132 } 13133 13134 synchronized (mPackages) { 13135 // Ensure the installer package name up to date 13136 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13137 13138 // Update permissions for restored package 13139 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13140 13141 mSettings.writeLPr(); 13142 } 13143 13144 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13145 } 13146 } else { 13147 synchronized (mPackages) { 13148 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13149 if (ps != null) { 13150 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13151 if (res.removedInfo.removedChildPackages != null) { 13152 final int childCount = res.removedInfo.removedChildPackages.size(); 13153 // Iterate in reverse as we may modify the collection 13154 for (int i = childCount - 1; i >= 0; i--) { 13155 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13156 if (res.addedChildPackages.containsKey(childPackageName)) { 13157 res.removedInfo.removedChildPackages.removeAt(i); 13158 } else { 13159 PackageRemovedInfo childInfo = res.removedInfo 13160 .removedChildPackages.valueAt(i); 13161 childInfo.removedForAllUsers = mPackages.get( 13162 childInfo.removedPackage) == null; 13163 } 13164 } 13165 } 13166 } 13167 } 13168 } 13169 } 13170 13171 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 13172 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13173 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13174 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13175 + ", old=" + deletedPackage); 13176 13177 final boolean disabledSystem; 13178 13179 // Set the system/privileged flags as needed 13180 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13181 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13182 != 0) { 13183 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13184 } 13185 13186 // Kill package processes including services, providers, etc. 13187 killPackage(deletedPackage, "replace sys pkg"); 13188 13189 // Remove existing system package 13190 removePackageLI(deletedPackage, true); 13191 13192 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13193 if (!disabledSystem) { 13194 // We didn't need to disable the .apk as a current system package, 13195 // which means we are replacing another update that is already 13196 // installed. We need to make sure to delete the older one's .apk. 13197 res.removedInfo.args = createInstallArgsForExisting(0, 13198 deletedPackage.applicationInfo.getCodePath(), 13199 deletedPackage.applicationInfo.getResourcePath(), 13200 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13201 } else { 13202 res.removedInfo.args = null; 13203 } 13204 13205 // Successfully disabled the old package. Now proceed with re-installation 13206 deleteCodeCacheDirsLI(pkg); 13207 13208 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13209 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13210 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13211 13212 PackageParser.Package newPackage = null; 13213 try { 13214 // Add the package to the internal data structures 13215 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13216 13217 // Set the update and install times 13218 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13219 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13220 System.currentTimeMillis()); 13221 13222 // Check for shared user id changes 13223 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13224 deletedPackage, newPackage); 13225 if (invalidPackageName != null) { 13226 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13227 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13228 + " to " + invalidPackageName); 13229 } 13230 13231 // Update the package dynamic state if succeeded 13232 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13233 // Now that the install succeeded make sure we remove data 13234 // directories for any child package the update removed. 13235 final int deletedChildCount = (deletedPackage.childPackages != null) 13236 ? deletedPackage.childPackages.size() : 0; 13237 final int newChildCount = (newPackage.childPackages != null) 13238 ? newPackage.childPackages.size() : 0; 13239 for (int i = 0; i < deletedChildCount; i++) { 13240 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13241 boolean childPackageDeleted = true; 13242 for (int j = 0; j < newChildCount; j++) { 13243 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13244 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13245 childPackageDeleted = false; 13246 break; 13247 } 13248 } 13249 if (childPackageDeleted) { 13250 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13251 deletedChildPkg.packageName); 13252 if (ps != null && res.removedInfo.removedChildPackages != null) { 13253 PackageRemovedInfo removedChildRes = res.removedInfo 13254 .removedChildPackages.get(deletedChildPkg.packageName); 13255 removePackageDataLI(ps, allUsers, removedChildRes, 0, false); 13256 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13257 } 13258 } 13259 } 13260 13261 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13262 prepareAppDataAfterInstall(newPackage); 13263 } 13264 } catch (PackageManagerException e) { 13265 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13266 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13267 } 13268 13269 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13270 // Re installation failed. Restore old information 13271 // Remove new pkg information 13272 if (newPackage != null) { 13273 removeInstalledPackageLI(newPackage, true); 13274 } 13275 // Add back the old system package 13276 try { 13277 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13278 } catch (PackageManagerException e) { 13279 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13280 } 13281 13282 synchronized (mPackages) { 13283 if (disabledSystem) { 13284 enableSystemPackageLPw(deletedPackage); 13285 } 13286 13287 // Ensure the installer package name up to date 13288 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13289 13290 // Update permissions for restored package 13291 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13292 13293 mSettings.writeLPr(); 13294 } 13295 13296 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13297 + " after failed upgrade"); 13298 } 13299 } 13300 13301 /** 13302 * Checks whether the parent or any of the child packages have a change shared 13303 * user. For a package to be a valid update the shred users of the parent and 13304 * the children should match. We may later support changing child shared users. 13305 * @param oldPkg The updated package. 13306 * @param newPkg The update package. 13307 * @return The shared user that change between the versions. 13308 */ 13309 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13310 PackageParser.Package newPkg) { 13311 // Check parent shared user 13312 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13313 return newPkg.packageName; 13314 } 13315 // Check child shared users 13316 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13317 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13318 for (int i = 0; i < newChildCount; i++) { 13319 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13320 // If this child was present, did it have the same shared user? 13321 for (int j = 0; j < oldChildCount; j++) { 13322 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13323 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13324 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13325 return newChildPkg.packageName; 13326 } 13327 } 13328 } 13329 return null; 13330 } 13331 13332 private void removeNativeBinariesLI(PackageSetting ps) { 13333 // Remove the lib path for the parent package 13334 if (ps != null) { 13335 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13336 // Remove the lib path for the child packages 13337 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 13338 for (int i = 0; i < childCount; i++) { 13339 PackageSetting childPs = null; 13340 synchronized (mPackages) { 13341 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 13342 } 13343 if (childPs != null) { 13344 NativeLibraryHelper.removeNativeBinariesLI(childPs 13345 .legacyNativeLibraryPathString); 13346 } 13347 } 13348 } 13349 } 13350 13351 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13352 // Enable the parent package 13353 mSettings.enableSystemPackageLPw(pkg.packageName); 13354 // Enable the child packages 13355 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13356 for (int i = 0; i < childCount; i++) { 13357 PackageParser.Package childPkg = pkg.childPackages.get(i); 13358 mSettings.enableSystemPackageLPw(childPkg.packageName); 13359 } 13360 } 13361 13362 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13363 PackageParser.Package newPkg) { 13364 // Disable the parent package (parent always replaced) 13365 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13366 // Disable the child packages 13367 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13368 for (int i = 0; i < childCount; i++) { 13369 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13370 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13371 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13372 } 13373 return disabled; 13374 } 13375 13376 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13377 String installerPackageName) { 13378 // Enable the parent package 13379 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 13380 // Enable the child packages 13381 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13382 for (int i = 0; i < childCount; i++) { 13383 PackageParser.Package childPkg = pkg.childPackages.get(i); 13384 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 13385 } 13386 } 13387 13388 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 13389 // Collect all used permissions in the UID 13390 ArraySet<String> usedPermissions = new ArraySet<>(); 13391 final int packageCount = su.packages.size(); 13392 for (int i = 0; i < packageCount; i++) { 13393 PackageSetting ps = su.packages.valueAt(i); 13394 if (ps.pkg == null) { 13395 continue; 13396 } 13397 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 13398 for (int j = 0; j < requestedPermCount; j++) { 13399 String permission = ps.pkg.requestedPermissions.get(j); 13400 BasePermission bp = mSettings.mPermissions.get(permission); 13401 if (bp != null) { 13402 usedPermissions.add(permission); 13403 } 13404 } 13405 } 13406 13407 PermissionsState permissionsState = su.getPermissionsState(); 13408 // Prune install permissions 13409 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 13410 final int installPermCount = installPermStates.size(); 13411 for (int i = installPermCount - 1; i >= 0; i--) { 13412 PermissionState permissionState = installPermStates.get(i); 13413 if (!usedPermissions.contains(permissionState.getName())) { 13414 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13415 if (bp != null) { 13416 permissionsState.revokeInstallPermission(bp); 13417 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 13418 PackageManager.MASK_PERMISSION_FLAGS, 0); 13419 } 13420 } 13421 } 13422 13423 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 13424 13425 // Prune runtime permissions 13426 for (int userId : allUserIds) { 13427 List<PermissionState> runtimePermStates = permissionsState 13428 .getRuntimePermissionStates(userId); 13429 final int runtimePermCount = runtimePermStates.size(); 13430 for (int i = runtimePermCount - 1; i >= 0; i--) { 13431 PermissionState permissionState = runtimePermStates.get(i); 13432 if (!usedPermissions.contains(permissionState.getName())) { 13433 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13434 if (bp != null) { 13435 permissionsState.revokeRuntimePermission(bp, userId); 13436 permissionsState.updatePermissionFlags(bp, userId, 13437 PackageManager.MASK_PERMISSION_FLAGS, 0); 13438 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 13439 runtimePermissionChangedUserIds, userId); 13440 } 13441 } 13442 } 13443 } 13444 13445 return runtimePermissionChangedUserIds; 13446 } 13447 13448 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 13449 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 13450 // Update the parent package setting 13451 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 13452 res, user); 13453 // Update the child packages setting 13454 final int childCount = (newPackage.childPackages != null) 13455 ? newPackage.childPackages.size() : 0; 13456 for (int i = 0; i < childCount; i++) { 13457 PackageParser.Package childPackage = newPackage.childPackages.get(i); 13458 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 13459 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 13460 childRes.origUsers, childRes, user); 13461 } 13462 } 13463 13464 private void updateSettingsInternalLI(PackageParser.Package newPackage, 13465 String installerPackageName, int[] allUsers, int[] installedForUsers, 13466 PackageInstalledInfo res, UserHandle user) { 13467 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 13468 13469 String pkgName = newPackage.packageName; 13470 synchronized (mPackages) { 13471 //write settings. the installStatus will be incomplete at this stage. 13472 //note that the new package setting would have already been 13473 //added to mPackages. It hasn't been persisted yet. 13474 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 13475 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13476 mSettings.writeLPr(); 13477 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13478 } 13479 13480 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 13481 synchronized (mPackages) { 13482 updatePermissionsLPw(newPackage.packageName, newPackage, 13483 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 13484 ? UPDATE_PERMISSIONS_ALL : 0)); 13485 // For system-bundled packages, we assume that installing an upgraded version 13486 // of the package implies that the user actually wants to run that new code, 13487 // so we enable the package. 13488 PackageSetting ps = mSettings.mPackages.get(pkgName); 13489 final int userId = user.getIdentifier(); 13490 if (ps != null) { 13491 if (isSystemApp(newPackage)) { 13492 if (DEBUG_INSTALL) { 13493 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 13494 } 13495 // Enable system package for requested users 13496 if (res.origUsers != null) { 13497 for (int origUserId : res.origUsers) { 13498 if (userId == UserHandle.USER_ALL || userId == origUserId) { 13499 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 13500 origUserId, installerPackageName); 13501 } 13502 } 13503 } 13504 // Also convey the prior install/uninstall state 13505 if (allUsers != null && installedForUsers != null) { 13506 for (int currentUserId : allUsers) { 13507 final boolean installed = ArrayUtils.contains( 13508 installedForUsers, currentUserId); 13509 if (DEBUG_INSTALL) { 13510 Slog.d(TAG, " user " + currentUserId + " => " + installed); 13511 } 13512 ps.setInstalled(installed, currentUserId); 13513 } 13514 // these install state changes will be persisted in the 13515 // upcoming call to mSettings.writeLPr(). 13516 } 13517 } 13518 // It's implied that when a user requests installation, they want the app to be 13519 // installed and enabled. 13520 if (userId != UserHandle.USER_ALL) { 13521 ps.setInstalled(true, userId); 13522 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 13523 } 13524 } 13525 res.name = pkgName; 13526 res.uid = newPackage.applicationInfo.uid; 13527 res.pkg = newPackage; 13528 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 13529 mSettings.setInstallerPackageName(pkgName, installerPackageName); 13530 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13531 //to update install status 13532 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13533 mSettings.writeLPr(); 13534 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13535 } 13536 13537 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13538 } 13539 13540 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 13541 try { 13542 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 13543 installPackageLI(args, res); 13544 } finally { 13545 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13546 } 13547 } 13548 13549 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 13550 final int installFlags = args.installFlags; 13551 final String installerPackageName = args.installerPackageName; 13552 final String volumeUuid = args.volumeUuid; 13553 final File tmpPackageFile = new File(args.getCodePath()); 13554 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 13555 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 13556 || (args.volumeUuid != null)); 13557 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 13558 boolean replace = false; 13559 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 13560 if (args.move != null) { 13561 // moving a complete application; perform an initial scan on the new install location 13562 scanFlags |= SCAN_INITIAL; 13563 } 13564 13565 // Result object to be returned 13566 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13567 13568 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 13569 13570 // Sanity check 13571 if (ephemeral && (forwardLocked || onExternal)) { 13572 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 13573 + " external=" + onExternal); 13574 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13575 return; 13576 } 13577 13578 // Retrieve PackageSettings and parse package 13579 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 13580 | PackageParser.PARSE_ENFORCE_CODE 13581 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 13582 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 13583 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 13584 PackageParser pp = new PackageParser(); 13585 pp.setSeparateProcesses(mSeparateProcesses); 13586 pp.setDisplayMetrics(mMetrics); 13587 13588 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 13589 final PackageParser.Package pkg; 13590 try { 13591 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 13592 } catch (PackageParserException e) { 13593 res.setError("Failed parse during installPackageLI", e); 13594 return; 13595 } finally { 13596 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13597 } 13598 13599 // If we are installing a clustered package add results for the children 13600 if (pkg.childPackages != null) { 13601 synchronized (mPackages) { 13602 final int childCount = pkg.childPackages.size(); 13603 for (int i = 0; i < childCount; i++) { 13604 PackageParser.Package childPkg = pkg.childPackages.get(i); 13605 PackageInstalledInfo childRes = new PackageInstalledInfo(); 13606 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13607 childRes.pkg = childPkg; 13608 childRes.name = childPkg.packageName; 13609 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13610 if (childPs != null) { 13611 childRes.origUsers = childPs.queryInstalledUsers( 13612 sUserManager.getUserIds(), true); 13613 } 13614 if ((mPackages.containsKey(childPkg.packageName))) { 13615 childRes.removedInfo = new PackageRemovedInfo(); 13616 childRes.removedInfo.removedPackage = childPkg.packageName; 13617 } 13618 if (res.addedChildPackages == null) { 13619 res.addedChildPackages = new ArrayMap<>(); 13620 } 13621 res.addedChildPackages.put(childPkg.packageName, childRes); 13622 } 13623 } 13624 } 13625 13626 // If package doesn't declare API override, mark that we have an install 13627 // time CPU ABI override. 13628 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 13629 pkg.cpuAbiOverride = args.abiOverride; 13630 } 13631 13632 String pkgName = res.name = pkg.packageName; 13633 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 13634 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 13635 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 13636 return; 13637 } 13638 } 13639 13640 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 13641 try { 13642 PackageParser.collectCertificates(pkg, parseFlags); 13643 } catch (PackageParserException e) { 13644 res.setError("Failed collect during installPackageLI", e); 13645 return; 13646 } finally { 13647 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13648 } 13649 13650 // Get rid of all references to package scan path via parser. 13651 pp = null; 13652 String oldCodePath = null; 13653 boolean systemApp = false; 13654 synchronized (mPackages) { 13655 // Check if installing already existing package 13656 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13657 String oldName = mSettings.mRenamedPackages.get(pkgName); 13658 if (pkg.mOriginalPackages != null 13659 && pkg.mOriginalPackages.contains(oldName) 13660 && mPackages.containsKey(oldName)) { 13661 // This package is derived from an original package, 13662 // and this device has been updating from that original 13663 // name. We must continue using the original name, so 13664 // rename the new package here. 13665 pkg.setPackageName(oldName); 13666 pkgName = pkg.packageName; 13667 replace = true; 13668 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 13669 + oldName + " pkgName=" + pkgName); 13670 } else if (mPackages.containsKey(pkgName)) { 13671 // This package, under its official name, already exists 13672 // on the device; we should replace it. 13673 replace = true; 13674 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 13675 } 13676 13677 // Child packages are installed through the parent package 13678 if (pkg.parentPackage != null) { 13679 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13680 "Package " + pkg.packageName + " is child of package " 13681 + pkg.parentPackage.parentPackage + ". Child packages " 13682 + "can be updated only through the parent package."); 13683 return; 13684 } 13685 13686 if (replace) { 13687 // Prevent apps opting out from runtime permissions 13688 PackageParser.Package oldPackage = mPackages.get(pkgName); 13689 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 13690 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 13691 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 13692 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 13693 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 13694 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 13695 + " doesn't support runtime permissions but the old" 13696 + " target SDK " + oldTargetSdk + " does."); 13697 return; 13698 } 13699 13700 // Prevent installing of child packages 13701 if (oldPackage.parentPackage != null) { 13702 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13703 "Package " + pkg.packageName + " is child of package " 13704 + oldPackage.parentPackage + ". Child packages " 13705 + "can be updated only through the parent package."); 13706 return; 13707 } 13708 } 13709 } 13710 13711 PackageSetting ps = mSettings.mPackages.get(pkgName); 13712 if (ps != null) { 13713 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 13714 13715 // Quick sanity check that we're signed correctly if updating; 13716 // we'll check this again later when scanning, but we want to 13717 // bail early here before tripping over redefined permissions. 13718 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13719 if (!checkUpgradeKeySetLP(ps, pkg)) { 13720 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 13721 + pkg.packageName + " upgrade keys do not match the " 13722 + "previously installed version"); 13723 return; 13724 } 13725 } else { 13726 try { 13727 verifySignaturesLP(ps, pkg); 13728 } catch (PackageManagerException e) { 13729 res.setError(e.error, e.getMessage()); 13730 return; 13731 } 13732 } 13733 13734 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 13735 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 13736 systemApp = (ps.pkg.applicationInfo.flags & 13737 ApplicationInfo.FLAG_SYSTEM) != 0; 13738 } 13739 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13740 } 13741 13742 // Check whether the newly-scanned package wants to define an already-defined perm 13743 int N = pkg.permissions.size(); 13744 for (int i = N-1; i >= 0; i--) { 13745 PackageParser.Permission perm = pkg.permissions.get(i); 13746 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 13747 if (bp != null) { 13748 // If the defining package is signed with our cert, it's okay. This 13749 // also includes the "updating the same package" case, of course. 13750 // "updating same package" could also involve key-rotation. 13751 final boolean sigsOk; 13752 if (bp.sourcePackage.equals(pkg.packageName) 13753 && (bp.packageSetting instanceof PackageSetting) 13754 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 13755 scanFlags))) { 13756 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 13757 } else { 13758 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 13759 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 13760 } 13761 if (!sigsOk) { 13762 // If the owning package is the system itself, we log but allow 13763 // install to proceed; we fail the install on all other permission 13764 // redefinitions. 13765 if (!bp.sourcePackage.equals("android")) { 13766 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 13767 + pkg.packageName + " attempting to redeclare permission " 13768 + perm.info.name + " already owned by " + bp.sourcePackage); 13769 res.origPermission = perm.info.name; 13770 res.origPackage = bp.sourcePackage; 13771 return; 13772 } else { 13773 Slog.w(TAG, "Package " + pkg.packageName 13774 + " attempting to redeclare system permission " 13775 + perm.info.name + "; ignoring new declaration"); 13776 pkg.permissions.remove(i); 13777 } 13778 } 13779 } 13780 } 13781 } 13782 13783 if (systemApp) { 13784 if (onExternal) { 13785 // Abort update; system app can't be replaced with app on sdcard 13786 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 13787 "Cannot install updates to system apps on sdcard"); 13788 return; 13789 } else if (ephemeral) { 13790 // Abort update; system app can't be replaced with an ephemeral app 13791 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 13792 "Cannot update a system app with an ephemeral app"); 13793 return; 13794 } 13795 } 13796 13797 if (args.move != null) { 13798 // We did an in-place move, so dex is ready to roll 13799 scanFlags |= SCAN_NO_DEX; 13800 scanFlags |= SCAN_MOVE; 13801 13802 synchronized (mPackages) { 13803 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13804 if (ps == null) { 13805 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 13806 "Missing settings for moved package " + pkgName); 13807 } 13808 13809 // We moved the entire application as-is, so bring over the 13810 // previously derived ABI information. 13811 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13812 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13813 } 13814 13815 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13816 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13817 scanFlags |= SCAN_NO_DEX; 13818 13819 try { 13820 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 13821 args.abiOverride : pkg.cpuAbiOverride); 13822 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 13823 true /* extract libs */); 13824 } catch (PackageManagerException pme) { 13825 Slog.e(TAG, "Error deriving application ABI", pme); 13826 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13827 return; 13828 } 13829 13830 13831 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 13832 // Do not run PackageDexOptimizer through the local performDexOpt 13833 // method because `pkg` is not in `mPackages` yet. 13834 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 13835 false /* useProfiles */, true /* extractOnly */); 13836 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13837 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 13838 String msg = "Extracking package failed for " + pkgName; 13839 res.setError(INSTALL_FAILED_DEXOPT, msg); 13840 return; 13841 } 13842 } 13843 13844 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13845 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13846 return; 13847 } 13848 13849 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13850 13851 if (replace) { 13852 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13853 installerPackageName, res); 13854 } else { 13855 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13856 args.user, installerPackageName, volumeUuid, res); 13857 } 13858 synchronized (mPackages) { 13859 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13860 if (ps != null) { 13861 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13862 } 13863 13864 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13865 for (int i = 0; i < childCount; i++) { 13866 PackageParser.Package childPkg = pkg.childPackages.get(i); 13867 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13868 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13869 if (childPs != null) { 13870 childRes.newUsers = childPs.queryInstalledUsers( 13871 sUserManager.getUserIds(), true); 13872 } 13873 } 13874 } 13875 } 13876 13877 private void startIntentFilterVerifications(int userId, boolean replacing, 13878 PackageParser.Package pkg) { 13879 if (mIntentFilterVerifierComponent == null) { 13880 Slog.w(TAG, "No IntentFilter verification will not be done as " 13881 + "there is no IntentFilterVerifier available!"); 13882 return; 13883 } 13884 13885 final int verifierUid = getPackageUid( 13886 mIntentFilterVerifierComponent.getPackageName(), 13887 MATCH_DEBUG_TRIAGED_MISSING, 13888 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13889 13890 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13891 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13892 mHandler.sendMessage(msg); 13893 13894 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13895 for (int i = 0; i < childCount; i++) { 13896 PackageParser.Package childPkg = pkg.childPackages.get(i); 13897 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13898 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 13899 mHandler.sendMessage(msg); 13900 } 13901 } 13902 13903 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13904 PackageParser.Package pkg) { 13905 int size = pkg.activities.size(); 13906 if (size == 0) { 13907 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13908 "No activity, so no need to verify any IntentFilter!"); 13909 return; 13910 } 13911 13912 final boolean hasDomainURLs = hasDomainURLs(pkg); 13913 if (!hasDomainURLs) { 13914 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13915 "No domain URLs, so no need to verify any IntentFilter!"); 13916 return; 13917 } 13918 13919 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13920 + " if any IntentFilter from the " + size 13921 + " Activities needs verification ..."); 13922 13923 int count = 0; 13924 final String packageName = pkg.packageName; 13925 13926 synchronized (mPackages) { 13927 // If this is a new install and we see that we've already run verification for this 13928 // package, we have nothing to do: it means the state was restored from backup. 13929 if (!replacing) { 13930 IntentFilterVerificationInfo ivi = 13931 mSettings.getIntentFilterVerificationLPr(packageName); 13932 if (ivi != null) { 13933 if (DEBUG_DOMAIN_VERIFICATION) { 13934 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13935 + ivi.getStatusString()); 13936 } 13937 return; 13938 } 13939 } 13940 13941 // If any filters need to be verified, then all need to be. 13942 boolean needToVerify = false; 13943 for (PackageParser.Activity a : pkg.activities) { 13944 for (ActivityIntentInfo filter : a.intents) { 13945 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13946 if (DEBUG_DOMAIN_VERIFICATION) { 13947 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13948 } 13949 needToVerify = true; 13950 break; 13951 } 13952 } 13953 } 13954 13955 if (needToVerify) { 13956 final int verificationId = mIntentFilterVerificationToken++; 13957 for (PackageParser.Activity a : pkg.activities) { 13958 for (ActivityIntentInfo filter : a.intents) { 13959 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13960 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13961 "Verification needed for IntentFilter:" + filter.toString()); 13962 mIntentFilterVerifier.addOneIntentFilterVerification( 13963 verifierUid, userId, verificationId, filter, packageName); 13964 count++; 13965 } 13966 } 13967 } 13968 } 13969 } 13970 13971 if (count > 0) { 13972 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13973 + " IntentFilter verification" + (count > 1 ? "s" : "") 13974 + " for userId:" + userId); 13975 mIntentFilterVerifier.startVerifications(userId); 13976 } else { 13977 if (DEBUG_DOMAIN_VERIFICATION) { 13978 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13979 } 13980 } 13981 } 13982 13983 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13984 final ComponentName cn = filter.activity.getComponentName(); 13985 final String packageName = cn.getPackageName(); 13986 13987 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13988 packageName); 13989 if (ivi == null) { 13990 return true; 13991 } 13992 int status = ivi.getStatus(); 13993 switch (status) { 13994 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13995 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13996 return true; 13997 13998 default: 13999 // Nothing to do 14000 return false; 14001 } 14002 } 14003 14004 private static boolean isMultiArch(ApplicationInfo info) { 14005 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14006 } 14007 14008 private static boolean isExternal(PackageParser.Package pkg) { 14009 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14010 } 14011 14012 private static boolean isExternal(PackageSetting ps) { 14013 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14014 } 14015 14016 private static boolean isEphemeral(PackageParser.Package pkg) { 14017 return pkg.applicationInfo.isEphemeralApp(); 14018 } 14019 14020 private static boolean isEphemeral(PackageSetting ps) { 14021 return ps.pkg != null && isEphemeral(ps.pkg); 14022 } 14023 14024 private static boolean isSystemApp(PackageParser.Package pkg) { 14025 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14026 } 14027 14028 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14029 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14030 } 14031 14032 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14033 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14034 } 14035 14036 private static boolean isSystemApp(PackageSetting ps) { 14037 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14038 } 14039 14040 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14041 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14042 } 14043 14044 private int packageFlagsToInstallFlags(PackageSetting ps) { 14045 int installFlags = 0; 14046 if (isEphemeral(ps)) { 14047 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14048 } 14049 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14050 // This existing package was an external ASEC install when we have 14051 // the external flag without a UUID 14052 installFlags |= PackageManager.INSTALL_EXTERNAL; 14053 } 14054 if (ps.isForwardLocked()) { 14055 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14056 } 14057 return installFlags; 14058 } 14059 14060 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14061 if (isExternal(pkg)) { 14062 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14063 return StorageManager.UUID_PRIMARY_PHYSICAL; 14064 } else { 14065 return pkg.volumeUuid; 14066 } 14067 } else { 14068 return StorageManager.UUID_PRIVATE_INTERNAL; 14069 } 14070 } 14071 14072 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14073 if (isExternal(pkg)) { 14074 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14075 return mSettings.getExternalVersion(); 14076 } else { 14077 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14078 } 14079 } else { 14080 return mSettings.getInternalVersion(); 14081 } 14082 } 14083 14084 private void deleteTempPackageFiles() { 14085 final FilenameFilter filter = new FilenameFilter() { 14086 public boolean accept(File dir, String name) { 14087 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14088 } 14089 }; 14090 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14091 file.delete(); 14092 } 14093 } 14094 14095 @Override 14096 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14097 int flags) { 14098 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14099 flags); 14100 } 14101 14102 @Override 14103 public void deletePackage(final String packageName, 14104 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 14105 mContext.enforceCallingOrSelfPermission( 14106 android.Manifest.permission.DELETE_PACKAGES, null); 14107 Preconditions.checkNotNull(packageName); 14108 Preconditions.checkNotNull(observer); 14109 final int uid = Binder.getCallingUid(); 14110 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 14111 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14112 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14113 mContext.enforceCallingOrSelfPermission( 14114 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14115 "deletePackage for user " + userId); 14116 } 14117 14118 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14119 try { 14120 observer.onPackageDeleted(packageName, 14121 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14122 } catch (RemoteException re) { 14123 } 14124 return; 14125 } 14126 14127 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14128 try { 14129 observer.onPackageDeleted(packageName, 14130 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14131 } catch (RemoteException re) { 14132 } 14133 return; 14134 } 14135 14136 if (DEBUG_REMOVE) { 14137 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14138 + " deleteAllUsers: " + deleteAllUsers ); 14139 } 14140 // Queue up an async operation since the package deletion may take a little while. 14141 mHandler.post(new Runnable() { 14142 public void run() { 14143 mHandler.removeCallbacks(this); 14144 int returnCode; 14145 if (!deleteAllUsers) { 14146 returnCode = deletePackageX(packageName, userId, flags); 14147 } else { 14148 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14149 // If nobody is blocking uninstall, proceed with delete for all users 14150 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14151 returnCode = deletePackageX(packageName, userId, flags); 14152 } else { 14153 // Otherwise uninstall individually for users with blockUninstalls=false 14154 final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS; 14155 for (int userId : users) { 14156 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14157 returnCode = deletePackageX(packageName, userId, userFlags); 14158 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14159 Slog.w(TAG, "Package delete failed for user " + userId 14160 + ", returnCode " + returnCode); 14161 } 14162 } 14163 } 14164 // The app has only been marked uninstalled for certain users. 14165 // We still need to report that delete was blocked 14166 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14167 } 14168 } 14169 try { 14170 observer.onPackageDeleted(packageName, returnCode, null); 14171 } catch (RemoteException e) { 14172 Log.i(TAG, "Observer no longer exists."); 14173 } //end catch 14174 } //end run 14175 }); 14176 } 14177 14178 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14179 int[] result = EMPTY_INT_ARRAY; 14180 for (int userId : userIds) { 14181 if (getBlockUninstallForUser(packageName, userId)) { 14182 result = ArrayUtils.appendInt(result, userId); 14183 } 14184 } 14185 return result; 14186 } 14187 14188 @Override 14189 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14190 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14191 } 14192 14193 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14194 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14195 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14196 try { 14197 if (dpm != null) { 14198 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14199 /* callingUserOnly =*/ false); 14200 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14201 : deviceOwnerComponentName.getPackageName(); 14202 // Does the package contains the device owner? 14203 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14204 // this check is probably not needed, since DO should be registered as a device 14205 // admin on some user too. (Original bug for this: b/17657954) 14206 if (packageName.equals(deviceOwnerPackageName)) { 14207 return true; 14208 } 14209 // Does it contain a device admin for any user? 14210 int[] users; 14211 if (userId == UserHandle.USER_ALL) { 14212 users = sUserManager.getUserIds(); 14213 } else { 14214 users = new int[]{userId}; 14215 } 14216 for (int i = 0; i < users.length; ++i) { 14217 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14218 return true; 14219 } 14220 } 14221 } 14222 } catch (RemoteException e) { 14223 } 14224 return false; 14225 } 14226 14227 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14228 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14229 } 14230 14231 /** 14232 * This method is an internal method that could be get invoked either 14233 * to delete an installed package or to clean up a failed installation. 14234 * After deleting an installed package, a broadcast is sent to notify any 14235 * listeners that the package has been installed. For cleaning up a failed 14236 * installation, the broadcast is not necessary since the package's 14237 * installation wouldn't have sent the initial broadcast either 14238 * The key steps in deleting a package are 14239 * deleting the package information in internal structures like mPackages, 14240 * deleting the packages base directories through installd 14241 * updating mSettings to reflect current status 14242 * persisting settings for later use 14243 * sending a broadcast if necessary 14244 */ 14245 private int deletePackageX(String packageName, int userId, int flags) { 14246 final PackageRemovedInfo info = new PackageRemovedInfo(); 14247 final boolean res; 14248 14249 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 14250 ? UserHandle.ALL : new UserHandle(userId); 14251 14252 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14253 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14254 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14255 } 14256 14257 PackageSetting uninstalledPs = null; 14258 14259 // for the uninstall-updates case and restricted profiles, remember the per- 14260 // user handle installed state 14261 int[] allUsers; 14262 synchronized (mPackages) { 14263 uninstalledPs = mSettings.mPackages.get(packageName); 14264 if (uninstalledPs == null) { 14265 Slog.w(TAG, "Not removing non-existent package " + packageName); 14266 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14267 } 14268 allUsers = sUserManager.getUserIds(); 14269 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14270 } 14271 14272 synchronized (mInstallLock) { 14273 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14274 res = deletePackageLI(packageName, removeForUser, true, allUsers, 14275 flags | REMOVE_CHATTY, info, true, null); 14276 synchronized (mPackages) { 14277 if (res) { 14278 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14279 } 14280 } 14281 } 14282 14283 if (res) { 14284 info.sendPackageRemovedBroadcasts(); 14285 info.sendSystemPackageUpdatedBroadcasts(); 14286 info.sendSystemPackageAppearedBroadcasts(); 14287 } 14288 // Force a gc here. 14289 Runtime.getRuntime().gc(); 14290 // Delete the resources here after sending the broadcast to let 14291 // other processes clean up before deleting resources. 14292 if (info.args != null) { 14293 synchronized (mInstallLock) { 14294 info.args.doPostDeleteLI(true); 14295 } 14296 } 14297 14298 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14299 } 14300 14301 class PackageRemovedInfo { 14302 String removedPackage; 14303 int uid = -1; 14304 int removedAppId = -1; 14305 int[] origUsers; 14306 int[] removedUsers = null; 14307 boolean isRemovedPackageSystemUpdate = false; 14308 boolean isUpdate; 14309 boolean dataRemoved; 14310 boolean removedForAllUsers; 14311 // Clean up resources deleted packages. 14312 InstallArgs args = null; 14313 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14314 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14315 14316 void sendPackageRemovedBroadcasts() { 14317 sendPackageRemovedBroadcastInternal(); 14318 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14319 for (int i = 0; i < childCount; i++) { 14320 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14321 childInfo.sendPackageRemovedBroadcastInternal(); 14322 } 14323 } 14324 14325 void sendSystemPackageUpdatedBroadcasts() { 14326 if (isRemovedPackageSystemUpdate) { 14327 sendSystemPackageUpdatedBroadcastsInternal(); 14328 final int childCount = (removedChildPackages != null) 14329 ? removedChildPackages.size() : 0; 14330 for (int i = 0; i < childCount; i++) { 14331 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14332 if (childInfo.isRemovedPackageSystemUpdate) { 14333 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 14334 } 14335 } 14336 } 14337 } 14338 14339 void sendSystemPackageAppearedBroadcasts() { 14340 final int packageCount = (appearedChildPackages != null) 14341 ? appearedChildPackages.size() : 0; 14342 for (int i = 0; i < packageCount; i++) { 14343 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 14344 for (int userId : installedInfo.newUsers) { 14345 sendPackageAddedForUser(installedInfo.name, true, 14346 UserHandle.getAppId(installedInfo.uid), userId); 14347 } 14348 } 14349 } 14350 14351 private void sendSystemPackageUpdatedBroadcastsInternal() { 14352 Bundle extras = new Bundle(2); 14353 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14354 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14355 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 14356 extras, 0, null, null, null); 14357 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 14358 extras, 0, null, null, null); 14359 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14360 null, 0, removedPackage, null, null); 14361 } 14362 14363 private void sendPackageRemovedBroadcastInternal() { 14364 Bundle extras = new Bundle(2); 14365 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14366 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 14367 if (isUpdate || isRemovedPackageSystemUpdate) { 14368 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14369 } 14370 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14371 if (removedPackage != null) { 14372 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14373 extras, 0, null, null, removedUsers); 14374 if (dataRemoved && !isRemovedPackageSystemUpdate) { 14375 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 14376 removedPackage, extras, 0, null, null, removedUsers); 14377 } 14378 } 14379 if (removedAppId >= 0) { 14380 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 14381 removedUsers); 14382 } 14383 } 14384 } 14385 14386 /* 14387 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 14388 * flag is not set, the data directory is removed as well. 14389 * make sure this flag is set for partially installed apps. If not its meaningless to 14390 * delete a partially installed application. 14391 */ 14392 private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, 14393 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 14394 String packageName = ps.name; 14395 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 14396 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 14397 // Retrieve object to delete permissions for shared user later on 14398 final PackageSetting deletedPs; 14399 // reader 14400 synchronized (mPackages) { 14401 deletedPs = mSettings.mPackages.get(packageName); 14402 if (outInfo != null) { 14403 outInfo.removedPackage = packageName; 14404 outInfo.removedUsers = deletedPs != null 14405 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 14406 : null; 14407 } 14408 } 14409 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14410 removeDataDirsLI(ps.volumeUuid, packageName); 14411 if (outInfo != null) { 14412 outInfo.dataRemoved = true; 14413 } 14414 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 14415 } 14416 // writer 14417 synchronized (mPackages) { 14418 if (deletedPs != null) { 14419 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14420 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 14421 clearDefaultBrowserIfNeeded(packageName); 14422 if (outInfo != null) { 14423 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 14424 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 14425 } 14426 updatePermissionsLPw(deletedPs.name, null, 0); 14427 if (deletedPs.sharedUser != null) { 14428 // Remove permissions associated with package. Since runtime 14429 // permissions are per user we have to kill the removed package 14430 // or packages running under the shared user of the removed 14431 // package if revoking the permissions requested only by the removed 14432 // package is successful and this causes a change in gids. 14433 for (int userId : UserManagerService.getInstance().getUserIds()) { 14434 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 14435 userId); 14436 if (userIdToKill == UserHandle.USER_ALL 14437 || userIdToKill >= UserHandle.USER_SYSTEM) { 14438 // If gids changed for this user, kill all affected packages. 14439 mHandler.post(new Runnable() { 14440 @Override 14441 public void run() { 14442 // This has to happen with no lock held. 14443 killApplication(deletedPs.name, deletedPs.appId, 14444 KILL_APP_REASON_GIDS_CHANGED); 14445 } 14446 }); 14447 break; 14448 } 14449 } 14450 } 14451 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 14452 } 14453 // make sure to preserve per-user disabled state if this removal was just 14454 // a downgrade of a system app to the factory package 14455 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 14456 if (DEBUG_REMOVE) { 14457 Slog.d(TAG, "Propagating install state across downgrade"); 14458 } 14459 for (int userId : allUserHandles) { 14460 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14461 if (DEBUG_REMOVE) { 14462 Slog.d(TAG, " user " + userId + " => " + installed); 14463 } 14464 ps.setInstalled(installed, userId); 14465 } 14466 } 14467 } 14468 // can downgrade to reader 14469 if (writeSettings) { 14470 // Save settings now 14471 mSettings.writeLPr(); 14472 } 14473 } 14474 if (outInfo != null) { 14475 // A user ID was deleted here. Go through all users and remove it 14476 // from KeyStore. 14477 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 14478 } 14479 } 14480 14481 static boolean locationIsPrivileged(File path) { 14482 try { 14483 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 14484 .getCanonicalPath(); 14485 return path.getCanonicalPath().startsWith(privilegedAppDir); 14486 } catch (IOException e) { 14487 Slog.e(TAG, "Unable to access code path " + path); 14488 } 14489 return false; 14490 } 14491 14492 /* 14493 * Tries to delete system package. 14494 */ 14495 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 14496 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 14497 boolean writeSettings) { 14498 if (deletedPs.parentPackageName != null) { 14499 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 14500 return false; 14501 } 14502 14503 final boolean applyUserRestrictions 14504 = (allUserHandles != null) && (outInfo.origUsers != null); 14505 final PackageSetting disabledPs; 14506 // Confirm if the system package has been updated 14507 // An updated system app can be deleted. This will also have to restore 14508 // the system pkg from system partition 14509 // reader 14510 synchronized (mPackages) { 14511 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 14512 } 14513 14514 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 14515 + " disabledPs=" + disabledPs); 14516 14517 if (disabledPs == null) { 14518 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 14519 return false; 14520 } else if (DEBUG_REMOVE) { 14521 Slog.d(TAG, "Deleting system pkg from data partition"); 14522 } 14523 14524 if (DEBUG_REMOVE) { 14525 if (applyUserRestrictions) { 14526 Slog.d(TAG, "Remembering install states:"); 14527 for (int userId : allUserHandles) { 14528 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 14529 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 14530 } 14531 } 14532 } 14533 14534 // Delete the updated package 14535 outInfo.isRemovedPackageSystemUpdate = true; 14536 if (outInfo.removedChildPackages != null) { 14537 final int childCount = (deletedPs.childPackageNames != null) 14538 ? deletedPs.childPackageNames.size() : 0; 14539 for (int i = 0; i < childCount; i++) { 14540 String childPackageName = deletedPs.childPackageNames.get(i); 14541 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 14542 .contains(childPackageName)) { 14543 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14544 childPackageName); 14545 if (childInfo != null) { 14546 childInfo.isRemovedPackageSystemUpdate = true; 14547 } 14548 } 14549 } 14550 } 14551 14552 if (disabledPs.versionCode < deletedPs.versionCode) { 14553 // Delete data for downgrades 14554 flags &= ~PackageManager.DELETE_KEEP_DATA; 14555 } else { 14556 // Preserve data by setting flag 14557 flags |= PackageManager.DELETE_KEEP_DATA; 14558 } 14559 14560 boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles, 14561 outInfo, writeSettings, disabledPs.pkg); 14562 if (!ret) { 14563 return false; 14564 } 14565 14566 // writer 14567 synchronized (mPackages) { 14568 // Reinstate the old system package 14569 enableSystemPackageLPw(disabledPs.pkg); 14570 // Remove any native libraries from the upgraded package. 14571 removeNativeBinariesLI(deletedPs); 14572 } 14573 14574 // Install the system package 14575 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 14576 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 14577 if (locationIsPrivileged(disabledPs.codePath)) { 14578 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 14579 } 14580 14581 final PackageParser.Package newPkg; 14582 try { 14583 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 14584 } catch (PackageManagerException e) { 14585 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 14586 + e.getMessage()); 14587 return false; 14588 } 14589 14590 prepareAppDataAfterInstall(newPkg); 14591 14592 // writer 14593 synchronized (mPackages) { 14594 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 14595 14596 // Propagate the permissions state as we do not want to drop on the floor 14597 // runtime permissions. The update permissions method below will take 14598 // care of removing obsolete permissions and grant install permissions. 14599 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 14600 updatePermissionsLPw(newPkg.packageName, newPkg, 14601 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 14602 14603 if (applyUserRestrictions) { 14604 if (DEBUG_REMOVE) { 14605 Slog.d(TAG, "Propagating install state across reinstall"); 14606 } 14607 for (int userId : allUserHandles) { 14608 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14609 if (DEBUG_REMOVE) { 14610 Slog.d(TAG, " user " + userId + " => " + installed); 14611 } 14612 ps.setInstalled(installed, userId); 14613 14614 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 14615 } 14616 // Regardless of writeSettings we need to ensure that this restriction 14617 // state propagation is persisted 14618 mSettings.writeAllUsersPackageRestrictionsLPr(); 14619 } 14620 // can downgrade to reader here 14621 if (writeSettings) { 14622 mSettings.writeLPr(); 14623 } 14624 } 14625 return true; 14626 } 14627 14628 private boolean deleteInstalledPackageLI(PackageSetting ps, 14629 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 14630 PackageRemovedInfo outInfo, boolean writeSettings, 14631 PackageParser.Package replacingPackage) { 14632 synchronized (mPackages) { 14633 if (outInfo != null) { 14634 outInfo.uid = ps.appId; 14635 } 14636 14637 if (outInfo != null && outInfo.removedChildPackages != null) { 14638 final int childCount = (ps.childPackageNames != null) 14639 ? ps.childPackageNames.size() : 0; 14640 for (int i = 0; i < childCount; i++) { 14641 String childPackageName = ps.childPackageNames.get(i); 14642 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 14643 if (childPs == null) { 14644 return false; 14645 } 14646 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14647 childPackageName); 14648 if (childInfo != null) { 14649 childInfo.uid = childPs.appId; 14650 } 14651 } 14652 } 14653 } 14654 14655 // Delete package data from internal structures and also remove data if flag is set 14656 removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings); 14657 14658 // Delete the child packages data 14659 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14660 for (int i = 0; i < childCount; i++) { 14661 PackageSetting childPs; 14662 synchronized (mPackages) { 14663 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14664 } 14665 if (childPs != null) { 14666 PackageRemovedInfo childOutInfo = (outInfo != null 14667 && outInfo.removedChildPackages != null) 14668 ? outInfo.removedChildPackages.get(childPs.name) : null; 14669 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 14670 && (replacingPackage != null 14671 && !replacingPackage.hasChildPackage(childPs.name)) 14672 ? flags & ~DELETE_KEEP_DATA : flags; 14673 removePackageDataLI(childPs, allUserHandles, childOutInfo, 14674 deleteFlags, writeSettings); 14675 } 14676 } 14677 14678 // Delete application code and resources only for parent packages 14679 if (ps.parentPackageName == null) { 14680 if (deleteCodeAndResources && (outInfo != null)) { 14681 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 14682 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 14683 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 14684 } 14685 } 14686 14687 return true; 14688 } 14689 14690 @Override 14691 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 14692 int userId) { 14693 mContext.enforceCallingOrSelfPermission( 14694 android.Manifest.permission.DELETE_PACKAGES, null); 14695 synchronized (mPackages) { 14696 PackageSetting ps = mSettings.mPackages.get(packageName); 14697 if (ps == null) { 14698 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 14699 return false; 14700 } 14701 if (!ps.getInstalled(userId)) { 14702 // Can't block uninstall for an app that is not installed or enabled. 14703 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 14704 return false; 14705 } 14706 ps.setBlockUninstall(blockUninstall, userId); 14707 mSettings.writePackageRestrictionsLPr(userId); 14708 } 14709 return true; 14710 } 14711 14712 @Override 14713 public boolean getBlockUninstallForUser(String packageName, int userId) { 14714 synchronized (mPackages) { 14715 PackageSetting ps = mSettings.mPackages.get(packageName); 14716 if (ps == null) { 14717 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 14718 return false; 14719 } 14720 return ps.getBlockUninstall(userId); 14721 } 14722 } 14723 14724 @Override 14725 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 14726 int callingUid = Binder.getCallingUid(); 14727 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 14728 throw new SecurityException( 14729 "setRequiredForSystemUser can only be run by the system or root"); 14730 } 14731 synchronized (mPackages) { 14732 PackageSetting ps = mSettings.mPackages.get(packageName); 14733 if (ps == null) { 14734 Log.w(TAG, "Package doesn't exist: " + packageName); 14735 return false; 14736 } 14737 if (systemUserApp) { 14738 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14739 } else { 14740 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14741 } 14742 mSettings.writeLPr(); 14743 } 14744 return true; 14745 } 14746 14747 /* 14748 * This method handles package deletion in general 14749 */ 14750 private boolean deletePackageLI(String packageName, UserHandle user, 14751 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 14752 PackageRemovedInfo outInfo, boolean writeSettings, 14753 PackageParser.Package replacingPackage) { 14754 if (packageName == null) { 14755 Slog.w(TAG, "Attempt to delete null packageName."); 14756 return false; 14757 } 14758 14759 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 14760 14761 PackageSetting ps; 14762 14763 synchronized (mPackages) { 14764 ps = mSettings.mPackages.get(packageName); 14765 if (ps == null) { 14766 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14767 return false; 14768 } 14769 14770 if (ps.parentPackageName != null && (!isSystemApp(ps) 14771 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 14772 if (DEBUG_REMOVE) { 14773 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 14774 + ((user == null) ? UserHandle.USER_ALL : user)); 14775 } 14776 final int removedUserId = (user != null) ? user.getIdentifier() 14777 : UserHandle.USER_ALL; 14778 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 14779 return false; 14780 } 14781 markPackageUninstalledForUserLPw(ps, user); 14782 scheduleWritePackageRestrictionsLocked(user); 14783 return true; 14784 } 14785 } 14786 14787 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 14788 && user.getIdentifier() != UserHandle.USER_ALL)) { 14789 // The caller is asking that the package only be deleted for a single 14790 // user. To do this, we just mark its uninstalled state and delete 14791 // its data. If this is a system app, we only allow this to happen if 14792 // they have set the special DELETE_SYSTEM_APP which requests different 14793 // semantics than normal for uninstalling system apps. 14794 markPackageUninstalledForUserLPw(ps, user); 14795 14796 if (!isSystemApp(ps)) { 14797 // Do not uninstall the APK if an app should be cached 14798 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 14799 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 14800 // Other user still have this package installed, so all 14801 // we need to do is clear this user's data and save that 14802 // it is uninstalled. 14803 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 14804 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14805 return false; 14806 } 14807 scheduleWritePackageRestrictionsLocked(user); 14808 return true; 14809 } else { 14810 // We need to set it back to 'installed' so the uninstall 14811 // broadcasts will be sent correctly. 14812 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 14813 ps.setInstalled(true, user.getIdentifier()); 14814 } 14815 } else { 14816 // This is a system app, so we assume that the 14817 // other users still have this package installed, so all 14818 // we need to do is clear this user's data and save that 14819 // it is uninstalled. 14820 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 14821 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14822 return false; 14823 } 14824 scheduleWritePackageRestrictionsLocked(user); 14825 return true; 14826 } 14827 } 14828 14829 // If we are deleting a composite package for all users, keep track 14830 // of result for each child. 14831 if (ps.childPackageNames != null && outInfo != null) { 14832 synchronized (mPackages) { 14833 final int childCount = ps.childPackageNames.size(); 14834 outInfo.removedChildPackages = new ArrayMap<>(childCount); 14835 for (int i = 0; i < childCount; i++) { 14836 String childPackageName = ps.childPackageNames.get(i); 14837 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 14838 childInfo.removedPackage = childPackageName; 14839 outInfo.removedChildPackages.put(childPackageName, childInfo); 14840 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 14841 if (childPs != null) { 14842 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 14843 } 14844 } 14845 } 14846 } 14847 14848 boolean ret = false; 14849 if (isSystemApp(ps)) { 14850 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 14851 // When an updated system application is deleted we delete the existing resources 14852 // as well and fall back to existing code in system partition 14853 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 14854 } else { 14855 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 14856 // Kill application pre-emptively especially for apps on sd. 14857 killApplication(packageName, ps.appId, "uninstall pkg"); 14858 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles, 14859 outInfo, writeSettings, replacingPackage); 14860 } 14861 14862 // Take a note whether we deleted the package for all users 14863 if (outInfo != null) { 14864 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14865 if (outInfo.removedChildPackages != null) { 14866 synchronized (mPackages) { 14867 final int childCount = outInfo.removedChildPackages.size(); 14868 for (int i = 0; i < childCount; i++) { 14869 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 14870 if (childInfo != null) { 14871 childInfo.removedForAllUsers = mPackages.get( 14872 childInfo.removedPackage) == null; 14873 } 14874 } 14875 } 14876 } 14877 // If we uninstalled an update to a system app there may be some 14878 // child packages that appeared as they are declared in the system 14879 // app but were not declared in the update. 14880 if (isSystemApp(ps)) { 14881 synchronized (mPackages) { 14882 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 14883 final int childCount = (updatedPs.childPackageNames != null) 14884 ? updatedPs.childPackageNames.size() : 0; 14885 for (int i = 0; i < childCount; i++) { 14886 String childPackageName = updatedPs.childPackageNames.get(i); 14887 if (outInfo.removedChildPackages == null 14888 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 14889 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 14890 if (childPs == null) { 14891 continue; 14892 } 14893 PackageInstalledInfo installRes = new PackageInstalledInfo(); 14894 installRes.name = childPackageName; 14895 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 14896 installRes.pkg = mPackages.get(childPackageName); 14897 installRes.uid = childPs.pkg.applicationInfo.uid; 14898 if (outInfo.appearedChildPackages == null) { 14899 outInfo.appearedChildPackages = new ArrayMap<>(); 14900 } 14901 outInfo.appearedChildPackages.put(childPackageName, installRes); 14902 } 14903 } 14904 } 14905 } 14906 } 14907 14908 return ret; 14909 } 14910 14911 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 14912 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 14913 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 14914 for (int nextUserId : userIds) { 14915 if (DEBUG_REMOVE) { 14916 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 14917 } 14918 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 14919 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 14920 false /*hidden*/, false /*suspended*/, null, null, null, 14921 false /*blockUninstall*/, 14922 ps.readUserState(nextUserId).domainVerificationStatus, 0); 14923 } 14924 } 14925 14926 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 14927 PackageRemovedInfo outInfo) { 14928 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 14929 : new int[] {userId}; 14930 for (int nextUserId : userIds) { 14931 if (DEBUG_REMOVE) { 14932 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 14933 + nextUserId); 14934 } 14935 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 14936 try { 14937 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 14938 } catch (InstallerException e) { 14939 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 14940 return false; 14941 } 14942 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 14943 schedulePackageCleaning(ps.name, nextUserId, false); 14944 synchronized (mPackages) { 14945 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 14946 scheduleWritePackageRestrictionsLocked(nextUserId); 14947 } 14948 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 14949 } 14950 } 14951 14952 if (outInfo != null) { 14953 outInfo.removedPackage = ps.name; 14954 outInfo.removedAppId = ps.appId; 14955 outInfo.removedUsers = userIds; 14956 } 14957 14958 return true; 14959 } 14960 14961 private final class ClearStorageConnection implements ServiceConnection { 14962 IMediaContainerService mContainerService; 14963 14964 @Override 14965 public void onServiceConnected(ComponentName name, IBinder service) { 14966 synchronized (this) { 14967 mContainerService = IMediaContainerService.Stub.asInterface(service); 14968 notifyAll(); 14969 } 14970 } 14971 14972 @Override 14973 public void onServiceDisconnected(ComponentName name) { 14974 } 14975 } 14976 14977 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 14978 final boolean mounted; 14979 if (Environment.isExternalStorageEmulated()) { 14980 mounted = true; 14981 } else { 14982 final String status = Environment.getExternalStorageState(); 14983 14984 mounted = status.equals(Environment.MEDIA_MOUNTED) 14985 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 14986 } 14987 14988 if (!mounted) { 14989 return; 14990 } 14991 14992 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 14993 int[] users; 14994 if (userId == UserHandle.USER_ALL) { 14995 users = sUserManager.getUserIds(); 14996 } else { 14997 users = new int[] { userId }; 14998 } 14999 final ClearStorageConnection conn = new ClearStorageConnection(); 15000 if (mContext.bindServiceAsUser( 15001 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15002 try { 15003 for (int curUser : users) { 15004 long timeout = SystemClock.uptimeMillis() + 5000; 15005 synchronized (conn) { 15006 long now = SystemClock.uptimeMillis(); 15007 while (conn.mContainerService == null && now < timeout) { 15008 try { 15009 conn.wait(timeout - now); 15010 } catch (InterruptedException e) { 15011 } 15012 } 15013 } 15014 if (conn.mContainerService == null) { 15015 return; 15016 } 15017 15018 final UserEnvironment userEnv = new UserEnvironment(curUser); 15019 clearDirectory(conn.mContainerService, 15020 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15021 if (allData) { 15022 clearDirectory(conn.mContainerService, 15023 userEnv.buildExternalStorageAppDataDirs(packageName)); 15024 clearDirectory(conn.mContainerService, 15025 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15026 } 15027 } 15028 } finally { 15029 mContext.unbindService(conn); 15030 } 15031 } 15032 } 15033 15034 @Override 15035 public void clearApplicationUserData(final String packageName, 15036 final IPackageDataObserver observer, final int userId) { 15037 mContext.enforceCallingOrSelfPermission( 15038 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15039 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15040 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15041 // Queue up an async operation since the package deletion may take a little while. 15042 mHandler.post(new Runnable() { 15043 public void run() { 15044 mHandler.removeCallbacks(this); 15045 final boolean succeeded; 15046 synchronized (mInstallLock) { 15047 succeeded = clearApplicationUserDataLI(packageName, userId); 15048 } 15049 clearExternalStorageDataSync(packageName, userId, true); 15050 if (succeeded) { 15051 // invoke DeviceStorageMonitor's update method to clear any notifications 15052 DeviceStorageMonitorInternal 15053 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15054 if (dsm != null) { 15055 dsm.checkMemory(); 15056 } 15057 } 15058 if(observer != null) { 15059 try { 15060 observer.onRemoveCompleted(packageName, succeeded); 15061 } catch (RemoteException e) { 15062 Log.i(TAG, "Observer no longer exists."); 15063 } 15064 } //end if observer 15065 } //end run 15066 }); 15067 } 15068 15069 private boolean clearApplicationUserDataLI(String packageName, int userId) { 15070 if (packageName == null) { 15071 Slog.w(TAG, "Attempt to delete null packageName."); 15072 return false; 15073 } 15074 15075 // Try finding details about the requested package 15076 PackageParser.Package pkg; 15077 synchronized (mPackages) { 15078 pkg = mPackages.get(packageName); 15079 if (pkg == null) { 15080 final PackageSetting ps = mSettings.mPackages.get(packageName); 15081 if (ps != null) { 15082 pkg = ps.pkg; 15083 } 15084 } 15085 15086 if (pkg == null) { 15087 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15088 return false; 15089 } 15090 15091 PackageSetting ps = (PackageSetting) pkg.mExtras; 15092 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15093 } 15094 15095 // Always delete data directories for package, even if we found no other 15096 // record of app. This helps users recover from UID mismatches without 15097 // resorting to a full data wipe. 15098 // TODO: triage flags as part of 26466827 15099 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15100 try { 15101 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 15102 } catch (InstallerException e) { 15103 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 15104 return false; 15105 } 15106 15107 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15108 removeKeystoreDataIfNeeded(userId, appId); 15109 15110 // Create a native library symlink only if we have native libraries 15111 // and if the native libraries are 32 bit libraries. We do not provide 15112 // this symlink for 64 bit libraries. 15113 if (pkg.applicationInfo.primaryCpuAbi != null && 15114 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 15115 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 15116 try { 15117 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 15118 nativeLibPath, userId); 15119 } catch (InstallerException e) { 15120 Slog.w(TAG, "Failed linking native library dir", e); 15121 return false; 15122 } 15123 } 15124 15125 return true; 15126 } 15127 15128 /** 15129 * Reverts user permission state changes (permissions and flags) in 15130 * all packages for a given user. 15131 * 15132 * @param userId The device user for which to do a reset. 15133 */ 15134 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15135 final int packageCount = mPackages.size(); 15136 for (int i = 0; i < packageCount; i++) { 15137 PackageParser.Package pkg = mPackages.valueAt(i); 15138 PackageSetting ps = (PackageSetting) pkg.mExtras; 15139 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15140 } 15141 } 15142 15143 /** 15144 * Reverts user permission state changes (permissions and flags). 15145 * 15146 * @param ps The package for which to reset. 15147 * @param userId The device user for which to do a reset. 15148 */ 15149 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15150 final PackageSetting ps, final int userId) { 15151 if (ps.pkg == null) { 15152 return; 15153 } 15154 15155 // These are flags that can change base on user actions. 15156 final int userSettableMask = FLAG_PERMISSION_USER_SET 15157 | FLAG_PERMISSION_USER_FIXED 15158 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15159 | FLAG_PERMISSION_REVIEW_REQUIRED; 15160 15161 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15162 | FLAG_PERMISSION_POLICY_FIXED; 15163 15164 boolean writeInstallPermissions = false; 15165 boolean writeRuntimePermissions = false; 15166 15167 final int permissionCount = ps.pkg.requestedPermissions.size(); 15168 for (int i = 0; i < permissionCount; i++) { 15169 String permission = ps.pkg.requestedPermissions.get(i); 15170 15171 BasePermission bp = mSettings.mPermissions.get(permission); 15172 if (bp == null) { 15173 continue; 15174 } 15175 15176 // If shared user we just reset the state to which only this app contributed. 15177 if (ps.sharedUser != null) { 15178 boolean used = false; 15179 final int packageCount = ps.sharedUser.packages.size(); 15180 for (int j = 0; j < packageCount; j++) { 15181 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15182 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15183 && pkg.pkg.requestedPermissions.contains(permission)) { 15184 used = true; 15185 break; 15186 } 15187 } 15188 if (used) { 15189 continue; 15190 } 15191 } 15192 15193 PermissionsState permissionsState = ps.getPermissionsState(); 15194 15195 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15196 15197 // Always clear the user settable flags. 15198 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15199 bp.name) != null; 15200 // If permission review is enabled and this is a legacy app, mark the 15201 // permission as requiring a review as this is the initial state. 15202 int flags = 0; 15203 if (Build.PERMISSIONS_REVIEW_REQUIRED 15204 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15205 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15206 } 15207 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15208 if (hasInstallState) { 15209 writeInstallPermissions = true; 15210 } else { 15211 writeRuntimePermissions = true; 15212 } 15213 } 15214 15215 // Below is only runtime permission handling. 15216 if (!bp.isRuntime()) { 15217 continue; 15218 } 15219 15220 // Never clobber system or policy. 15221 if ((oldFlags & policyOrSystemFlags) != 0) { 15222 continue; 15223 } 15224 15225 // If this permission was granted by default, make sure it is. 15226 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15227 if (permissionsState.grantRuntimePermission(bp, userId) 15228 != PERMISSION_OPERATION_FAILURE) { 15229 writeRuntimePermissions = true; 15230 } 15231 // If permission review is enabled the permissions for a legacy apps 15232 // are represented as constantly granted runtime ones, so don't revoke. 15233 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15234 // Otherwise, reset the permission. 15235 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15236 switch (revokeResult) { 15237 case PERMISSION_OPERATION_SUCCESS: { 15238 writeRuntimePermissions = true; 15239 } break; 15240 15241 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15242 writeRuntimePermissions = true; 15243 final int appId = ps.appId; 15244 mHandler.post(new Runnable() { 15245 @Override 15246 public void run() { 15247 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 15248 } 15249 }); 15250 } break; 15251 } 15252 } 15253 } 15254 15255 // Synchronously write as we are taking permissions away. 15256 if (writeRuntimePermissions) { 15257 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15258 } 15259 15260 // Synchronously write as we are taking permissions away. 15261 if (writeInstallPermissions) { 15262 mSettings.writeLPr(); 15263 } 15264 } 15265 15266 /** 15267 * Remove entries from the keystore daemon. Will only remove it if the 15268 * {@code appId} is valid. 15269 */ 15270 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15271 if (appId < 0) { 15272 return; 15273 } 15274 15275 final KeyStore keyStore = KeyStore.getInstance(); 15276 if (keyStore != null) { 15277 if (userId == UserHandle.USER_ALL) { 15278 for (final int individual : sUserManager.getUserIds()) { 15279 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15280 } 15281 } else { 15282 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15283 } 15284 } else { 15285 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15286 } 15287 } 15288 15289 @Override 15290 public void deleteApplicationCacheFiles(final String packageName, 15291 final IPackageDataObserver observer) { 15292 mContext.enforceCallingOrSelfPermission( 15293 android.Manifest.permission.DELETE_CACHE_FILES, null); 15294 // Queue up an async operation since the package deletion may take a little while. 15295 final int userId = UserHandle.getCallingUserId(); 15296 mHandler.post(new Runnable() { 15297 public void run() { 15298 mHandler.removeCallbacks(this); 15299 final boolean succeded; 15300 synchronized (mInstallLock) { 15301 succeded = deleteApplicationCacheFilesLI(packageName, userId); 15302 } 15303 clearExternalStorageDataSync(packageName, userId, false); 15304 if (observer != null) { 15305 try { 15306 observer.onRemoveCompleted(packageName, succeded); 15307 } catch (RemoteException e) { 15308 Log.i(TAG, "Observer no longer exists."); 15309 } 15310 } //end if observer 15311 } //end run 15312 }); 15313 } 15314 15315 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 15316 if (packageName == null) { 15317 Slog.w(TAG, "Attempt to delete null packageName."); 15318 return false; 15319 } 15320 PackageParser.Package p; 15321 synchronized (mPackages) { 15322 p = mPackages.get(packageName); 15323 } 15324 if (p == null) { 15325 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15326 return false; 15327 } 15328 final ApplicationInfo applicationInfo = p.applicationInfo; 15329 if (applicationInfo == null) { 15330 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15331 return false; 15332 } 15333 // TODO: triage flags as part of 26466827 15334 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15335 try { 15336 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 15337 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 15338 } catch (InstallerException e) { 15339 Slog.w(TAG, "Couldn't remove cache files for package " 15340 + packageName + " u" + userId, e); 15341 return false; 15342 } 15343 return true; 15344 } 15345 15346 @Override 15347 public void getPackageSizeInfo(final String packageName, int userHandle, 15348 final IPackageStatsObserver observer) { 15349 mContext.enforceCallingOrSelfPermission( 15350 android.Manifest.permission.GET_PACKAGE_SIZE, null); 15351 if (packageName == null) { 15352 throw new IllegalArgumentException("Attempt to get size of null packageName"); 15353 } 15354 15355 PackageStats stats = new PackageStats(packageName, userHandle); 15356 15357 /* 15358 * Queue up an async operation since the package measurement may take a 15359 * little while. 15360 */ 15361 Message msg = mHandler.obtainMessage(INIT_COPY); 15362 msg.obj = new MeasureParams(stats, observer); 15363 mHandler.sendMessage(msg); 15364 } 15365 15366 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 15367 PackageStats pStats) { 15368 if (packageName == null) { 15369 Slog.w(TAG, "Attempt to get size of null packageName."); 15370 return false; 15371 } 15372 PackageParser.Package p; 15373 boolean dataOnly = false; 15374 String libDirRoot = null; 15375 String asecPath = null; 15376 PackageSetting ps = null; 15377 synchronized (mPackages) { 15378 p = mPackages.get(packageName); 15379 ps = mSettings.mPackages.get(packageName); 15380 if(p == null) { 15381 dataOnly = true; 15382 if((ps == null) || (ps.pkg == null)) { 15383 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15384 return false; 15385 } 15386 p = ps.pkg; 15387 } 15388 if (ps != null) { 15389 libDirRoot = ps.legacyNativeLibraryPathString; 15390 } 15391 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 15392 final long token = Binder.clearCallingIdentity(); 15393 try { 15394 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 15395 if (secureContainerId != null) { 15396 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 15397 } 15398 } finally { 15399 Binder.restoreCallingIdentity(token); 15400 } 15401 } 15402 } 15403 String publicSrcDir = null; 15404 if(!dataOnly) { 15405 final ApplicationInfo applicationInfo = p.applicationInfo; 15406 if (applicationInfo == null) { 15407 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15408 return false; 15409 } 15410 if (p.isForwardLocked()) { 15411 publicSrcDir = applicationInfo.getBaseResourcePath(); 15412 } 15413 } 15414 // TODO: extend to measure size of split APKs 15415 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 15416 // not just the first level. 15417 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 15418 // just the primary. 15419 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 15420 15421 String apkPath; 15422 File packageDir = new File(p.codePath); 15423 15424 if (packageDir.isDirectory() && p.canHaveOatDir()) { 15425 apkPath = packageDir.getAbsolutePath(); 15426 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 15427 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 15428 libDirRoot = null; 15429 } 15430 } else { 15431 apkPath = p.baseCodePath; 15432 } 15433 15434 // TODO: triage flags as part of 26466827 15435 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15436 try { 15437 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 15438 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 15439 } catch (InstallerException e) { 15440 return false; 15441 } 15442 15443 // Fix-up for forward-locked applications in ASEC containers. 15444 if (!isExternal(p)) { 15445 pStats.codeSize += pStats.externalCodeSize; 15446 pStats.externalCodeSize = 0L; 15447 } 15448 15449 return true; 15450 } 15451 15452 15453 @Override 15454 public void addPackageToPreferred(String packageName) { 15455 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 15456 } 15457 15458 @Override 15459 public void removePackageFromPreferred(String packageName) { 15460 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 15461 } 15462 15463 @Override 15464 public List<PackageInfo> getPreferredPackages(int flags) { 15465 return new ArrayList<PackageInfo>(); 15466 } 15467 15468 private int getUidTargetSdkVersionLockedLPr(int uid) { 15469 Object obj = mSettings.getUserIdLPr(uid); 15470 if (obj instanceof SharedUserSetting) { 15471 final SharedUserSetting sus = (SharedUserSetting) obj; 15472 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 15473 final Iterator<PackageSetting> it = sus.packages.iterator(); 15474 while (it.hasNext()) { 15475 final PackageSetting ps = it.next(); 15476 if (ps.pkg != null) { 15477 int v = ps.pkg.applicationInfo.targetSdkVersion; 15478 if (v < vers) vers = v; 15479 } 15480 } 15481 return vers; 15482 } else if (obj instanceof PackageSetting) { 15483 final PackageSetting ps = (PackageSetting) obj; 15484 if (ps.pkg != null) { 15485 return ps.pkg.applicationInfo.targetSdkVersion; 15486 } 15487 } 15488 return Build.VERSION_CODES.CUR_DEVELOPMENT; 15489 } 15490 15491 @Override 15492 public void addPreferredActivity(IntentFilter filter, int match, 15493 ComponentName[] set, ComponentName activity, int userId) { 15494 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15495 "Adding preferred"); 15496 } 15497 15498 private void addPreferredActivityInternal(IntentFilter filter, int match, 15499 ComponentName[] set, ComponentName activity, boolean always, int userId, 15500 String opname) { 15501 // writer 15502 int callingUid = Binder.getCallingUid(); 15503 enforceCrossUserPermission(callingUid, userId, 15504 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 15505 if (filter.countActions() == 0) { 15506 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15507 return; 15508 } 15509 synchronized (mPackages) { 15510 if (mContext.checkCallingOrSelfPermission( 15511 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15512 != PackageManager.PERMISSION_GRANTED) { 15513 if (getUidTargetSdkVersionLockedLPr(callingUid) 15514 < Build.VERSION_CODES.FROYO) { 15515 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 15516 + callingUid); 15517 return; 15518 } 15519 mContext.enforceCallingOrSelfPermission( 15520 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15521 } 15522 15523 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 15524 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 15525 + userId + ":"); 15526 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15527 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 15528 scheduleWritePackageRestrictionsLocked(userId); 15529 } 15530 } 15531 15532 @Override 15533 public void replacePreferredActivity(IntentFilter filter, int match, 15534 ComponentName[] set, ComponentName activity, int userId) { 15535 if (filter.countActions() != 1) { 15536 throw new IllegalArgumentException( 15537 "replacePreferredActivity expects filter to have only 1 action."); 15538 } 15539 if (filter.countDataAuthorities() != 0 15540 || filter.countDataPaths() != 0 15541 || filter.countDataSchemes() > 1 15542 || filter.countDataTypes() != 0) { 15543 throw new IllegalArgumentException( 15544 "replacePreferredActivity expects filter to have no data authorities, " + 15545 "paths, or types; and at most one scheme."); 15546 } 15547 15548 final int callingUid = Binder.getCallingUid(); 15549 enforceCrossUserPermission(callingUid, userId, 15550 true /* requireFullPermission */, false /* checkShell */, 15551 "replace preferred activity"); 15552 synchronized (mPackages) { 15553 if (mContext.checkCallingOrSelfPermission( 15554 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15555 != PackageManager.PERMISSION_GRANTED) { 15556 if (getUidTargetSdkVersionLockedLPr(callingUid) 15557 < Build.VERSION_CODES.FROYO) { 15558 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 15559 + Binder.getCallingUid()); 15560 return; 15561 } 15562 mContext.enforceCallingOrSelfPermission( 15563 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15564 } 15565 15566 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15567 if (pir != null) { 15568 // Get all of the existing entries that exactly match this filter. 15569 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 15570 if (existing != null && existing.size() == 1) { 15571 PreferredActivity cur = existing.get(0); 15572 if (DEBUG_PREFERRED) { 15573 Slog.i(TAG, "Checking replace of preferred:"); 15574 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15575 if (!cur.mPref.mAlways) { 15576 Slog.i(TAG, " -- CUR; not mAlways!"); 15577 } else { 15578 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 15579 Slog.i(TAG, " -- CUR: mSet=" 15580 + Arrays.toString(cur.mPref.mSetComponents)); 15581 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 15582 Slog.i(TAG, " -- NEW: mMatch=" 15583 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 15584 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 15585 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 15586 } 15587 } 15588 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 15589 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 15590 && cur.mPref.sameSet(set)) { 15591 // Setting the preferred activity to what it happens to be already 15592 if (DEBUG_PREFERRED) { 15593 Slog.i(TAG, "Replacing with same preferred activity " 15594 + cur.mPref.mShortComponent + " for user " 15595 + userId + ":"); 15596 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15597 } 15598 return; 15599 } 15600 } 15601 15602 if (existing != null) { 15603 if (DEBUG_PREFERRED) { 15604 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 15605 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15606 } 15607 for (int i = 0; i < existing.size(); i++) { 15608 PreferredActivity pa = existing.get(i); 15609 if (DEBUG_PREFERRED) { 15610 Slog.i(TAG, "Removing existing preferred activity " 15611 + pa.mPref.mComponent + ":"); 15612 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 15613 } 15614 pir.removeFilter(pa); 15615 } 15616 } 15617 } 15618 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15619 "Replacing preferred"); 15620 } 15621 } 15622 15623 @Override 15624 public void clearPackagePreferredActivities(String packageName) { 15625 final int uid = Binder.getCallingUid(); 15626 // writer 15627 synchronized (mPackages) { 15628 PackageParser.Package pkg = mPackages.get(packageName); 15629 if (pkg == null || pkg.applicationInfo.uid != uid) { 15630 if (mContext.checkCallingOrSelfPermission( 15631 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15632 != PackageManager.PERMISSION_GRANTED) { 15633 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 15634 < Build.VERSION_CODES.FROYO) { 15635 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 15636 + Binder.getCallingUid()); 15637 return; 15638 } 15639 mContext.enforceCallingOrSelfPermission( 15640 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15641 } 15642 } 15643 15644 int user = UserHandle.getCallingUserId(); 15645 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 15646 scheduleWritePackageRestrictionsLocked(user); 15647 } 15648 } 15649 } 15650 15651 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15652 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 15653 ArrayList<PreferredActivity> removed = null; 15654 boolean changed = false; 15655 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15656 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 15657 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15658 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 15659 continue; 15660 } 15661 Iterator<PreferredActivity> it = pir.filterIterator(); 15662 while (it.hasNext()) { 15663 PreferredActivity pa = it.next(); 15664 // Mark entry for removal only if it matches the package name 15665 // and the entry is of type "always". 15666 if (packageName == null || 15667 (pa.mPref.mComponent.getPackageName().equals(packageName) 15668 && pa.mPref.mAlways)) { 15669 if (removed == null) { 15670 removed = new ArrayList<PreferredActivity>(); 15671 } 15672 removed.add(pa); 15673 } 15674 } 15675 if (removed != null) { 15676 for (int j=0; j<removed.size(); j++) { 15677 PreferredActivity pa = removed.get(j); 15678 pir.removeFilter(pa); 15679 } 15680 changed = true; 15681 } 15682 } 15683 return changed; 15684 } 15685 15686 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15687 private void clearIntentFilterVerificationsLPw(int userId) { 15688 final int packageCount = mPackages.size(); 15689 for (int i = 0; i < packageCount; i++) { 15690 PackageParser.Package pkg = mPackages.valueAt(i); 15691 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 15692 } 15693 } 15694 15695 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15696 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 15697 if (userId == UserHandle.USER_ALL) { 15698 if (mSettings.removeIntentFilterVerificationLPw(packageName, 15699 sUserManager.getUserIds())) { 15700 for (int oneUserId : sUserManager.getUserIds()) { 15701 scheduleWritePackageRestrictionsLocked(oneUserId); 15702 } 15703 } 15704 } else { 15705 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 15706 scheduleWritePackageRestrictionsLocked(userId); 15707 } 15708 } 15709 } 15710 15711 void clearDefaultBrowserIfNeeded(String packageName) { 15712 for (int oneUserId : sUserManager.getUserIds()) { 15713 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 15714 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 15715 if (packageName.equals(defaultBrowserPackageName)) { 15716 setDefaultBrowserPackageName(null, oneUserId); 15717 } 15718 } 15719 } 15720 15721 @Override 15722 public void resetApplicationPreferences(int userId) { 15723 mContext.enforceCallingOrSelfPermission( 15724 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15725 // writer 15726 synchronized (mPackages) { 15727 final long identity = Binder.clearCallingIdentity(); 15728 try { 15729 clearPackagePreferredActivitiesLPw(null, userId); 15730 mSettings.applyDefaultPreferredAppsLPw(this, userId); 15731 // TODO: We have to reset the default SMS and Phone. This requires 15732 // significant refactoring to keep all default apps in the package 15733 // manager (cleaner but more work) or have the services provide 15734 // callbacks to the package manager to request a default app reset. 15735 applyFactoryDefaultBrowserLPw(userId); 15736 clearIntentFilterVerificationsLPw(userId); 15737 primeDomainVerificationsLPw(userId); 15738 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 15739 scheduleWritePackageRestrictionsLocked(userId); 15740 } finally { 15741 Binder.restoreCallingIdentity(identity); 15742 } 15743 } 15744 } 15745 15746 @Override 15747 public int getPreferredActivities(List<IntentFilter> outFilters, 15748 List<ComponentName> outActivities, String packageName) { 15749 15750 int num = 0; 15751 final int userId = UserHandle.getCallingUserId(); 15752 // reader 15753 synchronized (mPackages) { 15754 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15755 if (pir != null) { 15756 final Iterator<PreferredActivity> it = pir.filterIterator(); 15757 while (it.hasNext()) { 15758 final PreferredActivity pa = it.next(); 15759 if (packageName == null 15760 || (pa.mPref.mComponent.getPackageName().equals(packageName) 15761 && pa.mPref.mAlways)) { 15762 if (outFilters != null) { 15763 outFilters.add(new IntentFilter(pa)); 15764 } 15765 if (outActivities != null) { 15766 outActivities.add(pa.mPref.mComponent); 15767 } 15768 } 15769 } 15770 } 15771 } 15772 15773 return num; 15774 } 15775 15776 @Override 15777 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 15778 int userId) { 15779 int callingUid = Binder.getCallingUid(); 15780 if (callingUid != Process.SYSTEM_UID) { 15781 throw new SecurityException( 15782 "addPersistentPreferredActivity can only be run by the system"); 15783 } 15784 if (filter.countActions() == 0) { 15785 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15786 return; 15787 } 15788 synchronized (mPackages) { 15789 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 15790 ":"); 15791 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15792 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 15793 new PersistentPreferredActivity(filter, activity)); 15794 scheduleWritePackageRestrictionsLocked(userId); 15795 } 15796 } 15797 15798 @Override 15799 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 15800 int callingUid = Binder.getCallingUid(); 15801 if (callingUid != Process.SYSTEM_UID) { 15802 throw new SecurityException( 15803 "clearPackagePersistentPreferredActivities can only be run by the system"); 15804 } 15805 ArrayList<PersistentPreferredActivity> removed = null; 15806 boolean changed = false; 15807 synchronized (mPackages) { 15808 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 15809 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 15810 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 15811 .valueAt(i); 15812 if (userId != thisUserId) { 15813 continue; 15814 } 15815 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 15816 while (it.hasNext()) { 15817 PersistentPreferredActivity ppa = it.next(); 15818 // Mark entry for removal only if it matches the package name. 15819 if (ppa.mComponent.getPackageName().equals(packageName)) { 15820 if (removed == null) { 15821 removed = new ArrayList<PersistentPreferredActivity>(); 15822 } 15823 removed.add(ppa); 15824 } 15825 } 15826 if (removed != null) { 15827 for (int j=0; j<removed.size(); j++) { 15828 PersistentPreferredActivity ppa = removed.get(j); 15829 ppir.removeFilter(ppa); 15830 } 15831 changed = true; 15832 } 15833 } 15834 15835 if (changed) { 15836 scheduleWritePackageRestrictionsLocked(userId); 15837 } 15838 } 15839 } 15840 15841 /** 15842 * Common machinery for picking apart a restored XML blob and passing 15843 * it to a caller-supplied functor to be applied to the running system. 15844 */ 15845 private void restoreFromXml(XmlPullParser parser, int userId, 15846 String expectedStartTag, BlobXmlRestorer functor) 15847 throws IOException, XmlPullParserException { 15848 int type; 15849 while ((type = parser.next()) != XmlPullParser.START_TAG 15850 && type != XmlPullParser.END_DOCUMENT) { 15851 } 15852 if (type != XmlPullParser.START_TAG) { 15853 // oops didn't find a start tag?! 15854 if (DEBUG_BACKUP) { 15855 Slog.e(TAG, "Didn't find start tag during restore"); 15856 } 15857 return; 15858 } 15859Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 15860 // this is supposed to be TAG_PREFERRED_BACKUP 15861 if (!expectedStartTag.equals(parser.getName())) { 15862 if (DEBUG_BACKUP) { 15863 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 15864 } 15865 return; 15866 } 15867 15868 // skip interfering stuff, then we're aligned with the backing implementation 15869 while ((type = parser.next()) == XmlPullParser.TEXT) { } 15870Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 15871 functor.apply(parser, userId); 15872 } 15873 15874 private interface BlobXmlRestorer { 15875 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 15876 } 15877 15878 /** 15879 * Non-Binder method, support for the backup/restore mechanism: write the 15880 * full set of preferred activities in its canonical XML format. Returns the 15881 * XML output as a byte array, or null if there is none. 15882 */ 15883 @Override 15884 public byte[] getPreferredActivityBackup(int userId) { 15885 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15886 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 15887 } 15888 15889 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15890 try { 15891 final XmlSerializer serializer = new FastXmlSerializer(); 15892 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15893 serializer.startDocument(null, true); 15894 serializer.startTag(null, TAG_PREFERRED_BACKUP); 15895 15896 synchronized (mPackages) { 15897 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 15898 } 15899 15900 serializer.endTag(null, TAG_PREFERRED_BACKUP); 15901 serializer.endDocument(); 15902 serializer.flush(); 15903 } catch (Exception e) { 15904 if (DEBUG_BACKUP) { 15905 Slog.e(TAG, "Unable to write preferred activities for backup", e); 15906 } 15907 return null; 15908 } 15909 15910 return dataStream.toByteArray(); 15911 } 15912 15913 @Override 15914 public void restorePreferredActivities(byte[] backup, int userId) { 15915 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15916 throw new SecurityException("Only the system may call restorePreferredActivities()"); 15917 } 15918 15919 try { 15920 final XmlPullParser parser = Xml.newPullParser(); 15921 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15922 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 15923 new BlobXmlRestorer() { 15924 @Override 15925 public void apply(XmlPullParser parser, int userId) 15926 throws XmlPullParserException, IOException { 15927 synchronized (mPackages) { 15928 mSettings.readPreferredActivitiesLPw(parser, userId); 15929 } 15930 } 15931 } ); 15932 } catch (Exception e) { 15933 if (DEBUG_BACKUP) { 15934 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15935 } 15936 } 15937 } 15938 15939 /** 15940 * Non-Binder method, support for the backup/restore mechanism: write the 15941 * default browser (etc) settings in its canonical XML format. Returns the default 15942 * browser XML representation as a byte array, or null if there is none. 15943 */ 15944 @Override 15945 public byte[] getDefaultAppsBackup(int userId) { 15946 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15947 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 15948 } 15949 15950 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15951 try { 15952 final XmlSerializer serializer = new FastXmlSerializer(); 15953 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15954 serializer.startDocument(null, true); 15955 serializer.startTag(null, TAG_DEFAULT_APPS); 15956 15957 synchronized (mPackages) { 15958 mSettings.writeDefaultAppsLPr(serializer, userId); 15959 } 15960 15961 serializer.endTag(null, TAG_DEFAULT_APPS); 15962 serializer.endDocument(); 15963 serializer.flush(); 15964 } catch (Exception e) { 15965 if (DEBUG_BACKUP) { 15966 Slog.e(TAG, "Unable to write default apps for backup", e); 15967 } 15968 return null; 15969 } 15970 15971 return dataStream.toByteArray(); 15972 } 15973 15974 @Override 15975 public void restoreDefaultApps(byte[] backup, int userId) { 15976 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15977 throw new SecurityException("Only the system may call restoreDefaultApps()"); 15978 } 15979 15980 try { 15981 final XmlPullParser parser = Xml.newPullParser(); 15982 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15983 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 15984 new BlobXmlRestorer() { 15985 @Override 15986 public void apply(XmlPullParser parser, int userId) 15987 throws XmlPullParserException, IOException { 15988 synchronized (mPackages) { 15989 mSettings.readDefaultAppsLPw(parser, userId); 15990 } 15991 } 15992 } ); 15993 } catch (Exception e) { 15994 if (DEBUG_BACKUP) { 15995 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 15996 } 15997 } 15998 } 15999 16000 @Override 16001 public byte[] getIntentFilterVerificationBackup(int userId) { 16002 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16003 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16004 } 16005 16006 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16007 try { 16008 final XmlSerializer serializer = new FastXmlSerializer(); 16009 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16010 serializer.startDocument(null, true); 16011 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16012 16013 synchronized (mPackages) { 16014 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16015 } 16016 16017 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16018 serializer.endDocument(); 16019 serializer.flush(); 16020 } catch (Exception e) { 16021 if (DEBUG_BACKUP) { 16022 Slog.e(TAG, "Unable to write default apps for backup", e); 16023 } 16024 return null; 16025 } 16026 16027 return dataStream.toByteArray(); 16028 } 16029 16030 @Override 16031 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16032 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16033 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16034 } 16035 16036 try { 16037 final XmlPullParser parser = Xml.newPullParser(); 16038 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16039 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16040 new BlobXmlRestorer() { 16041 @Override 16042 public void apply(XmlPullParser parser, int userId) 16043 throws XmlPullParserException, IOException { 16044 synchronized (mPackages) { 16045 mSettings.readAllDomainVerificationsLPr(parser, userId); 16046 mSettings.writeLPr(); 16047 } 16048 } 16049 } ); 16050 } catch (Exception e) { 16051 if (DEBUG_BACKUP) { 16052 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16053 } 16054 } 16055 } 16056 16057 @Override 16058 public byte[] getPermissionGrantBackup(int userId) { 16059 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16060 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16061 } 16062 16063 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16064 try { 16065 final XmlSerializer serializer = new FastXmlSerializer(); 16066 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16067 serializer.startDocument(null, true); 16068 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16069 16070 synchronized (mPackages) { 16071 serializeRuntimePermissionGrantsLPr(serializer, userId); 16072 } 16073 16074 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16075 serializer.endDocument(); 16076 serializer.flush(); 16077 } catch (Exception e) { 16078 if (DEBUG_BACKUP) { 16079 Slog.e(TAG, "Unable to write default apps for backup", e); 16080 } 16081 return null; 16082 } 16083 16084 return dataStream.toByteArray(); 16085 } 16086 16087 @Override 16088 public void restorePermissionGrants(byte[] backup, int userId) { 16089 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16090 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16091 } 16092 16093 try { 16094 final XmlPullParser parser = Xml.newPullParser(); 16095 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16096 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16097 new BlobXmlRestorer() { 16098 @Override 16099 public void apply(XmlPullParser parser, int userId) 16100 throws XmlPullParserException, IOException { 16101 synchronized (mPackages) { 16102 processRestoredPermissionGrantsLPr(parser, userId); 16103 } 16104 } 16105 } ); 16106 } catch (Exception e) { 16107 if (DEBUG_BACKUP) { 16108 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16109 } 16110 } 16111 } 16112 16113 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16114 throws IOException { 16115 serializer.startTag(null, TAG_ALL_GRANTS); 16116 16117 final int N = mSettings.mPackages.size(); 16118 for (int i = 0; i < N; i++) { 16119 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16120 boolean pkgGrantsKnown = false; 16121 16122 PermissionsState packagePerms = ps.getPermissionsState(); 16123 16124 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16125 final int grantFlags = state.getFlags(); 16126 // only look at grants that are not system/policy fixed 16127 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16128 final boolean isGranted = state.isGranted(); 16129 // And only back up the user-twiddled state bits 16130 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16131 final String packageName = mSettings.mPackages.keyAt(i); 16132 if (!pkgGrantsKnown) { 16133 serializer.startTag(null, TAG_GRANT); 16134 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16135 pkgGrantsKnown = true; 16136 } 16137 16138 final boolean userSet = 16139 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16140 final boolean userFixed = 16141 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16142 final boolean revoke = 16143 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16144 16145 serializer.startTag(null, TAG_PERMISSION); 16146 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16147 if (isGranted) { 16148 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16149 } 16150 if (userSet) { 16151 serializer.attribute(null, ATTR_USER_SET, "true"); 16152 } 16153 if (userFixed) { 16154 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16155 } 16156 if (revoke) { 16157 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16158 } 16159 serializer.endTag(null, TAG_PERMISSION); 16160 } 16161 } 16162 } 16163 16164 if (pkgGrantsKnown) { 16165 serializer.endTag(null, TAG_GRANT); 16166 } 16167 } 16168 16169 serializer.endTag(null, TAG_ALL_GRANTS); 16170 } 16171 16172 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16173 throws XmlPullParserException, IOException { 16174 String pkgName = null; 16175 int outerDepth = parser.getDepth(); 16176 int type; 16177 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16178 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16179 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16180 continue; 16181 } 16182 16183 final String tagName = parser.getName(); 16184 if (tagName.equals(TAG_GRANT)) { 16185 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16186 if (DEBUG_BACKUP) { 16187 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16188 } 16189 } else if (tagName.equals(TAG_PERMISSION)) { 16190 16191 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16192 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16193 16194 int newFlagSet = 0; 16195 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16196 newFlagSet |= FLAG_PERMISSION_USER_SET; 16197 } 16198 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16199 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16200 } 16201 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16202 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16203 } 16204 if (DEBUG_BACKUP) { 16205 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16206 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16207 } 16208 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16209 if (ps != null) { 16210 // Already installed so we apply the grant immediately 16211 if (DEBUG_BACKUP) { 16212 Slog.v(TAG, " + already installed; applying"); 16213 } 16214 PermissionsState perms = ps.getPermissionsState(); 16215 BasePermission bp = mSettings.mPermissions.get(permName); 16216 if (bp != null) { 16217 if (isGranted) { 16218 perms.grantRuntimePermission(bp, userId); 16219 } 16220 if (newFlagSet != 0) { 16221 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16222 } 16223 } 16224 } else { 16225 // Need to wait for post-restore install to apply the grant 16226 if (DEBUG_BACKUP) { 16227 Slog.v(TAG, " - not yet installed; saving for later"); 16228 } 16229 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16230 isGranted, newFlagSet, userId); 16231 } 16232 } else { 16233 PackageManagerService.reportSettingsProblem(Log.WARN, 16234 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16235 XmlUtils.skipCurrentTag(parser); 16236 } 16237 } 16238 16239 scheduleWriteSettingsLocked(); 16240 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16241 } 16242 16243 @Override 16244 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16245 int sourceUserId, int targetUserId, int flags) { 16246 mContext.enforceCallingOrSelfPermission( 16247 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16248 int callingUid = Binder.getCallingUid(); 16249 enforceOwnerRights(ownerPackage, callingUid); 16250 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16251 if (intentFilter.countActions() == 0) { 16252 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16253 return; 16254 } 16255 synchronized (mPackages) { 16256 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16257 ownerPackage, targetUserId, flags); 16258 CrossProfileIntentResolver resolver = 16259 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16260 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16261 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16262 if (existing != null) { 16263 int size = existing.size(); 16264 for (int i = 0; i < size; i++) { 16265 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16266 return; 16267 } 16268 } 16269 } 16270 resolver.addFilter(newFilter); 16271 scheduleWritePackageRestrictionsLocked(sourceUserId); 16272 } 16273 } 16274 16275 @Override 16276 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16277 mContext.enforceCallingOrSelfPermission( 16278 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16279 int callingUid = Binder.getCallingUid(); 16280 enforceOwnerRights(ownerPackage, callingUid); 16281 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16282 synchronized (mPackages) { 16283 CrossProfileIntentResolver resolver = 16284 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16285 ArraySet<CrossProfileIntentFilter> set = 16286 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16287 for (CrossProfileIntentFilter filter : set) { 16288 if (filter.getOwnerPackage().equals(ownerPackage)) { 16289 resolver.removeFilter(filter); 16290 } 16291 } 16292 scheduleWritePackageRestrictionsLocked(sourceUserId); 16293 } 16294 } 16295 16296 // Enforcing that callingUid is owning pkg on userId 16297 private void enforceOwnerRights(String pkg, int callingUid) { 16298 // The system owns everything. 16299 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16300 return; 16301 } 16302 int callingUserId = UserHandle.getUserId(callingUid); 16303 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16304 if (pi == null) { 16305 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16306 + callingUserId); 16307 } 16308 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16309 throw new SecurityException("Calling uid " + callingUid 16310 + " does not own package " + pkg); 16311 } 16312 } 16313 16314 @Override 16315 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16316 Intent intent = new Intent(Intent.ACTION_MAIN); 16317 intent.addCategory(Intent.CATEGORY_HOME); 16318 16319 final int callingUserId = UserHandle.getCallingUserId(); 16320 List<ResolveInfo> list = queryIntentActivities(intent, null, 16321 PackageManager.GET_META_DATA, callingUserId); 16322 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16323 true, false, false, callingUserId); 16324 16325 allHomeCandidates.clear(); 16326 if (list != null) { 16327 for (ResolveInfo ri : list) { 16328 allHomeCandidates.add(ri); 16329 } 16330 } 16331 return (preferred == null || preferred.activityInfo == null) 16332 ? null 16333 : new ComponentName(preferred.activityInfo.packageName, 16334 preferred.activityInfo.name); 16335 } 16336 16337 @Override 16338 public void setApplicationEnabledSetting(String appPackageName, 16339 int newState, int flags, int userId, String callingPackage) { 16340 if (!sUserManager.exists(userId)) return; 16341 if (callingPackage == null) { 16342 callingPackage = Integer.toString(Binder.getCallingUid()); 16343 } 16344 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 16345 } 16346 16347 @Override 16348 public void setComponentEnabledSetting(ComponentName componentName, 16349 int newState, int flags, int userId) { 16350 if (!sUserManager.exists(userId)) return; 16351 setEnabledSetting(componentName.getPackageName(), 16352 componentName.getClassName(), newState, flags, userId, null); 16353 } 16354 16355 private void setEnabledSetting(final String packageName, String className, int newState, 16356 final int flags, int userId, String callingPackage) { 16357 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 16358 || newState == COMPONENT_ENABLED_STATE_ENABLED 16359 || newState == COMPONENT_ENABLED_STATE_DISABLED 16360 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 16361 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 16362 throw new IllegalArgumentException("Invalid new component state: " 16363 + newState); 16364 } 16365 PackageSetting pkgSetting; 16366 final int uid = Binder.getCallingUid(); 16367 final int permission = mContext.checkCallingOrSelfPermission( 16368 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16369 enforceCrossUserPermission(uid, userId, 16370 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 16371 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16372 boolean sendNow = false; 16373 boolean isApp = (className == null); 16374 String componentName = isApp ? packageName : className; 16375 int packageUid = -1; 16376 ArrayList<String> components; 16377 16378 // writer 16379 synchronized (mPackages) { 16380 pkgSetting = mSettings.mPackages.get(packageName); 16381 if (pkgSetting == null) { 16382 if (className == null) { 16383 throw new IllegalArgumentException("Unknown package: " + packageName); 16384 } 16385 throw new IllegalArgumentException( 16386 "Unknown component: " + packageName + "/" + className); 16387 } 16388 // Allow root and verify that userId is not being specified by a different user 16389 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 16390 throw new SecurityException( 16391 "Permission Denial: attempt to change component state from pid=" 16392 + Binder.getCallingPid() 16393 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 16394 } 16395 if (className == null) { 16396 // We're dealing with an application/package level state change 16397 if (pkgSetting.getEnabled(userId) == newState) { 16398 // Nothing to do 16399 return; 16400 } 16401 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 16402 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 16403 // Don't care about who enables an app. 16404 callingPackage = null; 16405 } 16406 pkgSetting.setEnabled(newState, userId, callingPackage); 16407 // pkgSetting.pkg.mSetEnabled = newState; 16408 } else { 16409 // We're dealing with a component level state change 16410 // First, verify that this is a valid class name. 16411 PackageParser.Package pkg = pkgSetting.pkg; 16412 if (pkg == null || !pkg.hasComponentClassName(className)) { 16413 if (pkg != null && 16414 pkg.applicationInfo.targetSdkVersion >= 16415 Build.VERSION_CODES.JELLY_BEAN) { 16416 throw new IllegalArgumentException("Component class " + className 16417 + " does not exist in " + packageName); 16418 } else { 16419 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 16420 + className + " does not exist in " + packageName); 16421 } 16422 } 16423 switch (newState) { 16424 case COMPONENT_ENABLED_STATE_ENABLED: 16425 if (!pkgSetting.enableComponentLPw(className, userId)) { 16426 return; 16427 } 16428 break; 16429 case COMPONENT_ENABLED_STATE_DISABLED: 16430 if (!pkgSetting.disableComponentLPw(className, userId)) { 16431 return; 16432 } 16433 break; 16434 case COMPONENT_ENABLED_STATE_DEFAULT: 16435 if (!pkgSetting.restoreComponentLPw(className, userId)) { 16436 return; 16437 } 16438 break; 16439 default: 16440 Slog.e(TAG, "Invalid new component state: " + newState); 16441 return; 16442 } 16443 } 16444 scheduleWritePackageRestrictionsLocked(userId); 16445 components = mPendingBroadcasts.get(userId, packageName); 16446 final boolean newPackage = components == null; 16447 if (newPackage) { 16448 components = new ArrayList<String>(); 16449 } 16450 if (!components.contains(componentName)) { 16451 components.add(componentName); 16452 } 16453 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 16454 sendNow = true; 16455 // Purge entry from pending broadcast list if another one exists already 16456 // since we are sending one right away. 16457 mPendingBroadcasts.remove(userId, packageName); 16458 } else { 16459 if (newPackage) { 16460 mPendingBroadcasts.put(userId, packageName, components); 16461 } 16462 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 16463 // Schedule a message 16464 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 16465 } 16466 } 16467 } 16468 16469 long callingId = Binder.clearCallingIdentity(); 16470 try { 16471 if (sendNow) { 16472 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 16473 sendPackageChangedBroadcast(packageName, 16474 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 16475 } 16476 } finally { 16477 Binder.restoreCallingIdentity(callingId); 16478 } 16479 } 16480 16481 private void sendPackageChangedBroadcast(String packageName, 16482 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 16483 if (DEBUG_INSTALL) 16484 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 16485 + componentNames); 16486 Bundle extras = new Bundle(4); 16487 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 16488 String nameList[] = new String[componentNames.size()]; 16489 componentNames.toArray(nameList); 16490 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 16491 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 16492 extras.putInt(Intent.EXTRA_UID, packageUid); 16493 // If this is not reporting a change of the overall package, then only send it 16494 // to registered receivers. We don't want to launch a swath of apps for every 16495 // little component state change. 16496 final int flags = !componentNames.contains(packageName) 16497 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 16498 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 16499 new int[] {UserHandle.getUserId(packageUid)}); 16500 } 16501 16502 @Override 16503 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 16504 if (!sUserManager.exists(userId)) return; 16505 final int uid = Binder.getCallingUid(); 16506 final int permission = mContext.checkCallingOrSelfPermission( 16507 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16508 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16509 enforceCrossUserPermission(uid, userId, 16510 true /* requireFullPermission */, true /* checkShell */, "stop package"); 16511 // writer 16512 synchronized (mPackages) { 16513 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 16514 allowedByPermission, uid, userId)) { 16515 scheduleWritePackageRestrictionsLocked(userId); 16516 } 16517 } 16518 } 16519 16520 @Override 16521 public String getInstallerPackageName(String packageName) { 16522 // reader 16523 synchronized (mPackages) { 16524 return mSettings.getInstallerPackageNameLPr(packageName); 16525 } 16526 } 16527 16528 @Override 16529 public int getApplicationEnabledSetting(String packageName, int userId) { 16530 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16531 int uid = Binder.getCallingUid(); 16532 enforceCrossUserPermission(uid, userId, 16533 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 16534 // reader 16535 synchronized (mPackages) { 16536 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 16537 } 16538 } 16539 16540 @Override 16541 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 16542 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16543 int uid = Binder.getCallingUid(); 16544 enforceCrossUserPermission(uid, userId, 16545 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 16546 // reader 16547 synchronized (mPackages) { 16548 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 16549 } 16550 } 16551 16552 @Override 16553 public void enterSafeMode() { 16554 enforceSystemOrRoot("Only the system can request entering safe mode"); 16555 16556 if (!mSystemReady) { 16557 mSafeMode = true; 16558 } 16559 } 16560 16561 @Override 16562 public void systemReady() { 16563 mSystemReady = true; 16564 16565 // Read the compatibilty setting when the system is ready. 16566 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 16567 mContext.getContentResolver(), 16568 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 16569 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 16570 if (DEBUG_SETTINGS) { 16571 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 16572 } 16573 16574 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 16575 16576 synchronized (mPackages) { 16577 // Verify that all of the preferred activity components actually 16578 // exist. It is possible for applications to be updated and at 16579 // that point remove a previously declared activity component that 16580 // had been set as a preferred activity. We try to clean this up 16581 // the next time we encounter that preferred activity, but it is 16582 // possible for the user flow to never be able to return to that 16583 // situation so here we do a sanity check to make sure we haven't 16584 // left any junk around. 16585 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 16586 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16587 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16588 removed.clear(); 16589 for (PreferredActivity pa : pir.filterSet()) { 16590 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 16591 removed.add(pa); 16592 } 16593 } 16594 if (removed.size() > 0) { 16595 for (int r=0; r<removed.size(); r++) { 16596 PreferredActivity pa = removed.get(r); 16597 Slog.w(TAG, "Removing dangling preferred activity: " 16598 + pa.mPref.mComponent); 16599 pir.removeFilter(pa); 16600 } 16601 mSettings.writePackageRestrictionsLPr( 16602 mSettings.mPreferredActivities.keyAt(i)); 16603 } 16604 } 16605 16606 for (int userId : UserManagerService.getInstance().getUserIds()) { 16607 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 16608 grantPermissionsUserIds = ArrayUtils.appendInt( 16609 grantPermissionsUserIds, userId); 16610 } 16611 } 16612 } 16613 sUserManager.systemReady(); 16614 16615 // If we upgraded grant all default permissions before kicking off. 16616 for (int userId : grantPermissionsUserIds) { 16617 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 16618 } 16619 16620 // Kick off any messages waiting for system ready 16621 if (mPostSystemReadyMessages != null) { 16622 for (Message msg : mPostSystemReadyMessages) { 16623 msg.sendToTarget(); 16624 } 16625 mPostSystemReadyMessages = null; 16626 } 16627 16628 // Watch for external volumes that come and go over time 16629 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16630 storage.registerListener(mStorageListener); 16631 16632 mInstallerService.systemReady(); 16633 mPackageDexOptimizer.systemReady(); 16634 16635 MountServiceInternal mountServiceInternal = LocalServices.getService( 16636 MountServiceInternal.class); 16637 mountServiceInternal.addExternalStoragePolicy( 16638 new MountServiceInternal.ExternalStorageMountPolicy() { 16639 @Override 16640 public int getMountMode(int uid, String packageName) { 16641 if (Process.isIsolated(uid)) { 16642 return Zygote.MOUNT_EXTERNAL_NONE; 16643 } 16644 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 16645 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16646 } 16647 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16648 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16649 } 16650 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16651 return Zygote.MOUNT_EXTERNAL_READ; 16652 } 16653 return Zygote.MOUNT_EXTERNAL_WRITE; 16654 } 16655 16656 @Override 16657 public boolean hasExternalStorage(int uid, String packageName) { 16658 return true; 16659 } 16660 }); 16661 } 16662 16663 @Override 16664 public boolean isSafeMode() { 16665 return mSafeMode; 16666 } 16667 16668 @Override 16669 public boolean hasSystemUidErrors() { 16670 return mHasSystemUidErrors; 16671 } 16672 16673 static String arrayToString(int[] array) { 16674 StringBuffer buf = new StringBuffer(128); 16675 buf.append('['); 16676 if (array != null) { 16677 for (int i=0; i<array.length; i++) { 16678 if (i > 0) buf.append(", "); 16679 buf.append(array[i]); 16680 } 16681 } 16682 buf.append(']'); 16683 return buf.toString(); 16684 } 16685 16686 static class DumpState { 16687 public static final int DUMP_LIBS = 1 << 0; 16688 public static final int DUMP_FEATURES = 1 << 1; 16689 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 16690 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 16691 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 16692 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 16693 public static final int DUMP_PERMISSIONS = 1 << 6; 16694 public static final int DUMP_PACKAGES = 1 << 7; 16695 public static final int DUMP_SHARED_USERS = 1 << 8; 16696 public static final int DUMP_MESSAGES = 1 << 9; 16697 public static final int DUMP_PROVIDERS = 1 << 10; 16698 public static final int DUMP_VERIFIERS = 1 << 11; 16699 public static final int DUMP_PREFERRED = 1 << 12; 16700 public static final int DUMP_PREFERRED_XML = 1 << 13; 16701 public static final int DUMP_KEYSETS = 1 << 14; 16702 public static final int DUMP_VERSION = 1 << 15; 16703 public static final int DUMP_INSTALLS = 1 << 16; 16704 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 16705 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 16706 16707 public static final int OPTION_SHOW_FILTERS = 1 << 0; 16708 16709 private int mTypes; 16710 16711 private int mOptions; 16712 16713 private boolean mTitlePrinted; 16714 16715 private SharedUserSetting mSharedUser; 16716 16717 public boolean isDumping(int type) { 16718 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 16719 return true; 16720 } 16721 16722 return (mTypes & type) != 0; 16723 } 16724 16725 public void setDump(int type) { 16726 mTypes |= type; 16727 } 16728 16729 public boolean isOptionEnabled(int option) { 16730 return (mOptions & option) != 0; 16731 } 16732 16733 public void setOptionEnabled(int option) { 16734 mOptions |= option; 16735 } 16736 16737 public boolean onTitlePrinted() { 16738 final boolean printed = mTitlePrinted; 16739 mTitlePrinted = true; 16740 return printed; 16741 } 16742 16743 public boolean getTitlePrinted() { 16744 return mTitlePrinted; 16745 } 16746 16747 public void setTitlePrinted(boolean enabled) { 16748 mTitlePrinted = enabled; 16749 } 16750 16751 public SharedUserSetting getSharedUser() { 16752 return mSharedUser; 16753 } 16754 16755 public void setSharedUser(SharedUserSetting user) { 16756 mSharedUser = user; 16757 } 16758 } 16759 16760 @Override 16761 public void onShellCommand(FileDescriptor in, FileDescriptor out, 16762 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 16763 (new PackageManagerShellCommand(this)).exec( 16764 this, in, out, err, args, resultReceiver); 16765 } 16766 16767 @Override 16768 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 16769 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 16770 != PackageManager.PERMISSION_GRANTED) { 16771 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 16772 + Binder.getCallingPid() 16773 + ", uid=" + Binder.getCallingUid() 16774 + " without permission " 16775 + android.Manifest.permission.DUMP); 16776 return; 16777 } 16778 16779 DumpState dumpState = new DumpState(); 16780 boolean fullPreferred = false; 16781 boolean checkin = false; 16782 16783 String packageName = null; 16784 ArraySet<String> permissionNames = null; 16785 16786 int opti = 0; 16787 while (opti < args.length) { 16788 String opt = args[opti]; 16789 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 16790 break; 16791 } 16792 opti++; 16793 16794 if ("-a".equals(opt)) { 16795 // Right now we only know how to print all. 16796 } else if ("-h".equals(opt)) { 16797 pw.println("Package manager dump options:"); 16798 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 16799 pw.println(" --checkin: dump for a checkin"); 16800 pw.println(" -f: print details of intent filters"); 16801 pw.println(" -h: print this help"); 16802 pw.println(" cmd may be one of:"); 16803 pw.println(" l[ibraries]: list known shared libraries"); 16804 pw.println(" f[eatures]: list device features"); 16805 pw.println(" k[eysets]: print known keysets"); 16806 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 16807 pw.println(" perm[issions]: dump permissions"); 16808 pw.println(" permission [name ...]: dump declaration and use of given permission"); 16809 pw.println(" pref[erred]: print preferred package settings"); 16810 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 16811 pw.println(" prov[iders]: dump content providers"); 16812 pw.println(" p[ackages]: dump installed packages"); 16813 pw.println(" s[hared-users]: dump shared user IDs"); 16814 pw.println(" m[essages]: print collected runtime messages"); 16815 pw.println(" v[erifiers]: print package verifier info"); 16816 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 16817 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 16818 pw.println(" version: print database version info"); 16819 pw.println(" write: write current settings now"); 16820 pw.println(" installs: details about install sessions"); 16821 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 16822 pw.println(" <package.name>: info about given package"); 16823 return; 16824 } else if ("--checkin".equals(opt)) { 16825 checkin = true; 16826 } else if ("-f".equals(opt)) { 16827 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16828 } else { 16829 pw.println("Unknown argument: " + opt + "; use -h for help"); 16830 } 16831 } 16832 16833 // Is the caller requesting to dump a particular piece of data? 16834 if (opti < args.length) { 16835 String cmd = args[opti]; 16836 opti++; 16837 // Is this a package name? 16838 if ("android".equals(cmd) || cmd.contains(".")) { 16839 packageName = cmd; 16840 // When dumping a single package, we always dump all of its 16841 // filter information since the amount of data will be reasonable. 16842 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16843 } else if ("check-permission".equals(cmd)) { 16844 if (opti >= args.length) { 16845 pw.println("Error: check-permission missing permission argument"); 16846 return; 16847 } 16848 String perm = args[opti]; 16849 opti++; 16850 if (opti >= args.length) { 16851 pw.println("Error: check-permission missing package argument"); 16852 return; 16853 } 16854 String pkg = args[opti]; 16855 opti++; 16856 int user = UserHandle.getUserId(Binder.getCallingUid()); 16857 if (opti < args.length) { 16858 try { 16859 user = Integer.parseInt(args[opti]); 16860 } catch (NumberFormatException e) { 16861 pw.println("Error: check-permission user argument is not a number: " 16862 + args[opti]); 16863 return; 16864 } 16865 } 16866 pw.println(checkPermission(perm, pkg, user)); 16867 return; 16868 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 16869 dumpState.setDump(DumpState.DUMP_LIBS); 16870 } else if ("f".equals(cmd) || "features".equals(cmd)) { 16871 dumpState.setDump(DumpState.DUMP_FEATURES); 16872 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 16873 if (opti >= args.length) { 16874 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 16875 | DumpState.DUMP_SERVICE_RESOLVERS 16876 | DumpState.DUMP_RECEIVER_RESOLVERS 16877 | DumpState.DUMP_CONTENT_RESOLVERS); 16878 } else { 16879 while (opti < args.length) { 16880 String name = args[opti]; 16881 if ("a".equals(name) || "activity".equals(name)) { 16882 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 16883 } else if ("s".equals(name) || "service".equals(name)) { 16884 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 16885 } else if ("r".equals(name) || "receiver".equals(name)) { 16886 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 16887 } else if ("c".equals(name) || "content".equals(name)) { 16888 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 16889 } else { 16890 pw.println("Error: unknown resolver table type: " + name); 16891 return; 16892 } 16893 opti++; 16894 } 16895 } 16896 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 16897 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 16898 } else if ("permission".equals(cmd)) { 16899 if (opti >= args.length) { 16900 pw.println("Error: permission requires permission name"); 16901 return; 16902 } 16903 permissionNames = new ArraySet<>(); 16904 while (opti < args.length) { 16905 permissionNames.add(args[opti]); 16906 opti++; 16907 } 16908 dumpState.setDump(DumpState.DUMP_PERMISSIONS 16909 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 16910 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 16911 dumpState.setDump(DumpState.DUMP_PREFERRED); 16912 } else if ("preferred-xml".equals(cmd)) { 16913 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 16914 if (opti < args.length && "--full".equals(args[opti])) { 16915 fullPreferred = true; 16916 opti++; 16917 } 16918 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 16919 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 16920 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 16921 dumpState.setDump(DumpState.DUMP_PACKAGES); 16922 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 16923 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 16924 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 16925 dumpState.setDump(DumpState.DUMP_PROVIDERS); 16926 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 16927 dumpState.setDump(DumpState.DUMP_MESSAGES); 16928 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 16929 dumpState.setDump(DumpState.DUMP_VERIFIERS); 16930 } else if ("i".equals(cmd) || "ifv".equals(cmd) 16931 || "intent-filter-verifiers".equals(cmd)) { 16932 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 16933 } else if ("version".equals(cmd)) { 16934 dumpState.setDump(DumpState.DUMP_VERSION); 16935 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 16936 dumpState.setDump(DumpState.DUMP_KEYSETS); 16937 } else if ("installs".equals(cmd)) { 16938 dumpState.setDump(DumpState.DUMP_INSTALLS); 16939 } else if ("write".equals(cmd)) { 16940 synchronized (mPackages) { 16941 mSettings.writeLPr(); 16942 pw.println("Settings written."); 16943 return; 16944 } 16945 } 16946 } 16947 16948 if (checkin) { 16949 pw.println("vers,1"); 16950 } 16951 16952 // reader 16953 synchronized (mPackages) { 16954 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 16955 if (!checkin) { 16956 if (dumpState.onTitlePrinted()) 16957 pw.println(); 16958 pw.println("Database versions:"); 16959 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 16960 } 16961 } 16962 16963 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 16964 if (!checkin) { 16965 if (dumpState.onTitlePrinted()) 16966 pw.println(); 16967 pw.println("Verifiers:"); 16968 pw.print(" Required: "); 16969 pw.print(mRequiredVerifierPackage); 16970 pw.print(" (uid="); 16971 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 16972 UserHandle.USER_SYSTEM)); 16973 pw.println(")"); 16974 } else if (mRequiredVerifierPackage != null) { 16975 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 16976 pw.print(","); 16977 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 16978 UserHandle.USER_SYSTEM)); 16979 } 16980 } 16981 16982 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 16983 packageName == null) { 16984 if (mIntentFilterVerifierComponent != null) { 16985 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 16986 if (!checkin) { 16987 if (dumpState.onTitlePrinted()) 16988 pw.println(); 16989 pw.println("Intent Filter Verifier:"); 16990 pw.print(" Using: "); 16991 pw.print(verifierPackageName); 16992 pw.print(" (uid="); 16993 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 16994 UserHandle.USER_SYSTEM)); 16995 pw.println(")"); 16996 } else if (verifierPackageName != null) { 16997 pw.print("ifv,"); pw.print(verifierPackageName); 16998 pw.print(","); 16999 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17000 UserHandle.USER_SYSTEM)); 17001 } 17002 } else { 17003 pw.println(); 17004 pw.println("No Intent Filter Verifier available!"); 17005 } 17006 } 17007 17008 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17009 boolean printedHeader = false; 17010 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17011 while (it.hasNext()) { 17012 String name = it.next(); 17013 SharedLibraryEntry ent = mSharedLibraries.get(name); 17014 if (!checkin) { 17015 if (!printedHeader) { 17016 if (dumpState.onTitlePrinted()) 17017 pw.println(); 17018 pw.println("Libraries:"); 17019 printedHeader = true; 17020 } 17021 pw.print(" "); 17022 } else { 17023 pw.print("lib,"); 17024 } 17025 pw.print(name); 17026 if (!checkin) { 17027 pw.print(" -> "); 17028 } 17029 if (ent.path != null) { 17030 if (!checkin) { 17031 pw.print("(jar) "); 17032 pw.print(ent.path); 17033 } else { 17034 pw.print(",jar,"); 17035 pw.print(ent.path); 17036 } 17037 } else { 17038 if (!checkin) { 17039 pw.print("(apk) "); 17040 pw.print(ent.apk); 17041 } else { 17042 pw.print(",apk,"); 17043 pw.print(ent.apk); 17044 } 17045 } 17046 pw.println(); 17047 } 17048 } 17049 17050 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17051 if (dumpState.onTitlePrinted()) 17052 pw.println(); 17053 if (!checkin) { 17054 pw.println("Features:"); 17055 } 17056 17057 for (FeatureInfo feat : mAvailableFeatures.values()) { 17058 if (checkin) { 17059 pw.print("feat,"); 17060 pw.print(feat.name); 17061 pw.print(","); 17062 pw.println(feat.version); 17063 } else { 17064 pw.print(" "); 17065 pw.print(feat.name); 17066 if (feat.version > 0) { 17067 pw.print(" version="); 17068 pw.print(feat.version); 17069 } 17070 pw.println(); 17071 } 17072 } 17073 } 17074 17075 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17076 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17077 : "Activity Resolver Table:", " ", packageName, 17078 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17079 dumpState.setTitlePrinted(true); 17080 } 17081 } 17082 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17083 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17084 : "Receiver Resolver Table:", " ", packageName, 17085 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17086 dumpState.setTitlePrinted(true); 17087 } 17088 } 17089 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17090 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17091 : "Service Resolver Table:", " ", packageName, 17092 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17093 dumpState.setTitlePrinted(true); 17094 } 17095 } 17096 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17097 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17098 : "Provider Resolver Table:", " ", packageName, 17099 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17100 dumpState.setTitlePrinted(true); 17101 } 17102 } 17103 17104 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17105 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17106 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17107 int user = mSettings.mPreferredActivities.keyAt(i); 17108 if (pir.dump(pw, 17109 dumpState.getTitlePrinted() 17110 ? "\nPreferred Activities User " + user + ":" 17111 : "Preferred Activities User " + user + ":", " ", 17112 packageName, true, false)) { 17113 dumpState.setTitlePrinted(true); 17114 } 17115 } 17116 } 17117 17118 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17119 pw.flush(); 17120 FileOutputStream fout = new FileOutputStream(fd); 17121 BufferedOutputStream str = new BufferedOutputStream(fout); 17122 XmlSerializer serializer = new FastXmlSerializer(); 17123 try { 17124 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17125 serializer.startDocument(null, true); 17126 serializer.setFeature( 17127 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17128 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17129 serializer.endDocument(); 17130 serializer.flush(); 17131 } catch (IllegalArgumentException e) { 17132 pw.println("Failed writing: " + e); 17133 } catch (IllegalStateException e) { 17134 pw.println("Failed writing: " + e); 17135 } catch (IOException e) { 17136 pw.println("Failed writing: " + e); 17137 } 17138 } 17139 17140 if (!checkin 17141 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17142 && packageName == null) { 17143 pw.println(); 17144 int count = mSettings.mPackages.size(); 17145 if (count == 0) { 17146 pw.println("No applications!"); 17147 pw.println(); 17148 } else { 17149 final String prefix = " "; 17150 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17151 if (allPackageSettings.size() == 0) { 17152 pw.println("No domain preferred apps!"); 17153 pw.println(); 17154 } else { 17155 pw.println("App verification status:"); 17156 pw.println(); 17157 count = 0; 17158 for (PackageSetting ps : allPackageSettings) { 17159 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17160 if (ivi == null || ivi.getPackageName() == null) continue; 17161 pw.println(prefix + "Package: " + ivi.getPackageName()); 17162 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17163 pw.println(prefix + "Status: " + ivi.getStatusString()); 17164 pw.println(); 17165 count++; 17166 } 17167 if (count == 0) { 17168 pw.println(prefix + "No app verification established."); 17169 pw.println(); 17170 } 17171 for (int userId : sUserManager.getUserIds()) { 17172 pw.println("App linkages for user " + userId + ":"); 17173 pw.println(); 17174 count = 0; 17175 for (PackageSetting ps : allPackageSettings) { 17176 final long status = ps.getDomainVerificationStatusForUser(userId); 17177 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17178 continue; 17179 } 17180 pw.println(prefix + "Package: " + ps.name); 17181 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17182 String statusStr = IntentFilterVerificationInfo. 17183 getStatusStringFromValue(status); 17184 pw.println(prefix + "Status: " + statusStr); 17185 pw.println(); 17186 count++; 17187 } 17188 if (count == 0) { 17189 pw.println(prefix + "No configured app linkages."); 17190 pw.println(); 17191 } 17192 } 17193 } 17194 } 17195 } 17196 17197 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17198 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17199 if (packageName == null && permissionNames == null) { 17200 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17201 if (iperm == 0) { 17202 if (dumpState.onTitlePrinted()) 17203 pw.println(); 17204 pw.println("AppOp Permissions:"); 17205 } 17206 pw.print(" AppOp Permission "); 17207 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17208 pw.println(":"); 17209 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17210 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17211 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17212 } 17213 } 17214 } 17215 } 17216 17217 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17218 boolean printedSomething = false; 17219 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17220 if (packageName != null && !packageName.equals(p.info.packageName)) { 17221 continue; 17222 } 17223 if (!printedSomething) { 17224 if (dumpState.onTitlePrinted()) 17225 pw.println(); 17226 pw.println("Registered ContentProviders:"); 17227 printedSomething = true; 17228 } 17229 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17230 pw.print(" "); pw.println(p.toString()); 17231 } 17232 printedSomething = false; 17233 for (Map.Entry<String, PackageParser.Provider> entry : 17234 mProvidersByAuthority.entrySet()) { 17235 PackageParser.Provider p = entry.getValue(); 17236 if (packageName != null && !packageName.equals(p.info.packageName)) { 17237 continue; 17238 } 17239 if (!printedSomething) { 17240 if (dumpState.onTitlePrinted()) 17241 pw.println(); 17242 pw.println("ContentProvider Authorities:"); 17243 printedSomething = true; 17244 } 17245 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17246 pw.print(" "); pw.println(p.toString()); 17247 if (p.info != null && p.info.applicationInfo != null) { 17248 final String appInfo = p.info.applicationInfo.toString(); 17249 pw.print(" applicationInfo="); pw.println(appInfo); 17250 } 17251 } 17252 } 17253 17254 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17255 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17256 } 17257 17258 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17259 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17260 } 17261 17262 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17263 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17264 } 17265 17266 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17267 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17268 } 17269 17270 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17271 // XXX should handle packageName != null by dumping only install data that 17272 // the given package is involved with. 17273 if (dumpState.onTitlePrinted()) pw.println(); 17274 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17275 } 17276 17277 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 17278 if (dumpState.onTitlePrinted()) pw.println(); 17279 mSettings.dumpReadMessagesLPr(pw, dumpState); 17280 17281 pw.println(); 17282 pw.println("Package warning messages:"); 17283 BufferedReader in = null; 17284 String line = null; 17285 try { 17286 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17287 while ((line = in.readLine()) != null) { 17288 if (line.contains("ignored: updated version")) continue; 17289 pw.println(line); 17290 } 17291 } catch (IOException ignored) { 17292 } finally { 17293 IoUtils.closeQuietly(in); 17294 } 17295 } 17296 17297 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 17298 BufferedReader in = null; 17299 String line = null; 17300 try { 17301 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17302 while ((line = in.readLine()) != null) { 17303 if (line.contains("ignored: updated version")) continue; 17304 pw.print("msg,"); 17305 pw.println(line); 17306 } 17307 } catch (IOException ignored) { 17308 } finally { 17309 IoUtils.closeQuietly(in); 17310 } 17311 } 17312 } 17313 } 17314 17315 private String dumpDomainString(String packageName) { 17316 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 17317 List<IntentFilter> filters = getAllIntentFilters(packageName); 17318 17319 ArraySet<String> result = new ArraySet<>(); 17320 if (iviList.size() > 0) { 17321 for (IntentFilterVerificationInfo ivi : iviList) { 17322 for (String host : ivi.getDomains()) { 17323 result.add(host); 17324 } 17325 } 17326 } 17327 if (filters != null && filters.size() > 0) { 17328 for (IntentFilter filter : filters) { 17329 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 17330 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 17331 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 17332 result.addAll(filter.getHostsList()); 17333 } 17334 } 17335 } 17336 17337 StringBuilder sb = new StringBuilder(result.size() * 16); 17338 for (String domain : result) { 17339 if (sb.length() > 0) sb.append(" "); 17340 sb.append(domain); 17341 } 17342 return sb.toString(); 17343 } 17344 17345 // ------- apps on sdcard specific code ------- 17346 static final boolean DEBUG_SD_INSTALL = false; 17347 17348 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 17349 17350 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 17351 17352 private boolean mMediaMounted = false; 17353 17354 static String getEncryptKey() { 17355 try { 17356 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 17357 SD_ENCRYPTION_KEYSTORE_NAME); 17358 if (sdEncKey == null) { 17359 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 17360 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 17361 if (sdEncKey == null) { 17362 Slog.e(TAG, "Failed to create encryption keys"); 17363 return null; 17364 } 17365 } 17366 return sdEncKey; 17367 } catch (NoSuchAlgorithmException nsae) { 17368 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 17369 return null; 17370 } catch (IOException ioe) { 17371 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 17372 return null; 17373 } 17374 } 17375 17376 /* 17377 * Update media status on PackageManager. 17378 */ 17379 @Override 17380 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 17381 int callingUid = Binder.getCallingUid(); 17382 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 17383 throw new SecurityException("Media status can only be updated by the system"); 17384 } 17385 // reader; this apparently protects mMediaMounted, but should probably 17386 // be a different lock in that case. 17387 synchronized (mPackages) { 17388 Log.i(TAG, "Updating external media status from " 17389 + (mMediaMounted ? "mounted" : "unmounted") + " to " 17390 + (mediaStatus ? "mounted" : "unmounted")); 17391 if (DEBUG_SD_INSTALL) 17392 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 17393 + ", mMediaMounted=" + mMediaMounted); 17394 if (mediaStatus == mMediaMounted) { 17395 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 17396 : 0, -1); 17397 mHandler.sendMessage(msg); 17398 return; 17399 } 17400 mMediaMounted = mediaStatus; 17401 } 17402 // Queue up an async operation since the package installation may take a 17403 // little while. 17404 mHandler.post(new Runnable() { 17405 public void run() { 17406 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 17407 } 17408 }); 17409 } 17410 17411 /** 17412 * Called by MountService when the initial ASECs to scan are available. 17413 * Should block until all the ASEC containers are finished being scanned. 17414 */ 17415 public void scanAvailableAsecs() { 17416 updateExternalMediaStatusInner(true, false, false); 17417 } 17418 17419 /* 17420 * Collect information of applications on external media, map them against 17421 * existing containers and update information based on current mount status. 17422 * Please note that we always have to report status if reportStatus has been 17423 * set to true especially when unloading packages. 17424 */ 17425 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 17426 boolean externalStorage) { 17427 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 17428 int[] uidArr = EmptyArray.INT; 17429 17430 final String[] list = PackageHelper.getSecureContainerList(); 17431 if (ArrayUtils.isEmpty(list)) { 17432 Log.i(TAG, "No secure containers found"); 17433 } else { 17434 // Process list of secure containers and categorize them 17435 // as active or stale based on their package internal state. 17436 17437 // reader 17438 synchronized (mPackages) { 17439 for (String cid : list) { 17440 // Leave stages untouched for now; installer service owns them 17441 if (PackageInstallerService.isStageName(cid)) continue; 17442 17443 if (DEBUG_SD_INSTALL) 17444 Log.i(TAG, "Processing container " + cid); 17445 String pkgName = getAsecPackageName(cid); 17446 if (pkgName == null) { 17447 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 17448 continue; 17449 } 17450 if (DEBUG_SD_INSTALL) 17451 Log.i(TAG, "Looking for pkg : " + pkgName); 17452 17453 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17454 if (ps == null) { 17455 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 17456 continue; 17457 } 17458 17459 /* 17460 * Skip packages that are not external if we're unmounting 17461 * external storage. 17462 */ 17463 if (externalStorage && !isMounted && !isExternal(ps)) { 17464 continue; 17465 } 17466 17467 final AsecInstallArgs args = new AsecInstallArgs(cid, 17468 getAppDexInstructionSets(ps), ps.isForwardLocked()); 17469 // The package status is changed only if the code path 17470 // matches between settings and the container id. 17471 if (ps.codePathString != null 17472 && ps.codePathString.startsWith(args.getCodePath())) { 17473 if (DEBUG_SD_INSTALL) { 17474 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 17475 + " at code path: " + ps.codePathString); 17476 } 17477 17478 // We do have a valid package installed on sdcard 17479 processCids.put(args, ps.codePathString); 17480 final int uid = ps.appId; 17481 if (uid != -1) { 17482 uidArr = ArrayUtils.appendInt(uidArr, uid); 17483 } 17484 } else { 17485 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 17486 + ps.codePathString); 17487 } 17488 } 17489 } 17490 17491 Arrays.sort(uidArr); 17492 } 17493 17494 // Process packages with valid entries. 17495 if (isMounted) { 17496 if (DEBUG_SD_INSTALL) 17497 Log.i(TAG, "Loading packages"); 17498 loadMediaPackages(processCids, uidArr, externalStorage); 17499 startCleaningPackages(); 17500 mInstallerService.onSecureContainersAvailable(); 17501 } else { 17502 if (DEBUG_SD_INSTALL) 17503 Log.i(TAG, "Unloading packages"); 17504 unloadMediaPackages(processCids, uidArr, reportStatus); 17505 } 17506 } 17507 17508 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17509 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 17510 final int size = infos.size(); 17511 final String[] packageNames = new String[size]; 17512 final int[] packageUids = new int[size]; 17513 for (int i = 0; i < size; i++) { 17514 final ApplicationInfo info = infos.get(i); 17515 packageNames[i] = info.packageName; 17516 packageUids[i] = info.uid; 17517 } 17518 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 17519 finishedReceiver); 17520 } 17521 17522 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17523 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17524 sendResourcesChangedBroadcast(mediaStatus, replacing, 17525 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 17526 } 17527 17528 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17529 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17530 int size = pkgList.length; 17531 if (size > 0) { 17532 // Send broadcasts here 17533 Bundle extras = new Bundle(); 17534 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 17535 if (uidArr != null) { 17536 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 17537 } 17538 if (replacing) { 17539 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 17540 } 17541 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 17542 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 17543 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 17544 } 17545 } 17546 17547 /* 17548 * Look at potentially valid container ids from processCids If package 17549 * information doesn't match the one on record or package scanning fails, 17550 * the cid is added to list of removeCids. We currently don't delete stale 17551 * containers. 17552 */ 17553 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 17554 boolean externalStorage) { 17555 ArrayList<String> pkgList = new ArrayList<String>(); 17556 Set<AsecInstallArgs> keys = processCids.keySet(); 17557 17558 for (AsecInstallArgs args : keys) { 17559 String codePath = processCids.get(args); 17560 if (DEBUG_SD_INSTALL) 17561 Log.i(TAG, "Loading container : " + args.cid); 17562 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17563 try { 17564 // Make sure there are no container errors first. 17565 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 17566 Slog.e(TAG, "Failed to mount cid : " + args.cid 17567 + " when installing from sdcard"); 17568 continue; 17569 } 17570 // Check code path here. 17571 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 17572 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 17573 + " does not match one in settings " + codePath); 17574 continue; 17575 } 17576 // Parse package 17577 int parseFlags = mDefParseFlags; 17578 if (args.isExternalAsec()) { 17579 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 17580 } 17581 if (args.isFwdLocked()) { 17582 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 17583 } 17584 17585 synchronized (mInstallLock) { 17586 PackageParser.Package pkg = null; 17587 try { 17588 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 17589 } catch (PackageManagerException e) { 17590 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 17591 } 17592 // Scan the package 17593 if (pkg != null) { 17594 /* 17595 * TODO why is the lock being held? doPostInstall is 17596 * called in other places without the lock. This needs 17597 * to be straightened out. 17598 */ 17599 // writer 17600 synchronized (mPackages) { 17601 retCode = PackageManager.INSTALL_SUCCEEDED; 17602 pkgList.add(pkg.packageName); 17603 // Post process args 17604 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 17605 pkg.applicationInfo.uid); 17606 } 17607 } else { 17608 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 17609 } 17610 } 17611 17612 } finally { 17613 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 17614 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 17615 } 17616 } 17617 } 17618 // writer 17619 synchronized (mPackages) { 17620 // If the platform SDK has changed since the last time we booted, 17621 // we need to re-grant app permission to catch any new ones that 17622 // appear. This is really a hack, and means that apps can in some 17623 // cases get permissions that the user didn't initially explicitly 17624 // allow... it would be nice to have some better way to handle 17625 // this situation. 17626 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 17627 : mSettings.getInternalVersion(); 17628 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 17629 : StorageManager.UUID_PRIVATE_INTERNAL; 17630 17631 int updateFlags = UPDATE_PERMISSIONS_ALL; 17632 if (ver.sdkVersion != mSdkVersion) { 17633 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17634 + mSdkVersion + "; regranting permissions for external"); 17635 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17636 } 17637 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17638 17639 // Yay, everything is now upgraded 17640 ver.forceCurrent(); 17641 17642 // can downgrade to reader 17643 // Persist settings 17644 mSettings.writeLPr(); 17645 } 17646 // Send a broadcast to let everyone know we are done processing 17647 if (pkgList.size() > 0) { 17648 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 17649 } 17650 } 17651 17652 /* 17653 * Utility method to unload a list of specified containers 17654 */ 17655 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 17656 // Just unmount all valid containers. 17657 for (AsecInstallArgs arg : cidArgs) { 17658 synchronized (mInstallLock) { 17659 arg.doPostDeleteLI(false); 17660 } 17661 } 17662 } 17663 17664 /* 17665 * Unload packages mounted on external media. This involves deleting package 17666 * data from internal structures, sending broadcasts about disabled packages, 17667 * gc'ing to free up references, unmounting all secure containers 17668 * corresponding to packages on external media, and posting a 17669 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 17670 * that we always have to post this message if status has been requested no 17671 * matter what. 17672 */ 17673 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 17674 final boolean reportStatus) { 17675 if (DEBUG_SD_INSTALL) 17676 Log.i(TAG, "unloading media packages"); 17677 ArrayList<String> pkgList = new ArrayList<String>(); 17678 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 17679 final Set<AsecInstallArgs> keys = processCids.keySet(); 17680 for (AsecInstallArgs args : keys) { 17681 String pkgName = args.getPackageName(); 17682 if (DEBUG_SD_INSTALL) 17683 Log.i(TAG, "Trying to unload pkg : " + pkgName); 17684 // Delete package internally 17685 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17686 synchronized (mInstallLock) { 17687 boolean res = deletePackageLI(pkgName, null, false, null, 17688 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 17689 if (res) { 17690 pkgList.add(pkgName); 17691 } else { 17692 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 17693 failedList.add(args); 17694 } 17695 } 17696 } 17697 17698 // reader 17699 synchronized (mPackages) { 17700 // We didn't update the settings after removing each package; 17701 // write them now for all packages. 17702 mSettings.writeLPr(); 17703 } 17704 17705 // We have to absolutely send UPDATED_MEDIA_STATUS only 17706 // after confirming that all the receivers processed the ordered 17707 // broadcast when packages get disabled, force a gc to clean things up. 17708 // and unload all the containers. 17709 if (pkgList.size() > 0) { 17710 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 17711 new IIntentReceiver.Stub() { 17712 public void performReceive(Intent intent, int resultCode, String data, 17713 Bundle extras, boolean ordered, boolean sticky, 17714 int sendingUser) throws RemoteException { 17715 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 17716 reportStatus ? 1 : 0, 1, keys); 17717 mHandler.sendMessage(msg); 17718 } 17719 }); 17720 } else { 17721 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 17722 keys); 17723 mHandler.sendMessage(msg); 17724 } 17725 } 17726 17727 private void loadPrivatePackages(final VolumeInfo vol) { 17728 mHandler.post(new Runnable() { 17729 @Override 17730 public void run() { 17731 loadPrivatePackagesInner(vol); 17732 } 17733 }); 17734 } 17735 17736 private void loadPrivatePackagesInner(VolumeInfo vol) { 17737 final String volumeUuid = vol.fsUuid; 17738 if (TextUtils.isEmpty(volumeUuid)) { 17739 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 17740 return; 17741 } 17742 17743 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 17744 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 17745 17746 final VersionInfo ver; 17747 final List<PackageSetting> packages; 17748 synchronized (mPackages) { 17749 ver = mSettings.findOrCreateVersion(volumeUuid); 17750 packages = mSettings.getVolumePackagesLPr(volumeUuid); 17751 } 17752 17753 // TODO: introduce a new concept similar to "frozen" to prevent these 17754 // apps from being launched until after data has been fully reconciled 17755 for (PackageSetting ps : packages) { 17756 synchronized (mInstallLock) { 17757 final PackageParser.Package pkg; 17758 try { 17759 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 17760 loaded.add(pkg.applicationInfo); 17761 17762 } catch (PackageManagerException e) { 17763 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 17764 } 17765 17766 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 17767 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 17768 } 17769 } 17770 } 17771 17772 // Reconcile app data for all started/unlocked users 17773 final StorageManager sm = mContext.getSystemService(StorageManager.class); 17774 final UserManager um = mContext.getSystemService(UserManager.class); 17775 for (UserInfo user : um.getUsers()) { 17776 final int flags; 17777 if (um.isUserUnlocked(user.id)) { 17778 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17779 } else if (um.isUserRunning(user.id)) { 17780 flags = StorageManager.FLAG_STORAGE_DE; 17781 } else { 17782 continue; 17783 } 17784 17785 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 17786 reconcileAppsData(volumeUuid, user.id, flags); 17787 } 17788 17789 synchronized (mPackages) { 17790 int updateFlags = UPDATE_PERMISSIONS_ALL; 17791 if (ver.sdkVersion != mSdkVersion) { 17792 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17793 + mSdkVersion + "; regranting permissions for " + volumeUuid); 17794 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17795 } 17796 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17797 17798 // Yay, everything is now upgraded 17799 ver.forceCurrent(); 17800 17801 mSettings.writeLPr(); 17802 } 17803 17804 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 17805 sendResourcesChangedBroadcast(true, false, loaded, null); 17806 } 17807 17808 private void unloadPrivatePackages(final VolumeInfo vol) { 17809 mHandler.post(new Runnable() { 17810 @Override 17811 public void run() { 17812 unloadPrivatePackagesInner(vol); 17813 } 17814 }); 17815 } 17816 17817 private void unloadPrivatePackagesInner(VolumeInfo vol) { 17818 final String volumeUuid = vol.fsUuid; 17819 if (TextUtils.isEmpty(volumeUuid)) { 17820 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 17821 return; 17822 } 17823 17824 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 17825 synchronized (mInstallLock) { 17826 synchronized (mPackages) { 17827 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 17828 for (PackageSetting ps : packages) { 17829 if (ps.pkg == null) continue; 17830 17831 final ApplicationInfo info = ps.pkg.applicationInfo; 17832 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17833 if (deletePackageLI(ps.name, null, false, null, 17834 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 17835 unloaded.add(info); 17836 } else { 17837 Slog.w(TAG, "Failed to unload " + ps.codePath); 17838 } 17839 } 17840 17841 mSettings.writeLPr(); 17842 } 17843 } 17844 17845 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 17846 sendResourcesChangedBroadcast(false, false, unloaded, null); 17847 } 17848 17849 /** 17850 * Examine all users present on given mounted volume, and destroy data 17851 * belonging to users that are no longer valid, or whose user ID has been 17852 * recycled. 17853 */ 17854 private void reconcileUsers(String volumeUuid) { 17855 // TODO: also reconcile DE directories 17856 final File[] files = FileUtils 17857 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 17858 for (File file : files) { 17859 if (!file.isDirectory()) continue; 17860 17861 final int userId; 17862 final UserInfo info; 17863 try { 17864 userId = Integer.parseInt(file.getName()); 17865 info = sUserManager.getUserInfo(userId); 17866 } catch (NumberFormatException e) { 17867 Slog.w(TAG, "Invalid user directory " + file); 17868 continue; 17869 } 17870 17871 boolean destroyUser = false; 17872 if (info == null) { 17873 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17874 + " because no matching user was found"); 17875 destroyUser = true; 17876 } else { 17877 try { 17878 UserManagerService.enforceSerialNumber(file, info.serialNumber); 17879 } catch (IOException e) { 17880 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17881 + " because we failed to enforce serial number: " + e); 17882 destroyUser = true; 17883 } 17884 } 17885 17886 if (destroyUser) { 17887 synchronized (mInstallLock) { 17888 try { 17889 mInstaller.removeUserDataDirs(volumeUuid, userId); 17890 } catch (InstallerException e) { 17891 Slog.w(TAG, "Failed to clean up user dirs", e); 17892 } 17893 } 17894 } 17895 } 17896 } 17897 17898 private void assertPackageKnown(String volumeUuid, String packageName) 17899 throws PackageManagerException { 17900 synchronized (mPackages) { 17901 final PackageSetting ps = mSettings.mPackages.get(packageName); 17902 if (ps == null) { 17903 throw new PackageManagerException("Package " + packageName + " is unknown"); 17904 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 17905 throw new PackageManagerException( 17906 "Package " + packageName + " found on unknown volume " + volumeUuid 17907 + "; expected volume " + ps.volumeUuid); 17908 } 17909 } 17910 } 17911 17912 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 17913 throws PackageManagerException { 17914 synchronized (mPackages) { 17915 final PackageSetting ps = mSettings.mPackages.get(packageName); 17916 if (ps == null) { 17917 throw new PackageManagerException("Package " + packageName + " is unknown"); 17918 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 17919 throw new PackageManagerException( 17920 "Package " + packageName + " found on unknown volume " + volumeUuid 17921 + "; expected volume " + ps.volumeUuid); 17922 } else if (!ps.getInstalled(userId)) { 17923 throw new PackageManagerException( 17924 "Package " + packageName + " not installed for user " + userId); 17925 } 17926 } 17927 } 17928 17929 /** 17930 * Examine all apps present on given mounted volume, and destroy apps that 17931 * aren't expected, either due to uninstallation or reinstallation on 17932 * another volume. 17933 */ 17934 private void reconcileApps(String volumeUuid) { 17935 final File[] files = FileUtils 17936 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 17937 for (File file : files) { 17938 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 17939 && !PackageInstallerService.isStageName(file.getName()); 17940 if (!isPackage) { 17941 // Ignore entries which are not packages 17942 continue; 17943 } 17944 17945 try { 17946 final PackageLite pkg = PackageParser.parsePackageLite(file, 17947 PackageParser.PARSE_MUST_BE_APK); 17948 assertPackageKnown(volumeUuid, pkg.packageName); 17949 17950 } catch (PackageParserException | PackageManagerException e) { 17951 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17952 synchronized (mInstallLock) { 17953 removeCodePathLI(file); 17954 } 17955 } 17956 } 17957 } 17958 17959 /** 17960 * Reconcile all app data for the given user. 17961 * <p> 17962 * Verifies that directories exist and that ownership and labeling is 17963 * correct for all installed apps on all mounted volumes. 17964 */ 17965 void reconcileAppsData(int userId, int flags) { 17966 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17967 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 17968 final String volumeUuid = vol.getFsUuid(); 17969 reconcileAppsData(volumeUuid, userId, flags); 17970 } 17971 } 17972 17973 /** 17974 * Reconcile all app data on given mounted volume. 17975 * <p> 17976 * Destroys app data that isn't expected, either due to uninstallation or 17977 * reinstallation on another volume. 17978 * <p> 17979 * Verifies that directories exist and that ownership and labeling is 17980 * correct for all installed apps. 17981 */ 17982 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 17983 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 17984 + Integer.toHexString(flags)); 17985 17986 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 17987 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 17988 17989 boolean restoreconNeeded = false; 17990 17991 // First look for stale data that doesn't belong, and check if things 17992 // have changed since we did our last restorecon 17993 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 17994 if (!isUserKeyUnlocked(userId)) { 17995 throw new RuntimeException( 17996 "Yikes, someone asked us to reconcile CE storage while " + userId 17997 + " was still locked; this would have caused massive data loss!"); 17998 } 17999 18000 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18001 18002 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18003 for (File file : files) { 18004 final String packageName = file.getName(); 18005 try { 18006 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18007 } catch (PackageManagerException e) { 18008 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18009 synchronized (mInstallLock) { 18010 destroyAppDataLI(volumeUuid, packageName, userId, 18011 StorageManager.FLAG_STORAGE_CE); 18012 } 18013 } 18014 } 18015 } 18016 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18017 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18018 18019 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18020 for (File file : files) { 18021 final String packageName = file.getName(); 18022 try { 18023 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18024 } catch (PackageManagerException e) { 18025 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18026 synchronized (mInstallLock) { 18027 destroyAppDataLI(volumeUuid, packageName, userId, 18028 StorageManager.FLAG_STORAGE_DE); 18029 } 18030 } 18031 } 18032 } 18033 18034 // Ensure that data directories are ready to roll for all packages 18035 // installed for this volume and user 18036 final List<PackageSetting> packages; 18037 synchronized (mPackages) { 18038 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18039 } 18040 int preparedCount = 0; 18041 for (PackageSetting ps : packages) { 18042 final String packageName = ps.name; 18043 if (ps.pkg == null) { 18044 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18045 // TODO: might be due to legacy ASEC apps; we should circle back 18046 // and reconcile again once they're scanned 18047 continue; 18048 } 18049 18050 if (ps.getInstalled(userId)) { 18051 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18052 18053 if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) { 18054 // We may have just shuffled around app data directories, so 18055 // prepare them one more time 18056 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18057 } 18058 18059 preparedCount++; 18060 } 18061 } 18062 18063 if (restoreconNeeded) { 18064 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18065 SELinuxMMAC.setRestoreconDone(ceDir); 18066 } 18067 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18068 SELinuxMMAC.setRestoreconDone(deDir); 18069 } 18070 } 18071 18072 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18073 + " packages; restoreconNeeded was " + restoreconNeeded); 18074 } 18075 18076 /** 18077 * Prepare app data for the given app just after it was installed or 18078 * upgraded. This method carefully only touches users that it's installed 18079 * for, and it forces a restorecon to handle any seinfo changes. 18080 * <p> 18081 * Verifies that directories exist and that ownership and labeling is 18082 * correct for all installed apps. If there is an ownership mismatch, it 18083 * will try recovering system apps by wiping data; third-party app data is 18084 * left intact. 18085 * <p> 18086 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18087 */ 18088 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 18089 prepareAppDataAfterInstallInternal(pkg); 18090 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18091 for (int i = 0; i < childCount; i++) { 18092 PackageParser.Package childPackage = pkg.childPackages.get(i); 18093 prepareAppDataAfterInstallInternal(childPackage); 18094 } 18095 } 18096 18097 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 18098 final PackageSetting ps; 18099 synchronized (mPackages) { 18100 ps = mSettings.mPackages.get(pkg.packageName); 18101 mSettings.writeKernelMappingLPr(ps); 18102 } 18103 18104 final UserManager um = mContext.getSystemService(UserManager.class); 18105 for (UserInfo user : um.getUsers()) { 18106 final int flags; 18107 if (um.isUserUnlocked(user.id)) { 18108 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18109 } else if (um.isUserRunning(user.id)) { 18110 flags = StorageManager.FLAG_STORAGE_DE; 18111 } else { 18112 continue; 18113 } 18114 18115 if (ps.getInstalled(user.id)) { 18116 // Whenever an app changes, force a restorecon of its data 18117 // TODO: when user data is locked, mark that we're still dirty 18118 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 18119 } 18120 } 18121 } 18122 18123 /** 18124 * Prepare app data for the given app. 18125 * <p> 18126 * Verifies that directories exist and that ownership and labeling is 18127 * correct for all installed apps. If there is an ownership mismatch, this 18128 * will try recovering system apps by wiping data; third-party app data is 18129 * left intact. 18130 */ 18131 private void prepareAppData(String volumeUuid, int userId, int flags, 18132 PackageParser.Package pkg, boolean restoreconNeeded) { 18133 if (DEBUG_APP_DATA) { 18134 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18135 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18136 } 18137 18138 final String packageName = pkg.packageName; 18139 final ApplicationInfo app = pkg.applicationInfo; 18140 final int appId = UserHandle.getAppId(app.uid); 18141 18142 Preconditions.checkNotNull(app.seinfo); 18143 18144 synchronized (mInstallLock) { 18145 try { 18146 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18147 appId, app.seinfo, app.targetSdkVersion); 18148 } catch (InstallerException e) { 18149 if (app.isSystemApp()) { 18150 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18151 + ", but trying to recover: " + e); 18152 destroyAppDataLI(volumeUuid, packageName, userId, flags); 18153 try { 18154 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18155 appId, app.seinfo, app.targetSdkVersion); 18156 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18157 } catch (InstallerException e2) { 18158 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18159 } 18160 } else { 18161 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18162 } 18163 } 18164 18165 if (restoreconNeeded) { 18166 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18167 } 18168 18169 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18170 // Create a native library symlink only if we have native libraries 18171 // and if the native libraries are 32 bit libraries. We do not provide 18172 // this symlink for 64 bit libraries. 18173 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18174 final String nativeLibPath = app.nativeLibraryDir; 18175 try { 18176 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18177 nativeLibPath, userId); 18178 } catch (InstallerException e) { 18179 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18180 } 18181 } 18182 } 18183 } 18184 } 18185 18186 /** 18187 * For system apps on non-FBE devices, this method migrates any existing 18188 * CE/DE data to match the {@code forceDeviceEncrypted} flag requested by 18189 * the app. 18190 */ 18191 private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) { 18192 if (pkg.isSystemApp() && !StorageManager.isFileBasedEncryptionEnabled() 18193 && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) { 18194 final int storageTarget = pkg.applicationInfo.isForceDeviceEncrypted() 18195 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 18196 synchronized (mInstallLock) { 18197 try { 18198 mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget); 18199 } catch (InstallerException e) { 18200 logCriticalInfo(Log.WARN, 18201 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 18202 } 18203 } 18204 return true; 18205 } else { 18206 return false; 18207 } 18208 } 18209 18210 private void unfreezePackage(String packageName) { 18211 synchronized (mPackages) { 18212 final PackageSetting ps = mSettings.mPackages.get(packageName); 18213 if (ps != null) { 18214 ps.frozen = false; 18215 } 18216 } 18217 } 18218 18219 @Override 18220 public int movePackage(final String packageName, final String volumeUuid) { 18221 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18222 18223 final int moveId = mNextMoveId.getAndIncrement(); 18224 mHandler.post(new Runnable() { 18225 @Override 18226 public void run() { 18227 try { 18228 movePackageInternal(packageName, volumeUuid, moveId); 18229 } catch (PackageManagerException e) { 18230 Slog.w(TAG, "Failed to move " + packageName, e); 18231 mMoveCallbacks.notifyStatusChanged(moveId, 18232 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18233 } 18234 } 18235 }); 18236 return moveId; 18237 } 18238 18239 private void movePackageInternal(final String packageName, final String volumeUuid, 18240 final int moveId) throws PackageManagerException { 18241 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 18242 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18243 final PackageManager pm = mContext.getPackageManager(); 18244 18245 final boolean currentAsec; 18246 final String currentVolumeUuid; 18247 final File codeFile; 18248 final String installerPackageName; 18249 final String packageAbiOverride; 18250 final int appId; 18251 final String seinfo; 18252 final String label; 18253 final int targetSdkVersion; 18254 18255 // reader 18256 synchronized (mPackages) { 18257 final PackageParser.Package pkg = mPackages.get(packageName); 18258 final PackageSetting ps = mSettings.mPackages.get(packageName); 18259 if (pkg == null || ps == null) { 18260 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 18261 } 18262 18263 if (pkg.applicationInfo.isSystemApp()) { 18264 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 18265 "Cannot move system application"); 18266 } 18267 18268 if (pkg.applicationInfo.isExternalAsec()) { 18269 currentAsec = true; 18270 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 18271 } else if (pkg.applicationInfo.isForwardLocked()) { 18272 currentAsec = true; 18273 currentVolumeUuid = "forward_locked"; 18274 } else { 18275 currentAsec = false; 18276 currentVolumeUuid = ps.volumeUuid; 18277 18278 final File probe = new File(pkg.codePath); 18279 final File probeOat = new File(probe, "oat"); 18280 if (!probe.isDirectory() || !probeOat.isDirectory()) { 18281 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18282 "Move only supported for modern cluster style installs"); 18283 } 18284 } 18285 18286 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 18287 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18288 "Package already moved to " + volumeUuid); 18289 } 18290 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 18291 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 18292 "Device admin cannot be moved"); 18293 } 18294 18295 if (ps.frozen) { 18296 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 18297 "Failed to move already frozen package"); 18298 } 18299 ps.frozen = true; 18300 18301 codeFile = new File(pkg.codePath); 18302 installerPackageName = ps.installerPackageName; 18303 packageAbiOverride = ps.cpuAbiOverrideString; 18304 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18305 seinfo = pkg.applicationInfo.seinfo; 18306 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 18307 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 18308 } 18309 18310 // Now that we're guarded by frozen state, kill app during move 18311 final long token = Binder.clearCallingIdentity(); 18312 try { 18313 killApplication(packageName, appId, "move pkg"); 18314 } finally { 18315 Binder.restoreCallingIdentity(token); 18316 } 18317 18318 final Bundle extras = new Bundle(); 18319 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 18320 extras.putString(Intent.EXTRA_TITLE, label); 18321 mMoveCallbacks.notifyCreated(moveId, extras); 18322 18323 int installFlags; 18324 final boolean moveCompleteApp; 18325 final File measurePath; 18326 18327 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 18328 installFlags = INSTALL_INTERNAL; 18329 moveCompleteApp = !currentAsec; 18330 measurePath = Environment.getDataAppDirectory(volumeUuid); 18331 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 18332 installFlags = INSTALL_EXTERNAL; 18333 moveCompleteApp = false; 18334 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 18335 } else { 18336 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 18337 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 18338 || !volume.isMountedWritable()) { 18339 unfreezePackage(packageName); 18340 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18341 "Move location not mounted private volume"); 18342 } 18343 18344 Preconditions.checkState(!currentAsec); 18345 18346 installFlags = INSTALL_INTERNAL; 18347 moveCompleteApp = true; 18348 measurePath = Environment.getDataAppDirectory(volumeUuid); 18349 } 18350 18351 final PackageStats stats = new PackageStats(null, -1); 18352 synchronized (mInstaller) { 18353 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 18354 unfreezePackage(packageName); 18355 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18356 "Failed to measure package size"); 18357 } 18358 } 18359 18360 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 18361 + stats.dataSize); 18362 18363 final long startFreeBytes = measurePath.getFreeSpace(); 18364 final long sizeBytes; 18365 if (moveCompleteApp) { 18366 sizeBytes = stats.codeSize + stats.dataSize; 18367 } else { 18368 sizeBytes = stats.codeSize; 18369 } 18370 18371 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 18372 unfreezePackage(packageName); 18373 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18374 "Not enough free space to move"); 18375 } 18376 18377 mMoveCallbacks.notifyStatusChanged(moveId, 10); 18378 18379 final CountDownLatch installedLatch = new CountDownLatch(1); 18380 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 18381 @Override 18382 public void onUserActionRequired(Intent intent) throws RemoteException { 18383 throw new IllegalStateException(); 18384 } 18385 18386 @Override 18387 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 18388 Bundle extras) throws RemoteException { 18389 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 18390 + PackageManager.installStatusToString(returnCode, msg)); 18391 18392 installedLatch.countDown(); 18393 18394 // Regardless of success or failure of the move operation, 18395 // always unfreeze the package 18396 unfreezePackage(packageName); 18397 18398 final int status = PackageManager.installStatusToPublicStatus(returnCode); 18399 switch (status) { 18400 case PackageInstaller.STATUS_SUCCESS: 18401 mMoveCallbacks.notifyStatusChanged(moveId, 18402 PackageManager.MOVE_SUCCEEDED); 18403 break; 18404 case PackageInstaller.STATUS_FAILURE_STORAGE: 18405 mMoveCallbacks.notifyStatusChanged(moveId, 18406 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 18407 break; 18408 default: 18409 mMoveCallbacks.notifyStatusChanged(moveId, 18410 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18411 break; 18412 } 18413 } 18414 }; 18415 18416 final MoveInfo move; 18417 if (moveCompleteApp) { 18418 // Kick off a thread to report progress estimates 18419 new Thread() { 18420 @Override 18421 public void run() { 18422 while (true) { 18423 try { 18424 if (installedLatch.await(1, TimeUnit.SECONDS)) { 18425 break; 18426 } 18427 } catch (InterruptedException ignored) { 18428 } 18429 18430 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 18431 final int progress = 10 + (int) MathUtils.constrain( 18432 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 18433 mMoveCallbacks.notifyStatusChanged(moveId, progress); 18434 } 18435 } 18436 }.start(); 18437 18438 final String dataAppName = codeFile.getName(); 18439 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 18440 dataAppName, appId, seinfo, targetSdkVersion); 18441 } else { 18442 move = null; 18443 } 18444 18445 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 18446 18447 final Message msg = mHandler.obtainMessage(INIT_COPY); 18448 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 18449 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 18450 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 18451 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 18452 msg.obj = params; 18453 18454 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 18455 System.identityHashCode(msg.obj)); 18456 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 18457 System.identityHashCode(msg.obj)); 18458 18459 mHandler.sendMessage(msg); 18460 } 18461 18462 @Override 18463 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 18464 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18465 18466 final int realMoveId = mNextMoveId.getAndIncrement(); 18467 final Bundle extras = new Bundle(); 18468 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 18469 mMoveCallbacks.notifyCreated(realMoveId, extras); 18470 18471 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 18472 @Override 18473 public void onCreated(int moveId, Bundle extras) { 18474 // Ignored 18475 } 18476 18477 @Override 18478 public void onStatusChanged(int moveId, int status, long estMillis) { 18479 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 18480 } 18481 }; 18482 18483 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18484 storage.setPrimaryStorageUuid(volumeUuid, callback); 18485 return realMoveId; 18486 } 18487 18488 @Override 18489 public int getMoveStatus(int moveId) { 18490 mContext.enforceCallingOrSelfPermission( 18491 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18492 return mMoveCallbacks.mLastStatus.get(moveId); 18493 } 18494 18495 @Override 18496 public void registerMoveCallback(IPackageMoveObserver callback) { 18497 mContext.enforceCallingOrSelfPermission( 18498 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18499 mMoveCallbacks.register(callback); 18500 } 18501 18502 @Override 18503 public void unregisterMoveCallback(IPackageMoveObserver callback) { 18504 mContext.enforceCallingOrSelfPermission( 18505 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18506 mMoveCallbacks.unregister(callback); 18507 } 18508 18509 @Override 18510 public boolean setInstallLocation(int loc) { 18511 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 18512 null); 18513 if (getInstallLocation() == loc) { 18514 return true; 18515 } 18516 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 18517 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 18518 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 18519 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 18520 return true; 18521 } 18522 return false; 18523 } 18524 18525 @Override 18526 public int getInstallLocation() { 18527 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 18528 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 18529 PackageHelper.APP_INSTALL_AUTO); 18530 } 18531 18532 /** Called by UserManagerService */ 18533 void cleanUpUser(UserManagerService userManager, int userHandle) { 18534 synchronized (mPackages) { 18535 mDirtyUsers.remove(userHandle); 18536 mUserNeedsBadging.delete(userHandle); 18537 mSettings.removeUserLPw(userHandle); 18538 mPendingBroadcasts.remove(userHandle); 18539 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 18540 } 18541 synchronized (mInstallLock) { 18542 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18543 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18544 final String volumeUuid = vol.getFsUuid(); 18545 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 18546 try { 18547 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 18548 } catch (InstallerException e) { 18549 Slog.w(TAG, "Failed to remove user data", e); 18550 } 18551 } 18552 synchronized (mPackages) { 18553 removeUnusedPackagesLILPw(userManager, userHandle); 18554 } 18555 } 18556 } 18557 18558 /** 18559 * We're removing userHandle and would like to remove any downloaded packages 18560 * that are no longer in use by any other user. 18561 * @param userHandle the user being removed 18562 */ 18563 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 18564 final boolean DEBUG_CLEAN_APKS = false; 18565 int [] users = userManager.getUserIds(); 18566 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 18567 while (psit.hasNext()) { 18568 PackageSetting ps = psit.next(); 18569 if (ps.pkg == null) { 18570 continue; 18571 } 18572 final String packageName = ps.pkg.packageName; 18573 // Skip over if system app 18574 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 18575 continue; 18576 } 18577 if (DEBUG_CLEAN_APKS) { 18578 Slog.i(TAG, "Checking package " + packageName); 18579 } 18580 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 18581 if (keep) { 18582 if (DEBUG_CLEAN_APKS) { 18583 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 18584 } 18585 } else { 18586 for (int i = 0; i < users.length; i++) { 18587 if (users[i] != userHandle && ps.getInstalled(users[i])) { 18588 keep = true; 18589 if (DEBUG_CLEAN_APKS) { 18590 Slog.i(TAG, " Keeping package " + packageName + " for user " 18591 + users[i]); 18592 } 18593 break; 18594 } 18595 } 18596 } 18597 if (!keep) { 18598 if (DEBUG_CLEAN_APKS) { 18599 Slog.i(TAG, " Removing package " + packageName); 18600 } 18601 mHandler.post(new Runnable() { 18602 public void run() { 18603 deletePackageX(packageName, userHandle, 0); 18604 } //end run 18605 }); 18606 } 18607 } 18608 } 18609 18610 /** Called by UserManagerService */ 18611 void createNewUser(int userHandle) { 18612 synchronized (mInstallLock) { 18613 try { 18614 mInstaller.createUserConfig(userHandle); 18615 } catch (InstallerException e) { 18616 Slog.w(TAG, "Failed to create user config", e); 18617 } 18618 mSettings.createNewUserLI(this, mInstaller, userHandle); 18619 } 18620 synchronized (mPackages) { 18621 applyFactoryDefaultBrowserLPw(userHandle); 18622 primeDomainVerificationsLPw(userHandle); 18623 } 18624 } 18625 18626 void newUserCreated(final int userHandle) { 18627 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 18628 // If permission review for legacy apps is required, we represent 18629 // dagerous permissions for such apps as always granted runtime 18630 // permissions to keep per user flag state whether review is needed. 18631 // Hence, if a new user is added we have to propagate dangerous 18632 // permission grants for these legacy apps. 18633 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 18634 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 18635 | UPDATE_PERMISSIONS_REPLACE_ALL); 18636 } 18637 } 18638 18639 @Override 18640 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 18641 mContext.enforceCallingOrSelfPermission( 18642 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 18643 "Only package verification agents can read the verifier device identity"); 18644 18645 synchronized (mPackages) { 18646 return mSettings.getVerifierDeviceIdentityLPw(); 18647 } 18648 } 18649 18650 @Override 18651 public void setPermissionEnforced(String permission, boolean enforced) { 18652 // TODO: Now that we no longer change GID for storage, this should to away. 18653 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 18654 "setPermissionEnforced"); 18655 if (READ_EXTERNAL_STORAGE.equals(permission)) { 18656 synchronized (mPackages) { 18657 if (mSettings.mReadExternalStorageEnforced == null 18658 || mSettings.mReadExternalStorageEnforced != enforced) { 18659 mSettings.mReadExternalStorageEnforced = enforced; 18660 mSettings.writeLPr(); 18661 } 18662 } 18663 // kill any non-foreground processes so we restart them and 18664 // grant/revoke the GID. 18665 final IActivityManager am = ActivityManagerNative.getDefault(); 18666 if (am != null) { 18667 final long token = Binder.clearCallingIdentity(); 18668 try { 18669 am.killProcessesBelowForeground("setPermissionEnforcement"); 18670 } catch (RemoteException e) { 18671 } finally { 18672 Binder.restoreCallingIdentity(token); 18673 } 18674 } 18675 } else { 18676 throw new IllegalArgumentException("No selective enforcement for " + permission); 18677 } 18678 } 18679 18680 @Override 18681 @Deprecated 18682 public boolean isPermissionEnforced(String permission) { 18683 return true; 18684 } 18685 18686 @Override 18687 public boolean isStorageLow() { 18688 final long token = Binder.clearCallingIdentity(); 18689 try { 18690 final DeviceStorageMonitorInternal 18691 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 18692 if (dsm != null) { 18693 return dsm.isMemoryLow(); 18694 } else { 18695 return false; 18696 } 18697 } finally { 18698 Binder.restoreCallingIdentity(token); 18699 } 18700 } 18701 18702 @Override 18703 public IPackageInstaller getPackageInstaller() { 18704 return mInstallerService; 18705 } 18706 18707 private boolean userNeedsBadging(int userId) { 18708 int index = mUserNeedsBadging.indexOfKey(userId); 18709 if (index < 0) { 18710 final UserInfo userInfo; 18711 final long token = Binder.clearCallingIdentity(); 18712 try { 18713 userInfo = sUserManager.getUserInfo(userId); 18714 } finally { 18715 Binder.restoreCallingIdentity(token); 18716 } 18717 final boolean b; 18718 if (userInfo != null && userInfo.isManagedProfile()) { 18719 b = true; 18720 } else { 18721 b = false; 18722 } 18723 mUserNeedsBadging.put(userId, b); 18724 return b; 18725 } 18726 return mUserNeedsBadging.valueAt(index); 18727 } 18728 18729 @Override 18730 public KeySet getKeySetByAlias(String packageName, String alias) { 18731 if (packageName == null || alias == null) { 18732 return null; 18733 } 18734 synchronized(mPackages) { 18735 final PackageParser.Package pkg = mPackages.get(packageName); 18736 if (pkg == null) { 18737 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18738 throw new IllegalArgumentException("Unknown package: " + packageName); 18739 } 18740 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18741 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 18742 } 18743 } 18744 18745 @Override 18746 public KeySet getSigningKeySet(String packageName) { 18747 if (packageName == null) { 18748 return null; 18749 } 18750 synchronized(mPackages) { 18751 final PackageParser.Package pkg = mPackages.get(packageName); 18752 if (pkg == null) { 18753 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18754 throw new IllegalArgumentException("Unknown package: " + packageName); 18755 } 18756 if (pkg.applicationInfo.uid != Binder.getCallingUid() 18757 && Process.SYSTEM_UID != Binder.getCallingUid()) { 18758 throw new SecurityException("May not access signing KeySet of other apps."); 18759 } 18760 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18761 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 18762 } 18763 } 18764 18765 @Override 18766 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 18767 if (packageName == null || ks == null) { 18768 return false; 18769 } 18770 synchronized(mPackages) { 18771 final PackageParser.Package pkg = mPackages.get(packageName); 18772 if (pkg == null) { 18773 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18774 throw new IllegalArgumentException("Unknown package: " + packageName); 18775 } 18776 IBinder ksh = ks.getToken(); 18777 if (ksh instanceof KeySetHandle) { 18778 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18779 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 18780 } 18781 return false; 18782 } 18783 } 18784 18785 @Override 18786 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 18787 if (packageName == null || ks == null) { 18788 return false; 18789 } 18790 synchronized(mPackages) { 18791 final PackageParser.Package pkg = mPackages.get(packageName); 18792 if (pkg == null) { 18793 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18794 throw new IllegalArgumentException("Unknown package: " + packageName); 18795 } 18796 IBinder ksh = ks.getToken(); 18797 if (ksh instanceof KeySetHandle) { 18798 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18799 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 18800 } 18801 return false; 18802 } 18803 } 18804 18805 private void deletePackageIfUnusedLPr(final String packageName) { 18806 PackageSetting ps = mSettings.mPackages.get(packageName); 18807 if (ps == null) { 18808 return; 18809 } 18810 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 18811 // TODO Implement atomic delete if package is unused 18812 // It is currently possible that the package will be deleted even if it is installed 18813 // after this method returns. 18814 mHandler.post(new Runnable() { 18815 public void run() { 18816 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 18817 } 18818 }); 18819 } 18820 } 18821 18822 /** 18823 * Check and throw if the given before/after packages would be considered a 18824 * downgrade. 18825 */ 18826 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 18827 throws PackageManagerException { 18828 if (after.versionCode < before.mVersionCode) { 18829 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18830 "Update version code " + after.versionCode + " is older than current " 18831 + before.mVersionCode); 18832 } else if (after.versionCode == before.mVersionCode) { 18833 if (after.baseRevisionCode < before.baseRevisionCode) { 18834 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18835 "Update base revision code " + after.baseRevisionCode 18836 + " is older than current " + before.baseRevisionCode); 18837 } 18838 18839 if (!ArrayUtils.isEmpty(after.splitNames)) { 18840 for (int i = 0; i < after.splitNames.length; i++) { 18841 final String splitName = after.splitNames[i]; 18842 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 18843 if (j != -1) { 18844 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 18845 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18846 "Update split " + splitName + " revision code " 18847 + after.splitRevisionCodes[i] + " is older than current " 18848 + before.splitRevisionCodes[j]); 18849 } 18850 } 18851 } 18852 } 18853 } 18854 } 18855 18856 private static class MoveCallbacks extends Handler { 18857 private static final int MSG_CREATED = 1; 18858 private static final int MSG_STATUS_CHANGED = 2; 18859 18860 private final RemoteCallbackList<IPackageMoveObserver> 18861 mCallbacks = new RemoteCallbackList<>(); 18862 18863 private final SparseIntArray mLastStatus = new SparseIntArray(); 18864 18865 public MoveCallbacks(Looper looper) { 18866 super(looper); 18867 } 18868 18869 public void register(IPackageMoveObserver callback) { 18870 mCallbacks.register(callback); 18871 } 18872 18873 public void unregister(IPackageMoveObserver callback) { 18874 mCallbacks.unregister(callback); 18875 } 18876 18877 @Override 18878 public void handleMessage(Message msg) { 18879 final SomeArgs args = (SomeArgs) msg.obj; 18880 final int n = mCallbacks.beginBroadcast(); 18881 for (int i = 0; i < n; i++) { 18882 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 18883 try { 18884 invokeCallback(callback, msg.what, args); 18885 } catch (RemoteException ignored) { 18886 } 18887 } 18888 mCallbacks.finishBroadcast(); 18889 args.recycle(); 18890 } 18891 18892 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 18893 throws RemoteException { 18894 switch (what) { 18895 case MSG_CREATED: { 18896 callback.onCreated(args.argi1, (Bundle) args.arg2); 18897 break; 18898 } 18899 case MSG_STATUS_CHANGED: { 18900 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 18901 break; 18902 } 18903 } 18904 } 18905 18906 private void notifyCreated(int moveId, Bundle extras) { 18907 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 18908 18909 final SomeArgs args = SomeArgs.obtain(); 18910 args.argi1 = moveId; 18911 args.arg2 = extras; 18912 obtainMessage(MSG_CREATED, args).sendToTarget(); 18913 } 18914 18915 private void notifyStatusChanged(int moveId, int status) { 18916 notifyStatusChanged(moveId, status, -1); 18917 } 18918 18919 private void notifyStatusChanged(int moveId, int status, long estMillis) { 18920 Slog.v(TAG, "Move " + moveId + " status " + status); 18921 18922 final SomeArgs args = SomeArgs.obtain(); 18923 args.argi1 = moveId; 18924 args.argi2 = status; 18925 args.arg3 = estMillis; 18926 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 18927 18928 synchronized (mLastStatus) { 18929 mLastStatus.put(moveId, status); 18930 } 18931 } 18932 } 18933 18934 private final static class OnPermissionChangeListeners extends Handler { 18935 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 18936 18937 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 18938 new RemoteCallbackList<>(); 18939 18940 public OnPermissionChangeListeners(Looper looper) { 18941 super(looper); 18942 } 18943 18944 @Override 18945 public void handleMessage(Message msg) { 18946 switch (msg.what) { 18947 case MSG_ON_PERMISSIONS_CHANGED: { 18948 final int uid = msg.arg1; 18949 handleOnPermissionsChanged(uid); 18950 } break; 18951 } 18952 } 18953 18954 public void addListenerLocked(IOnPermissionsChangeListener listener) { 18955 mPermissionListeners.register(listener); 18956 18957 } 18958 18959 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 18960 mPermissionListeners.unregister(listener); 18961 } 18962 18963 public void onPermissionsChanged(int uid) { 18964 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 18965 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 18966 } 18967 } 18968 18969 private void handleOnPermissionsChanged(int uid) { 18970 final int count = mPermissionListeners.beginBroadcast(); 18971 try { 18972 for (int i = 0; i < count; i++) { 18973 IOnPermissionsChangeListener callback = mPermissionListeners 18974 .getBroadcastItem(i); 18975 try { 18976 callback.onPermissionsChanged(uid); 18977 } catch (RemoteException e) { 18978 Log.e(TAG, "Permission listener is dead", e); 18979 } 18980 } 18981 } finally { 18982 mPermissionListeners.finishBroadcast(); 18983 } 18984 } 18985 } 18986 18987 private class PackageManagerInternalImpl extends PackageManagerInternal { 18988 @Override 18989 public void setLocationPackagesProvider(PackagesProvider provider) { 18990 synchronized (mPackages) { 18991 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 18992 } 18993 } 18994 18995 @Override 18996 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 18997 synchronized (mPackages) { 18998 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 18999 } 19000 } 19001 19002 @Override 19003 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19004 synchronized (mPackages) { 19005 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19006 } 19007 } 19008 19009 @Override 19010 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19011 synchronized (mPackages) { 19012 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19013 } 19014 } 19015 19016 @Override 19017 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19018 synchronized (mPackages) { 19019 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19020 } 19021 } 19022 19023 @Override 19024 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19025 synchronized (mPackages) { 19026 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19027 } 19028 } 19029 19030 @Override 19031 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19032 synchronized (mPackages) { 19033 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19034 packageName, userId); 19035 } 19036 } 19037 19038 @Override 19039 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19040 synchronized (mPackages) { 19041 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19042 packageName, userId); 19043 } 19044 } 19045 19046 @Override 19047 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19048 synchronized (mPackages) { 19049 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19050 packageName, userId); 19051 } 19052 } 19053 19054 @Override 19055 public void setKeepUninstalledPackages(final List<String> packageList) { 19056 Preconditions.checkNotNull(packageList); 19057 List<String> removedFromList = null; 19058 synchronized (mPackages) { 19059 if (mKeepUninstalledPackages != null) { 19060 final int packagesCount = mKeepUninstalledPackages.size(); 19061 for (int i = 0; i < packagesCount; i++) { 19062 String oldPackage = mKeepUninstalledPackages.get(i); 19063 if (packageList != null && packageList.contains(oldPackage)) { 19064 continue; 19065 } 19066 if (removedFromList == null) { 19067 removedFromList = new ArrayList<>(); 19068 } 19069 removedFromList.add(oldPackage); 19070 } 19071 } 19072 mKeepUninstalledPackages = new ArrayList<>(packageList); 19073 if (removedFromList != null) { 19074 final int removedCount = removedFromList.size(); 19075 for (int i = 0; i < removedCount; i++) { 19076 deletePackageIfUnusedLPr(removedFromList.get(i)); 19077 } 19078 } 19079 } 19080 } 19081 19082 @Override 19083 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19084 synchronized (mPackages) { 19085 // If we do not support permission review, done. 19086 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19087 return false; 19088 } 19089 19090 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 19091 if (packageSetting == null) { 19092 return false; 19093 } 19094 19095 // Permission review applies only to apps not supporting the new permission model. 19096 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 19097 return false; 19098 } 19099 19100 // Legacy apps have the permission and get user consent on launch. 19101 PermissionsState permissionsState = packageSetting.getPermissionsState(); 19102 return permissionsState.isPermissionReviewRequired(userId); 19103 } 19104 } 19105 } 19106 19107 @Override 19108 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 19109 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 19110 synchronized (mPackages) { 19111 final long identity = Binder.clearCallingIdentity(); 19112 try { 19113 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 19114 packageNames, userId); 19115 } finally { 19116 Binder.restoreCallingIdentity(identity); 19117 } 19118 } 19119 } 19120 19121 private static void enforceSystemOrPhoneCaller(String tag) { 19122 int callingUid = Binder.getCallingUid(); 19123 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 19124 throw new SecurityException( 19125 "Cannot call " + tag + " from UID " + callingUid); 19126 } 19127 } 19128 19129 boolean isHistoricalPackageUsageAvailable() { 19130 return mPackageUsage.isHistoricalPackageUsageAvailable(); 19131 } 19132} 19133