PackageManagerService.java revision 355b232d7998cfc9b29d42a0356390e25191bcbd
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 65import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 67import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 68import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 69import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 70import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 71import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 72import static android.content.pm.PackageManager.PERMISSION_DENIED; 73import static android.content.pm.PackageManager.PERMISSION_GRANTED; 74import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 75import static android.content.pm.PackageParser.isApkFile; 76import static android.os.Process.PACKAGE_INFO_GID; 77import static android.os.Process.SYSTEM_UID; 78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 79import static android.system.OsConstants.O_CREAT; 80import static android.system.OsConstants.O_RDWR; 81 82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 86import static com.android.internal.util.ArrayUtils.appendInt; 87import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 93import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 94import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 95import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 96 97import android.Manifest; 98import android.annotation.NonNull; 99import android.annotation.Nullable; 100import android.app.ActivityManager; 101import android.app.ActivityManagerNative; 102import android.app.AppGlobals; 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.Package; 145import android.content.pm.PackageParser.PackageLite; 146import android.content.pm.PackageParser.PackageParserException; 147import android.content.pm.PackageStats; 148import android.content.pm.PackageUserState; 149import android.content.pm.ParceledListSlice; 150import android.content.pm.PermissionGroupInfo; 151import android.content.pm.PermissionInfo; 152import android.content.pm.ProviderInfo; 153import android.content.pm.ResolveInfo; 154import android.content.pm.ServiceInfo; 155import android.content.pm.Signature; 156import android.content.pm.UserInfo; 157import android.content.pm.VerificationParams; 158import android.content.pm.VerifierDeviceIdentity; 159import android.content.pm.VerifierInfo; 160import android.content.res.Resources; 161import android.graphics.Bitmap; 162import android.hardware.display.DisplayManager; 163import android.net.Uri; 164import android.os.Binder; 165import android.os.Build; 166import android.os.Bundle; 167import android.os.Debug; 168import android.os.Environment; 169import android.os.Environment.UserEnvironment; 170import android.os.FileUtils; 171import android.os.Handler; 172import android.os.IBinder; 173import android.os.Looper; 174import android.os.Message; 175import android.os.Parcel; 176import android.os.ParcelFileDescriptor; 177import android.os.Process; 178import android.os.RemoteCallbackList; 179import android.os.RemoteException; 180import android.os.ResultReceiver; 181import android.os.SELinux; 182import android.os.ServiceManager; 183import android.os.SystemClock; 184import android.os.SystemProperties; 185import android.os.Trace; 186import android.os.UserHandle; 187import android.os.UserManager; 188import android.os.storage.IMountService; 189import android.os.storage.MountServiceInternal; 190import android.os.storage.StorageEventListener; 191import android.os.storage.StorageManager; 192import android.os.storage.VolumeInfo; 193import android.os.storage.VolumeRecord; 194import android.security.KeyStore; 195import android.security.SystemKeyStore; 196import android.system.ErrnoException; 197import android.system.Os; 198import android.text.TextUtils; 199import android.text.format.DateUtils; 200import android.util.ArrayMap; 201import android.util.ArraySet; 202import android.util.AtomicFile; 203import android.util.DisplayMetrics; 204import android.util.EventLog; 205import android.util.ExceptionUtils; 206import android.util.Log; 207import android.util.LogPrinter; 208import android.util.MathUtils; 209import android.util.PrintStreamPrinter; 210import android.util.Slog; 211import android.util.SparseArray; 212import android.util.SparseBooleanArray; 213import android.util.SparseIntArray; 214import android.util.Xml; 215import android.view.Display; 216 217import com.android.internal.R; 218import com.android.internal.annotations.GuardedBy; 219import com.android.internal.app.IMediaContainerService; 220import com.android.internal.app.ResolverActivity; 221import com.android.internal.content.NativeLibraryHelper; 222import com.android.internal.content.PackageHelper; 223import com.android.internal.os.IParcelFileDescriptorFactory; 224import com.android.internal.os.InstallerConnection.InstallerException; 225import com.android.internal.os.SomeArgs; 226import com.android.internal.os.Zygote; 227import com.android.internal.util.ArrayUtils; 228import com.android.internal.util.FastPrintWriter; 229import com.android.internal.util.FastXmlSerializer; 230import com.android.internal.util.IndentingPrintWriter; 231import com.android.internal.util.Preconditions; 232import com.android.internal.util.XmlUtils; 233import com.android.server.EventLogTags; 234import com.android.server.FgThread; 235import com.android.server.IntentResolver; 236import com.android.server.LocalServices; 237import com.android.server.ServiceThread; 238import com.android.server.SystemConfig; 239import com.android.server.Watchdog; 240import com.android.server.pm.PermissionsState.PermissionState; 241import com.android.server.pm.Settings.DatabaseVersion; 242import com.android.server.pm.Settings.VersionInfo; 243import com.android.server.storage.DeviceStorageMonitorInternal; 244 245import dalvik.system.DexFile; 246import dalvik.system.VMRuntime; 247 248import libcore.io.IoUtils; 249import libcore.util.EmptyArray; 250 251import org.xmlpull.v1.XmlPullParser; 252import org.xmlpull.v1.XmlPullParserException; 253import org.xmlpull.v1.XmlSerializer; 254 255import java.io.BufferedInputStream; 256import java.io.BufferedOutputStream; 257import java.io.BufferedReader; 258import java.io.ByteArrayInputStream; 259import java.io.ByteArrayOutputStream; 260import java.io.File; 261import java.io.FileDescriptor; 262import java.io.FileNotFoundException; 263import java.io.FileOutputStream; 264import java.io.FileReader; 265import java.io.FilenameFilter; 266import java.io.IOException; 267import java.io.InputStream; 268import java.io.PrintStream; 269import java.io.PrintWriter; 270import java.nio.charset.StandardCharsets; 271import java.security.MessageDigest; 272import java.security.NoSuchAlgorithmException; 273import java.security.PublicKey; 274import java.security.cert.CertificateEncodingException; 275import java.security.cert.CertificateException; 276import java.text.SimpleDateFormat; 277import java.util.ArrayList; 278import java.util.Arrays; 279import java.util.Collection; 280import java.util.Collections; 281import java.util.Comparator; 282import java.util.Date; 283import java.util.HashSet; 284import java.util.Iterator; 285import java.util.LinkedList; 286import java.util.List; 287import java.util.Map; 288import java.util.Objects; 289import java.util.Set; 290import java.util.concurrent.CountDownLatch; 291import java.util.concurrent.TimeUnit; 292import java.util.concurrent.atomic.AtomicBoolean; 293import java.util.concurrent.atomic.AtomicInteger; 294import java.util.concurrent.atomic.AtomicLong; 295 296/** 297 * Keep track of all those .apks everywhere. 298 * 299 * This is very central to the platform's security; please run the unit 300 * tests whenever making modifications here: 301 * 302runtest -c android.content.pm.PackageManagerTests frameworks-core 303 * 304 * {@hide} 305 */ 306public class PackageManagerService extends IPackageManager.Stub { 307 static final String TAG = "PackageManager"; 308 static final boolean DEBUG_SETTINGS = false; 309 static final boolean DEBUG_PREFERRED = false; 310 static final boolean DEBUG_UPGRADE = false; 311 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 312 private static final boolean DEBUG_BACKUP = false; 313 private static final boolean DEBUG_INSTALL = false; 314 private static final boolean DEBUG_REMOVE = false; 315 private static final boolean DEBUG_BROADCASTS = false; 316 private static final boolean DEBUG_SHOW_INFO = false; 317 private static final boolean DEBUG_PACKAGE_INFO = false; 318 private static final boolean DEBUG_INTENT_MATCHING = false; 319 private static final boolean DEBUG_PACKAGE_SCANNING = false; 320 private static final boolean DEBUG_VERIFY = false; 321 322 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 323 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 324 // user, but by default initialize to this. 325 static final boolean DEBUG_DEXOPT = false; 326 327 private static final boolean DEBUG_ABI_SELECTION = false; 328 private static final boolean DEBUG_EPHEMERAL = false; 329 private static final boolean DEBUG_TRIAGED_MISSING = false; 330 private static final boolean DEBUG_APP_DATA = false; 331 332 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 333 334 private static final boolean DISABLE_EPHEMERAL_APPS = true; 335 336 private static final int RADIO_UID = Process.PHONE_UID; 337 private static final int LOG_UID = Process.LOG_UID; 338 private static final int NFC_UID = Process.NFC_UID; 339 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 340 private static final int SHELL_UID = Process.SHELL_UID; 341 342 // Cap the size of permission trees that 3rd party apps can define 343 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 344 345 // Suffix used during package installation when copying/moving 346 // package apks to install directory. 347 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 348 349 static final int SCAN_NO_DEX = 1<<1; 350 static final int SCAN_FORCE_DEX = 1<<2; 351 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 352 static final int SCAN_NEW_INSTALL = 1<<4; 353 static final int SCAN_NO_PATHS = 1<<5; 354 static final int SCAN_UPDATE_TIME = 1<<6; 355 static final int SCAN_DEFER_DEX = 1<<7; 356 static final int SCAN_BOOTING = 1<<8; 357 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 358 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 359 static final int SCAN_REPLACING = 1<<11; 360 static final int SCAN_REQUIRE_KNOWN = 1<<12; 361 static final int SCAN_MOVE = 1<<13; 362 static final int SCAN_INITIAL = 1<<14; 363 static final int SCAN_CHECK_ONLY = 1<<15; 364 365 static final int REMOVE_CHATTY = 1<<16; 366 367 private static final int[] EMPTY_INT_ARRAY = new int[0]; 368 369 /** 370 * Timeout (in milliseconds) after which the watchdog should declare that 371 * our handler thread is wedged. The usual default for such things is one 372 * minute but we sometimes do very lengthy I/O operations on this thread, 373 * such as installing multi-gigabyte applications, so ours needs to be longer. 374 */ 375 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 376 377 /** 378 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 379 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 380 * settings entry if available, otherwise we use the hardcoded default. If it's been 381 * more than this long since the last fstrim, we force one during the boot sequence. 382 * 383 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 384 * one gets run at the next available charging+idle time. This final mandatory 385 * no-fstrim check kicks in only of the other scheduling criteria is never met. 386 */ 387 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 388 389 /** 390 * Whether verification is enabled by default. 391 */ 392 private static final boolean DEFAULT_VERIFY_ENABLE = true; 393 394 /** 395 * The default maximum time to wait for the verification agent to return in 396 * milliseconds. 397 */ 398 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 399 400 /** 401 * The default response for package verification timeout. 402 * 403 * This can be either PackageManager.VERIFICATION_ALLOW or 404 * PackageManager.VERIFICATION_REJECT. 405 */ 406 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 407 408 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 409 410 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 411 DEFAULT_CONTAINER_PACKAGE, 412 "com.android.defcontainer.DefaultContainerService"); 413 414 private static final String KILL_APP_REASON_GIDS_CHANGED = 415 "permission grant or revoke changed gids"; 416 417 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 418 "permissions revoked"; 419 420 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 421 422 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 423 424 /** Permission grant: not grant the permission. */ 425 private static final int GRANT_DENIED = 1; 426 427 /** Permission grant: grant the permission as an install permission. */ 428 private static final int GRANT_INSTALL = 2; 429 430 /** Permission grant: grant the permission as a runtime one. */ 431 private static final int GRANT_RUNTIME = 3; 432 433 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 434 private static final int GRANT_UPGRADE = 4; 435 436 /** Canonical intent used to identify what counts as a "web browser" app */ 437 private static final Intent sBrowserIntent; 438 static { 439 sBrowserIntent = new Intent(); 440 sBrowserIntent.setAction(Intent.ACTION_VIEW); 441 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 442 sBrowserIntent.setData(Uri.parse("http:")); 443 } 444 445 final ServiceThread mHandlerThread; 446 447 final PackageHandler mHandler; 448 449 /** 450 * Messages for {@link #mHandler} that need to wait for system ready before 451 * being dispatched. 452 */ 453 private ArrayList<Message> mPostSystemReadyMessages; 454 455 final int mSdkVersion = Build.VERSION.SDK_INT; 456 457 final Context mContext; 458 final boolean mFactoryTest; 459 final boolean mOnlyCore; 460 final DisplayMetrics mMetrics; 461 final int mDefParseFlags; 462 final String[] mSeparateProcesses; 463 final boolean mIsUpgrade; 464 465 /** The location for ASEC container files on internal storage. */ 466 final String mAsecInternalPath; 467 468 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 469 // LOCK HELD. Can be called with mInstallLock held. 470 @GuardedBy("mInstallLock") 471 final Installer mInstaller; 472 473 /** Directory where installed third-party apps stored */ 474 final File mAppInstallDir; 475 final File mEphemeralInstallDir; 476 477 /** 478 * Directory to which applications installed internally have their 479 * 32 bit native libraries copied. 480 */ 481 private File mAppLib32InstallDir; 482 483 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 484 // apps. 485 final File mDrmAppPrivateInstallDir; 486 487 // ---------------------------------------------------------------- 488 489 // Lock for state used when installing and doing other long running 490 // operations. Methods that must be called with this lock held have 491 // the suffix "LI". 492 final Object mInstallLock = new Object(); 493 494 // ---------------------------------------------------------------- 495 496 // Keys are String (package name), values are Package. This also serves 497 // as the lock for the global state. Methods that must be called with 498 // this lock held have the prefix "LP". 499 @GuardedBy("mPackages") 500 final ArrayMap<String, PackageParser.Package> mPackages = 501 new ArrayMap<String, PackageParser.Package>(); 502 503 // Tracks available target package names -> overlay package paths. 504 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 505 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 506 507 /** 508 * Tracks new system packages [received in an OTA] that we expect to 509 * find updated user-installed versions. Keys are package name, values 510 * are package location. 511 */ 512 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 513 514 /** 515 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 516 */ 517 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 518 /** 519 * Whether or not system app permissions should be promoted from install to runtime. 520 */ 521 boolean mPromoteSystemApps; 522 523 final Settings mSettings; 524 boolean mRestoredSettings; 525 526 // System configuration read by SystemConfig. 527 final int[] mGlobalGids; 528 final SparseArray<ArraySet<String>> mSystemPermissions; 529 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 530 531 // If mac_permissions.xml was found for seinfo labeling. 532 boolean mFoundPolicyFile; 533 534 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 535 536 public static final class SharedLibraryEntry { 537 public final String path; 538 public final String apk; 539 540 SharedLibraryEntry(String _path, String _apk) { 541 path = _path; 542 apk = _apk; 543 } 544 } 545 546 // Currently known shared libraries. 547 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 548 new ArrayMap<String, SharedLibraryEntry>(); 549 550 // All available activities, for your resolving pleasure. 551 final ActivityIntentResolver mActivities = 552 new ActivityIntentResolver(); 553 554 // All available receivers, for your resolving pleasure. 555 final ActivityIntentResolver mReceivers = 556 new ActivityIntentResolver(); 557 558 // All available services, for your resolving pleasure. 559 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 560 561 // All available providers, for your resolving pleasure. 562 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 563 564 // Mapping from provider base names (first directory in content URI codePath) 565 // to the provider information. 566 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 567 new ArrayMap<String, PackageParser.Provider>(); 568 569 // Mapping from instrumentation class names to info about them. 570 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 571 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 572 573 // Mapping from permission names to info about them. 574 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 575 new ArrayMap<String, PackageParser.PermissionGroup>(); 576 577 // Packages whose data we have transfered into another package, thus 578 // should no longer exist. 579 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 580 581 // Broadcast actions that are only available to the system. 582 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 583 584 /** List of packages waiting for verification. */ 585 final SparseArray<PackageVerificationState> mPendingVerification 586 = new SparseArray<PackageVerificationState>(); 587 588 /** Set of packages associated with each app op permission. */ 589 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 590 591 final PackageInstallerService mInstallerService; 592 593 private final PackageDexOptimizer mPackageDexOptimizer; 594 595 private AtomicInteger mNextMoveId = new AtomicInteger(); 596 private final MoveCallbacks mMoveCallbacks; 597 598 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 599 600 // Cache of users who need badging. 601 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 602 603 /** Token for keys in mPendingVerification. */ 604 private int mPendingVerificationToken = 0; 605 606 volatile boolean mSystemReady; 607 volatile boolean mSafeMode; 608 volatile boolean mHasSystemUidErrors; 609 610 ApplicationInfo mAndroidApplication; 611 final ActivityInfo mResolveActivity = new ActivityInfo(); 612 final ResolveInfo mResolveInfo = new ResolveInfo(); 613 ComponentName mResolveComponentName; 614 PackageParser.Package mPlatformPackage; 615 ComponentName mCustomResolverComponentName; 616 617 boolean mResolverReplaced = false; 618 619 private final @Nullable ComponentName mIntentFilterVerifierComponent; 620 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 621 622 private int mIntentFilterVerificationToken = 0; 623 624 /** Component that knows whether or not an ephemeral application exists */ 625 final ComponentName mEphemeralResolverComponent; 626 /** The service connection to the ephemeral resolver */ 627 final EphemeralResolverConnection mEphemeralResolverConnection; 628 629 /** Component used to install ephemeral applications */ 630 final ComponentName mEphemeralInstallerComponent; 631 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 632 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 633 634 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 635 = new SparseArray<IntentFilterVerificationState>(); 636 637 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 638 new DefaultPermissionGrantPolicy(this); 639 640 // List of packages names to keep cached, even if they are uninstalled for all users 641 private List<String> mKeepUninstalledPackages; 642 643 private boolean mUseJitProfiles = 644 SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false); 645 646 private static class IFVerificationParams { 647 PackageParser.Package pkg; 648 boolean replacing; 649 int userId; 650 int verifierUid; 651 652 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 653 int _userId, int _verifierUid) { 654 pkg = _pkg; 655 replacing = _replacing; 656 userId = _userId; 657 replacing = _replacing; 658 verifierUid = _verifierUid; 659 } 660 } 661 662 private interface IntentFilterVerifier<T extends IntentFilter> { 663 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 664 T filter, String packageName); 665 void startVerifications(int userId); 666 void receiveVerificationResponse(int verificationId); 667 } 668 669 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 670 private Context mContext; 671 private ComponentName mIntentFilterVerifierComponent; 672 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 673 674 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 675 mContext = context; 676 mIntentFilterVerifierComponent = verifierComponent; 677 } 678 679 private String getDefaultScheme() { 680 return IntentFilter.SCHEME_HTTPS; 681 } 682 683 @Override 684 public void startVerifications(int userId) { 685 // Launch verifications requests 686 int count = mCurrentIntentFilterVerifications.size(); 687 for (int n=0; n<count; n++) { 688 int verificationId = mCurrentIntentFilterVerifications.get(n); 689 final IntentFilterVerificationState ivs = 690 mIntentFilterVerificationStates.get(verificationId); 691 692 String packageName = ivs.getPackageName(); 693 694 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 695 final int filterCount = filters.size(); 696 ArraySet<String> domainsSet = new ArraySet<>(); 697 for (int m=0; m<filterCount; m++) { 698 PackageParser.ActivityIntentInfo filter = filters.get(m); 699 domainsSet.addAll(filter.getHostsList()); 700 } 701 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 702 synchronized (mPackages) { 703 if (mSettings.createIntentFilterVerificationIfNeededLPw( 704 packageName, domainsList) != null) { 705 scheduleWriteSettingsLocked(); 706 } 707 } 708 sendVerificationRequest(userId, verificationId, ivs); 709 } 710 mCurrentIntentFilterVerifications.clear(); 711 } 712 713 private void sendVerificationRequest(int userId, int verificationId, 714 IntentFilterVerificationState ivs) { 715 716 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 717 verificationIntent.putExtra( 718 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 719 verificationId); 720 verificationIntent.putExtra( 721 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 722 getDefaultScheme()); 723 verificationIntent.putExtra( 724 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 725 ivs.getHostsString()); 726 verificationIntent.putExtra( 727 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 728 ivs.getPackageName()); 729 verificationIntent.setComponent(mIntentFilterVerifierComponent); 730 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 731 732 UserHandle user = new UserHandle(userId); 733 mContext.sendBroadcastAsUser(verificationIntent, user); 734 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 735 "Sending IntentFilter verification broadcast"); 736 } 737 738 public void receiveVerificationResponse(int verificationId) { 739 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 740 741 final boolean verified = ivs.isVerified(); 742 743 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 744 final int count = filters.size(); 745 if (DEBUG_DOMAIN_VERIFICATION) { 746 Slog.i(TAG, "Received verification response " + verificationId 747 + " for " + count + " filters, verified=" + verified); 748 } 749 for (int n=0; n<count; n++) { 750 PackageParser.ActivityIntentInfo filter = filters.get(n); 751 filter.setVerified(verified); 752 753 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 754 + " verified with result:" + verified + " and hosts:" 755 + ivs.getHostsString()); 756 } 757 758 mIntentFilterVerificationStates.remove(verificationId); 759 760 final String packageName = ivs.getPackageName(); 761 IntentFilterVerificationInfo ivi = null; 762 763 synchronized (mPackages) { 764 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 765 } 766 if (ivi == null) { 767 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 768 + verificationId + " packageName:" + packageName); 769 return; 770 } 771 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 772 "Updating IntentFilterVerificationInfo for package " + packageName 773 +" verificationId:" + verificationId); 774 775 synchronized (mPackages) { 776 if (verified) { 777 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 778 } else { 779 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 780 } 781 scheduleWriteSettingsLocked(); 782 783 final int userId = ivs.getUserId(); 784 if (userId != UserHandle.USER_ALL) { 785 final int userStatus = 786 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 787 788 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 789 boolean needUpdate = false; 790 791 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 792 // already been set by the User thru the Disambiguation dialog 793 switch (userStatus) { 794 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 795 if (verified) { 796 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 797 } else { 798 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 799 } 800 needUpdate = true; 801 break; 802 803 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 804 if (verified) { 805 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 806 needUpdate = true; 807 } 808 break; 809 810 default: 811 // Nothing to do 812 } 813 814 if (needUpdate) { 815 mSettings.updateIntentFilterVerificationStatusLPw( 816 packageName, updatedStatus, userId); 817 scheduleWritePackageRestrictionsLocked(userId); 818 } 819 } 820 } 821 } 822 823 @Override 824 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 825 ActivityIntentInfo filter, String packageName) { 826 if (!hasValidDomains(filter)) { 827 return false; 828 } 829 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 830 if (ivs == null) { 831 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 832 packageName); 833 } 834 if (DEBUG_DOMAIN_VERIFICATION) { 835 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 836 } 837 ivs.addFilter(filter); 838 return true; 839 } 840 841 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 842 int userId, int verificationId, String packageName) { 843 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 844 verifierUid, userId, packageName); 845 ivs.setPendingState(); 846 synchronized (mPackages) { 847 mIntentFilterVerificationStates.append(verificationId, ivs); 848 mCurrentIntentFilterVerifications.add(verificationId); 849 } 850 return ivs; 851 } 852 } 853 854 private static boolean hasValidDomains(ActivityIntentInfo filter) { 855 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 856 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 857 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 858 } 859 860 // Set of pending broadcasts for aggregating enable/disable of components. 861 static class PendingPackageBroadcasts { 862 // for each user id, a map of <package name -> components within that package> 863 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 864 865 public PendingPackageBroadcasts() { 866 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 867 } 868 869 public ArrayList<String> get(int userId, String packageName) { 870 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 871 return packages.get(packageName); 872 } 873 874 public void put(int userId, String packageName, ArrayList<String> components) { 875 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 876 packages.put(packageName, components); 877 } 878 879 public void remove(int userId, String packageName) { 880 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 881 if (packages != null) { 882 packages.remove(packageName); 883 } 884 } 885 886 public void remove(int userId) { 887 mUidMap.remove(userId); 888 } 889 890 public int userIdCount() { 891 return mUidMap.size(); 892 } 893 894 public int userIdAt(int n) { 895 return mUidMap.keyAt(n); 896 } 897 898 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 899 return mUidMap.get(userId); 900 } 901 902 public int size() { 903 // total number of pending broadcast entries across all userIds 904 int num = 0; 905 for (int i = 0; i< mUidMap.size(); i++) { 906 num += mUidMap.valueAt(i).size(); 907 } 908 return num; 909 } 910 911 public void clear() { 912 mUidMap.clear(); 913 } 914 915 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 916 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 917 if (map == null) { 918 map = new ArrayMap<String, ArrayList<String>>(); 919 mUidMap.put(userId, map); 920 } 921 return map; 922 } 923 } 924 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 925 926 // Service Connection to remote media container service to copy 927 // package uri's from external media onto secure containers 928 // or internal storage. 929 private IMediaContainerService mContainerService = null; 930 931 static final int SEND_PENDING_BROADCAST = 1; 932 static final int MCS_BOUND = 3; 933 static final int END_COPY = 4; 934 static final int INIT_COPY = 5; 935 static final int MCS_UNBIND = 6; 936 static final int START_CLEANING_PACKAGE = 7; 937 static final int FIND_INSTALL_LOC = 8; 938 static final int POST_INSTALL = 9; 939 static final int MCS_RECONNECT = 10; 940 static final int MCS_GIVE_UP = 11; 941 static final int UPDATED_MEDIA_STATUS = 12; 942 static final int WRITE_SETTINGS = 13; 943 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 944 static final int PACKAGE_VERIFIED = 15; 945 static final int CHECK_PENDING_VERIFICATION = 16; 946 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 947 static final int INTENT_FILTER_VERIFIED = 18; 948 949 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 950 951 // Delay time in millisecs 952 static final int BROADCAST_DELAY = 10 * 1000; 953 954 static UserManagerService sUserManager; 955 956 // Stores a list of users whose package restrictions file needs to be updated 957 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 958 959 final private DefaultContainerConnection mDefContainerConn = 960 new DefaultContainerConnection(); 961 class DefaultContainerConnection implements ServiceConnection { 962 public void onServiceConnected(ComponentName name, IBinder service) { 963 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 964 IMediaContainerService imcs = 965 IMediaContainerService.Stub.asInterface(service); 966 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 967 } 968 969 public void onServiceDisconnected(ComponentName name) { 970 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 971 } 972 } 973 974 // Recordkeeping of restore-after-install operations that are currently in flight 975 // between the Package Manager and the Backup Manager 976 static class PostInstallData { 977 public InstallArgs args; 978 public PackageInstalledInfo res; 979 980 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 981 args = _a; 982 res = _r; 983 } 984 } 985 986 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 987 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 988 989 // XML tags for backup/restore of various bits of state 990 private static final String TAG_PREFERRED_BACKUP = "pa"; 991 private static final String TAG_DEFAULT_APPS = "da"; 992 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 993 994 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 995 private static final String TAG_ALL_GRANTS = "rt-grants"; 996 private static final String TAG_GRANT = "grant"; 997 private static final String ATTR_PACKAGE_NAME = "pkg"; 998 999 private static final String TAG_PERMISSION = "perm"; 1000 private static final String ATTR_PERMISSION_NAME = "name"; 1001 private static final String ATTR_IS_GRANTED = "g"; 1002 private static final String ATTR_USER_SET = "set"; 1003 private static final String ATTR_USER_FIXED = "fixed"; 1004 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1005 1006 // System/policy permission grants are not backed up 1007 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1008 FLAG_PERMISSION_POLICY_FIXED 1009 | FLAG_PERMISSION_SYSTEM_FIXED 1010 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1011 1012 // And we back up these user-adjusted states 1013 private static final int USER_RUNTIME_GRANT_MASK = 1014 FLAG_PERMISSION_USER_SET 1015 | FLAG_PERMISSION_USER_FIXED 1016 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1017 1018 final @Nullable String mRequiredVerifierPackage; 1019 final @Nullable String mRequiredInstallerPackage; 1020 1021 private final PackageUsage mPackageUsage = new PackageUsage(); 1022 1023 private class PackageUsage { 1024 private static final int WRITE_INTERVAL 1025 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1026 1027 private final Object mFileLock = new Object(); 1028 private final AtomicLong mLastWritten = new AtomicLong(0); 1029 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1030 1031 private boolean mIsHistoricalPackageUsageAvailable = true; 1032 1033 boolean isHistoricalPackageUsageAvailable() { 1034 return mIsHistoricalPackageUsageAvailable; 1035 } 1036 1037 void write(boolean force) { 1038 if (force) { 1039 writeInternal(); 1040 return; 1041 } 1042 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1043 && !DEBUG_DEXOPT) { 1044 return; 1045 } 1046 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1047 new Thread("PackageUsage_DiskWriter") { 1048 @Override 1049 public void run() { 1050 try { 1051 writeInternal(); 1052 } finally { 1053 mBackgroundWriteRunning.set(false); 1054 } 1055 } 1056 }.start(); 1057 } 1058 } 1059 1060 private void writeInternal() { 1061 synchronized (mPackages) { 1062 synchronized (mFileLock) { 1063 AtomicFile file = getFile(); 1064 FileOutputStream f = null; 1065 try { 1066 f = file.startWrite(); 1067 BufferedOutputStream out = new BufferedOutputStream(f); 1068 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1069 StringBuilder sb = new StringBuilder(); 1070 for (PackageParser.Package pkg : mPackages.values()) { 1071 if (pkg.mLastPackageUsageTimeInMills == 0) { 1072 continue; 1073 } 1074 sb.setLength(0); 1075 sb.append(pkg.packageName); 1076 sb.append(' '); 1077 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1078 sb.append('\n'); 1079 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1080 } 1081 out.flush(); 1082 file.finishWrite(f); 1083 } catch (IOException e) { 1084 if (f != null) { 1085 file.failWrite(f); 1086 } 1087 Log.e(TAG, "Failed to write package usage times", e); 1088 } 1089 } 1090 } 1091 mLastWritten.set(SystemClock.elapsedRealtime()); 1092 } 1093 1094 void readLP() { 1095 synchronized (mFileLock) { 1096 AtomicFile file = getFile(); 1097 BufferedInputStream in = null; 1098 try { 1099 in = new BufferedInputStream(file.openRead()); 1100 StringBuffer sb = new StringBuffer(); 1101 while (true) { 1102 String packageName = readToken(in, sb, ' '); 1103 if (packageName == null) { 1104 break; 1105 } 1106 String timeInMillisString = readToken(in, sb, '\n'); 1107 if (timeInMillisString == null) { 1108 throw new IOException("Failed to find last usage time for package " 1109 + packageName); 1110 } 1111 PackageParser.Package pkg = mPackages.get(packageName); 1112 if (pkg == null) { 1113 continue; 1114 } 1115 long timeInMillis; 1116 try { 1117 timeInMillis = Long.parseLong(timeInMillisString); 1118 } catch (NumberFormatException e) { 1119 throw new IOException("Failed to parse " + timeInMillisString 1120 + " as a long.", e); 1121 } 1122 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1123 } 1124 } catch (FileNotFoundException expected) { 1125 mIsHistoricalPackageUsageAvailable = false; 1126 } catch (IOException e) { 1127 Log.w(TAG, "Failed to read package usage times", e); 1128 } finally { 1129 IoUtils.closeQuietly(in); 1130 } 1131 } 1132 mLastWritten.set(SystemClock.elapsedRealtime()); 1133 } 1134 1135 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1136 throws IOException { 1137 sb.setLength(0); 1138 while (true) { 1139 int ch = in.read(); 1140 if (ch == -1) { 1141 if (sb.length() == 0) { 1142 return null; 1143 } 1144 throw new IOException("Unexpected EOF"); 1145 } 1146 if (ch == endOfToken) { 1147 return sb.toString(); 1148 } 1149 sb.append((char)ch); 1150 } 1151 } 1152 1153 private AtomicFile getFile() { 1154 File dataDir = Environment.getDataDirectory(); 1155 File systemDir = new File(dataDir, "system"); 1156 File fname = new File(systemDir, "package-usage.list"); 1157 return new AtomicFile(fname); 1158 } 1159 } 1160 1161 class PackageHandler extends Handler { 1162 private boolean mBound = false; 1163 final ArrayList<HandlerParams> mPendingInstalls = 1164 new ArrayList<HandlerParams>(); 1165 1166 private boolean connectToService() { 1167 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1168 " DefaultContainerService"); 1169 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1170 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1171 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1172 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1173 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1174 mBound = true; 1175 return true; 1176 } 1177 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1178 return false; 1179 } 1180 1181 private void disconnectService() { 1182 mContainerService = null; 1183 mBound = false; 1184 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1185 mContext.unbindService(mDefContainerConn); 1186 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1187 } 1188 1189 PackageHandler(Looper looper) { 1190 super(looper); 1191 } 1192 1193 public void handleMessage(Message msg) { 1194 try { 1195 doHandleMessage(msg); 1196 } finally { 1197 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1198 } 1199 } 1200 1201 void doHandleMessage(Message msg) { 1202 switch (msg.what) { 1203 case INIT_COPY: { 1204 HandlerParams params = (HandlerParams) msg.obj; 1205 int idx = mPendingInstalls.size(); 1206 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1207 // If a bind was already initiated we dont really 1208 // need to do anything. The pending install 1209 // will be processed later on. 1210 if (!mBound) { 1211 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1212 System.identityHashCode(mHandler)); 1213 // If this is the only one pending we might 1214 // have to bind to the service again. 1215 if (!connectToService()) { 1216 Slog.e(TAG, "Failed to bind to media container service"); 1217 params.serviceError(); 1218 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1219 System.identityHashCode(mHandler)); 1220 if (params.traceMethod != null) { 1221 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1222 params.traceCookie); 1223 } 1224 return; 1225 } else { 1226 // Once we bind to the service, the first 1227 // pending request will be processed. 1228 mPendingInstalls.add(idx, params); 1229 } 1230 } else { 1231 mPendingInstalls.add(idx, params); 1232 // Already bound to the service. Just make 1233 // sure we trigger off processing the first request. 1234 if (idx == 0) { 1235 mHandler.sendEmptyMessage(MCS_BOUND); 1236 } 1237 } 1238 break; 1239 } 1240 case MCS_BOUND: { 1241 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1242 if (msg.obj != null) { 1243 mContainerService = (IMediaContainerService) msg.obj; 1244 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1245 System.identityHashCode(mHandler)); 1246 } 1247 if (mContainerService == null) { 1248 if (!mBound) { 1249 // Something seriously wrong since we are not bound and we are not 1250 // waiting for connection. Bail out. 1251 Slog.e(TAG, "Cannot bind to media container service"); 1252 for (HandlerParams params : mPendingInstalls) { 1253 // Indicate service bind error 1254 params.serviceError(); 1255 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1256 System.identityHashCode(params)); 1257 if (params.traceMethod != null) { 1258 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1259 params.traceMethod, params.traceCookie); 1260 } 1261 return; 1262 } 1263 mPendingInstalls.clear(); 1264 } else { 1265 Slog.w(TAG, "Waiting to connect to media container service"); 1266 } 1267 } else if (mPendingInstalls.size() > 0) { 1268 HandlerParams params = mPendingInstalls.get(0); 1269 if (params != null) { 1270 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1271 System.identityHashCode(params)); 1272 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1273 if (params.startCopy()) { 1274 // We are done... look for more work or to 1275 // go idle. 1276 if (DEBUG_SD_INSTALL) Log.i(TAG, 1277 "Checking for more work or unbind..."); 1278 // Delete pending install 1279 if (mPendingInstalls.size() > 0) { 1280 mPendingInstalls.remove(0); 1281 } 1282 if (mPendingInstalls.size() == 0) { 1283 if (mBound) { 1284 if (DEBUG_SD_INSTALL) Log.i(TAG, 1285 "Posting delayed MCS_UNBIND"); 1286 removeMessages(MCS_UNBIND); 1287 Message ubmsg = obtainMessage(MCS_UNBIND); 1288 // Unbind after a little delay, to avoid 1289 // continual thrashing. 1290 sendMessageDelayed(ubmsg, 10000); 1291 } 1292 } else { 1293 // There are more pending requests in queue. 1294 // Just post MCS_BOUND message to trigger processing 1295 // of next pending install. 1296 if (DEBUG_SD_INSTALL) Log.i(TAG, 1297 "Posting MCS_BOUND for next work"); 1298 mHandler.sendEmptyMessage(MCS_BOUND); 1299 } 1300 } 1301 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1302 } 1303 } else { 1304 // Should never happen ideally. 1305 Slog.w(TAG, "Empty queue"); 1306 } 1307 break; 1308 } 1309 case MCS_RECONNECT: { 1310 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1311 if (mPendingInstalls.size() > 0) { 1312 if (mBound) { 1313 disconnectService(); 1314 } 1315 if (!connectToService()) { 1316 Slog.e(TAG, "Failed to bind to media container service"); 1317 for (HandlerParams params : mPendingInstalls) { 1318 // Indicate service bind error 1319 params.serviceError(); 1320 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1321 System.identityHashCode(params)); 1322 } 1323 mPendingInstalls.clear(); 1324 } 1325 } 1326 break; 1327 } 1328 case MCS_UNBIND: { 1329 // If there is no actual work left, then time to unbind. 1330 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1331 1332 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1333 if (mBound) { 1334 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1335 1336 disconnectService(); 1337 } 1338 } else if (mPendingInstalls.size() > 0) { 1339 // There are more pending requests in queue. 1340 // Just post MCS_BOUND message to trigger processing 1341 // of next pending install. 1342 mHandler.sendEmptyMessage(MCS_BOUND); 1343 } 1344 1345 break; 1346 } 1347 case MCS_GIVE_UP: { 1348 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1349 HandlerParams params = mPendingInstalls.remove(0); 1350 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1351 System.identityHashCode(params)); 1352 break; 1353 } 1354 case SEND_PENDING_BROADCAST: { 1355 String packages[]; 1356 ArrayList<String> components[]; 1357 int size = 0; 1358 int uids[]; 1359 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1360 synchronized (mPackages) { 1361 if (mPendingBroadcasts == null) { 1362 return; 1363 } 1364 size = mPendingBroadcasts.size(); 1365 if (size <= 0) { 1366 // Nothing to be done. Just return 1367 return; 1368 } 1369 packages = new String[size]; 1370 components = new ArrayList[size]; 1371 uids = new int[size]; 1372 int i = 0; // filling out the above arrays 1373 1374 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1375 int packageUserId = mPendingBroadcasts.userIdAt(n); 1376 Iterator<Map.Entry<String, ArrayList<String>>> it 1377 = mPendingBroadcasts.packagesForUserId(packageUserId) 1378 .entrySet().iterator(); 1379 while (it.hasNext() && i < size) { 1380 Map.Entry<String, ArrayList<String>> ent = it.next(); 1381 packages[i] = ent.getKey(); 1382 components[i] = ent.getValue(); 1383 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1384 uids[i] = (ps != null) 1385 ? UserHandle.getUid(packageUserId, ps.appId) 1386 : -1; 1387 i++; 1388 } 1389 } 1390 size = i; 1391 mPendingBroadcasts.clear(); 1392 } 1393 // Send broadcasts 1394 for (int i = 0; i < size; i++) { 1395 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1396 } 1397 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1398 break; 1399 } 1400 case START_CLEANING_PACKAGE: { 1401 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1402 final String packageName = (String)msg.obj; 1403 final int userId = msg.arg1; 1404 final boolean andCode = msg.arg2 != 0; 1405 synchronized (mPackages) { 1406 if (userId == UserHandle.USER_ALL) { 1407 int[] users = sUserManager.getUserIds(); 1408 for (int user : users) { 1409 mSettings.addPackageToCleanLPw( 1410 new PackageCleanItem(user, packageName, andCode)); 1411 } 1412 } else { 1413 mSettings.addPackageToCleanLPw( 1414 new PackageCleanItem(userId, packageName, andCode)); 1415 } 1416 } 1417 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1418 startCleaningPackages(); 1419 } break; 1420 case POST_INSTALL: { 1421 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1422 1423 PostInstallData data = mRunningInstalls.get(msg.arg1); 1424 mRunningInstalls.delete(msg.arg1); 1425 boolean deleteOld = false; 1426 1427 if (data != null) { 1428 InstallArgs args = data.args; 1429 PackageInstalledInfo res = data.res; 1430 1431 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1432 //TODO: Broadcast for child packages too 1433 final String packageName = res.pkg.applicationInfo.packageName; 1434 res.removedInfo.sendBroadcast(false, true, false); 1435 Bundle extras = new Bundle(1); 1436 extras.putInt(Intent.EXTRA_UID, res.uid); 1437 1438 // Now that we successfully installed the package, grant runtime 1439 // permissions if requested before broadcasting the install. 1440 if ((args.installFlags 1441 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 1442 && res.pkg.applicationInfo.targetSdkVersion 1443 >= Build.VERSION_CODES.M) { 1444 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1445 args.installGrantPermissions); 1446 } 1447 1448 synchronized (mPackages) { 1449 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1450 } 1451 1452 // Determine the set of users who are adding this 1453 // package for the first time vs. those who are seeing 1454 // an update. 1455 int[] firstUsers; 1456 int[] updateUsers = new int[0]; 1457 if (res.origUsers == null || res.origUsers.length == 0) { 1458 firstUsers = res.newUsers; 1459 } else { 1460 firstUsers = new int[0]; 1461 for (int i=0; i<res.newUsers.length; i++) { 1462 int user = res.newUsers[i]; 1463 boolean isNew = true; 1464 for (int j=0; j<res.origUsers.length; j++) { 1465 if (res.origUsers[j] == user) { 1466 isNew = false; 1467 break; 1468 } 1469 } 1470 if (isNew) { 1471 int[] newFirst = new int[firstUsers.length+1]; 1472 System.arraycopy(firstUsers, 0, newFirst, 0, 1473 firstUsers.length); 1474 newFirst[firstUsers.length] = user; 1475 firstUsers = newFirst; 1476 } else { 1477 int[] newUpdate = new int[updateUsers.length+1]; 1478 System.arraycopy(updateUsers, 0, newUpdate, 0, 1479 updateUsers.length); 1480 newUpdate[updateUsers.length] = user; 1481 updateUsers = newUpdate; 1482 } 1483 } 1484 } 1485 // don't broadcast for ephemeral installs/updates 1486 final boolean isEphemeral = isEphemeral(res.pkg); 1487 if (!isEphemeral) { 1488 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1489 extras, 0 /*flags*/, null /*targetPackage*/, 1490 null /*finishedReceiver*/, firstUsers); 1491 } 1492 final boolean update = res.removedInfo.removedPackage != null; 1493 if (update) { 1494 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1495 } 1496 if (!isEphemeral) { 1497 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1498 extras, 0 /*flags*/, null /*targetPackage*/, 1499 null /*finishedReceiver*/, updateUsers); 1500 } 1501 if (update) { 1502 if (!isEphemeral) { 1503 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1504 packageName, extras, 0 /*flags*/, 1505 null /*targetPackage*/, null /*finishedReceiver*/, 1506 updateUsers); 1507 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1508 null /*package*/, null /*extras*/, 0 /*flags*/, 1509 packageName /*targetPackage*/, 1510 null /*finishedReceiver*/, updateUsers); 1511 } 1512 1513 // treat asec-hosted packages like removable media on upgrade 1514 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1515 if (DEBUG_INSTALL) { 1516 Slog.i(TAG, "upgrading pkg " + res.pkg 1517 + " is ASEC-hosted -> AVAILABLE"); 1518 } 1519 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1520 ArrayList<String> pkgList = new ArrayList<String>(1); 1521 pkgList.add(packageName); 1522 sendResourcesChangedBroadcast(true, true, 1523 pkgList,uidArray, null); 1524 } 1525 } 1526 if (res.removedInfo.args != null) { 1527 // Remove the replaced package's older resources safely now 1528 deleteOld = true; 1529 } 1530 1531 1532 // Work that needs to happen on first install within each user 1533 if (firstUsers.length > 0) { 1534 for (int userId : firstUsers) { 1535 synchronized (mPackages) { 1536 // If this app is a browser and it's newly-installed for 1537 // some users, clear any default-browser state in those 1538 // users. The app's nature doesn't depend on the user, 1539 // so we can just check its browser nature in any user 1540 // and generalize. 1541 if (packageIsBrowser(packageName, firstUsers[0])) { 1542 mSettings.setDefaultBrowserPackageNameLPw( 1543 null, userId); 1544 } 1545 1546 // We may also need to apply pending (restored) runtime 1547 // permission grants within these users. 1548 mSettings.applyPendingPermissionGrantsLPw( 1549 packageName, userId); 1550 } 1551 } 1552 } 1553 // Log current value of "unknown sources" setting 1554 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1555 getUnknownSourcesSettings()); 1556 } 1557 // Force a gc to clear up things 1558 Runtime.getRuntime().gc(); 1559 // We delete after a gc for applications on sdcard. 1560 if (deleteOld) { 1561 synchronized (mInstallLock) { 1562 res.removedInfo.args.doPostDeleteLI(true); 1563 } 1564 } 1565 if (args.observer != null) { 1566 try { 1567 Bundle extras = extrasForInstallResult(res); 1568 args.observer.onPackageInstalled(res.name, res.returnCode, 1569 res.returnMsg, extras); 1570 } catch (RemoteException e) { 1571 Slog.i(TAG, "Observer no longer exists."); 1572 } 1573 } 1574 if (args.traceMethod != null) { 1575 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1576 args.traceCookie); 1577 } 1578 return; 1579 } else { 1580 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1581 } 1582 1583 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1584 } break; 1585 case UPDATED_MEDIA_STATUS: { 1586 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1587 boolean reportStatus = msg.arg1 == 1; 1588 boolean doGc = msg.arg2 == 1; 1589 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1590 if (doGc) { 1591 // Force a gc to clear up stale containers. 1592 Runtime.getRuntime().gc(); 1593 } 1594 if (msg.obj != null) { 1595 @SuppressWarnings("unchecked") 1596 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1597 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1598 // Unload containers 1599 unloadAllContainers(args); 1600 } 1601 if (reportStatus) { 1602 try { 1603 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1604 PackageHelper.getMountService().finishMediaUpdate(); 1605 } catch (RemoteException e) { 1606 Log.e(TAG, "MountService not running?"); 1607 } 1608 } 1609 } break; 1610 case WRITE_SETTINGS: { 1611 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1612 synchronized (mPackages) { 1613 removeMessages(WRITE_SETTINGS); 1614 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1615 mSettings.writeLPr(); 1616 mDirtyUsers.clear(); 1617 } 1618 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1619 } break; 1620 case WRITE_PACKAGE_RESTRICTIONS: { 1621 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1622 synchronized (mPackages) { 1623 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1624 for (int userId : mDirtyUsers) { 1625 mSettings.writePackageRestrictionsLPr(userId); 1626 } 1627 mDirtyUsers.clear(); 1628 } 1629 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1630 } break; 1631 case CHECK_PENDING_VERIFICATION: { 1632 final int verificationId = msg.arg1; 1633 final PackageVerificationState state = mPendingVerification.get(verificationId); 1634 1635 if ((state != null) && !state.timeoutExtended()) { 1636 final InstallArgs args = state.getInstallArgs(); 1637 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1638 1639 Slog.i(TAG, "Verification timed out for " + originUri); 1640 mPendingVerification.remove(verificationId); 1641 1642 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1643 1644 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1645 Slog.i(TAG, "Continuing with installation of " + originUri); 1646 state.setVerifierResponse(Binder.getCallingUid(), 1647 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1648 broadcastPackageVerified(verificationId, originUri, 1649 PackageManager.VERIFICATION_ALLOW, 1650 state.getInstallArgs().getUser()); 1651 try { 1652 ret = args.copyApk(mContainerService, true); 1653 } catch (RemoteException e) { 1654 Slog.e(TAG, "Could not contact the ContainerService"); 1655 } 1656 } else { 1657 broadcastPackageVerified(verificationId, originUri, 1658 PackageManager.VERIFICATION_REJECT, 1659 state.getInstallArgs().getUser()); 1660 } 1661 1662 Trace.asyncTraceEnd( 1663 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1664 1665 processPendingInstall(args, ret); 1666 mHandler.sendEmptyMessage(MCS_UNBIND); 1667 } 1668 break; 1669 } 1670 case PACKAGE_VERIFIED: { 1671 final int verificationId = msg.arg1; 1672 1673 final PackageVerificationState state = mPendingVerification.get(verificationId); 1674 if (state == null) { 1675 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1676 break; 1677 } 1678 1679 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1680 1681 state.setVerifierResponse(response.callerUid, response.code); 1682 1683 if (state.isVerificationComplete()) { 1684 mPendingVerification.remove(verificationId); 1685 1686 final InstallArgs args = state.getInstallArgs(); 1687 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1688 1689 int ret; 1690 if (state.isInstallAllowed()) { 1691 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1692 broadcastPackageVerified(verificationId, originUri, 1693 response.code, state.getInstallArgs().getUser()); 1694 try { 1695 ret = args.copyApk(mContainerService, true); 1696 } catch (RemoteException e) { 1697 Slog.e(TAG, "Could not contact the ContainerService"); 1698 } 1699 } else { 1700 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1701 } 1702 1703 Trace.asyncTraceEnd( 1704 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1705 1706 processPendingInstall(args, ret); 1707 mHandler.sendEmptyMessage(MCS_UNBIND); 1708 } 1709 1710 break; 1711 } 1712 case START_INTENT_FILTER_VERIFICATIONS: { 1713 IFVerificationParams params = (IFVerificationParams) msg.obj; 1714 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1715 params.replacing, params.pkg); 1716 break; 1717 } 1718 case INTENT_FILTER_VERIFIED: { 1719 final int verificationId = msg.arg1; 1720 1721 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1722 verificationId); 1723 if (state == null) { 1724 Slog.w(TAG, "Invalid IntentFilter verification token " 1725 + verificationId + " received"); 1726 break; 1727 } 1728 1729 final int userId = state.getUserId(); 1730 1731 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1732 "Processing IntentFilter verification with token:" 1733 + verificationId + " and userId:" + userId); 1734 1735 final IntentFilterVerificationResponse response = 1736 (IntentFilterVerificationResponse) msg.obj; 1737 1738 state.setVerifierResponse(response.callerUid, response.code); 1739 1740 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1741 "IntentFilter verification with token:" + verificationId 1742 + " and userId:" + userId 1743 + " is settings verifier response with response code:" 1744 + response.code); 1745 1746 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1747 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1748 + response.getFailedDomainsString()); 1749 } 1750 1751 if (state.isVerificationComplete()) { 1752 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1753 } else { 1754 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1755 "IntentFilter verification with token:" + verificationId 1756 + " was not said to be complete"); 1757 } 1758 1759 break; 1760 } 1761 } 1762 } 1763 } 1764 1765 private StorageEventListener mStorageListener = new StorageEventListener() { 1766 @Override 1767 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1768 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1769 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1770 final String volumeUuid = vol.getFsUuid(); 1771 1772 // Clean up any users or apps that were removed or recreated 1773 // while this volume was missing 1774 reconcileUsers(volumeUuid); 1775 reconcileApps(volumeUuid); 1776 1777 // Clean up any install sessions that expired or were 1778 // cancelled while this volume was missing 1779 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1780 1781 loadPrivatePackages(vol); 1782 1783 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1784 unloadPrivatePackages(vol); 1785 } 1786 } 1787 1788 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1789 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1790 updateExternalMediaStatus(true, false); 1791 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1792 updateExternalMediaStatus(false, false); 1793 } 1794 } 1795 } 1796 1797 @Override 1798 public void onVolumeForgotten(String fsUuid) { 1799 if (TextUtils.isEmpty(fsUuid)) { 1800 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1801 return; 1802 } 1803 1804 // Remove any apps installed on the forgotten volume 1805 synchronized (mPackages) { 1806 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1807 for (PackageSetting ps : packages) { 1808 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1809 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1810 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1811 } 1812 1813 mSettings.onVolumeForgotten(fsUuid); 1814 mSettings.writeLPr(); 1815 } 1816 } 1817 }; 1818 1819 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1820 String[] grantedPermissions) { 1821 if (userId >= UserHandle.USER_SYSTEM) { 1822 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1823 } else if (userId == UserHandle.USER_ALL) { 1824 final int[] userIds; 1825 synchronized (mPackages) { 1826 userIds = UserManagerService.getInstance().getUserIds(); 1827 } 1828 for (int someUserId : userIds) { 1829 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1830 } 1831 } 1832 1833 // We could have touched GID membership, so flush out packages.list 1834 synchronized (mPackages) { 1835 mSettings.writePackageListLPr(); 1836 } 1837 } 1838 1839 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1840 String[] grantedPermissions) { 1841 SettingBase sb = (SettingBase) pkg.mExtras; 1842 if (sb == null) { 1843 return; 1844 } 1845 1846 PermissionsState permissionsState = sb.getPermissionsState(); 1847 1848 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1849 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1850 1851 synchronized (mPackages) { 1852 for (String permission : pkg.requestedPermissions) { 1853 BasePermission bp = mSettings.mPermissions.get(permission); 1854 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1855 && (grantedPermissions == null 1856 || ArrayUtils.contains(grantedPermissions, permission))) { 1857 final int flags = permissionsState.getPermissionFlags(permission, userId); 1858 // Installer cannot change immutable permissions. 1859 if ((flags & immutableFlags) == 0) { 1860 grantRuntimePermission(pkg.packageName, permission, userId); 1861 } 1862 } 1863 } 1864 } 1865 } 1866 1867 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1868 Bundle extras = null; 1869 switch (res.returnCode) { 1870 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1871 extras = new Bundle(); 1872 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1873 res.origPermission); 1874 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1875 res.origPackage); 1876 break; 1877 } 1878 case PackageManager.INSTALL_SUCCEEDED: { 1879 extras = new Bundle(); 1880 extras.putBoolean(Intent.EXTRA_REPLACING, 1881 res.removedInfo != null && res.removedInfo.removedPackage != null); 1882 break; 1883 } 1884 } 1885 return extras; 1886 } 1887 1888 void scheduleWriteSettingsLocked() { 1889 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1890 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1891 } 1892 } 1893 1894 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1895 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1896 scheduleWritePackageRestrictionsLocked(userId); 1897 } 1898 1899 void scheduleWritePackageRestrictionsLocked(int userId) { 1900 final int[] userIds = (userId == UserHandle.USER_ALL) 1901 ? sUserManager.getUserIds() : new int[]{userId}; 1902 for (int nextUserId : userIds) { 1903 if (!sUserManager.exists(nextUserId)) return; 1904 mDirtyUsers.add(nextUserId); 1905 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1906 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1907 } 1908 } 1909 } 1910 1911 public static PackageManagerService main(Context context, Installer installer, 1912 boolean factoryTest, boolean onlyCore) { 1913 PackageManagerService m = new PackageManagerService(context, installer, 1914 factoryTest, onlyCore); 1915 m.enableSystemUserPackages(); 1916 ServiceManager.addService("package", m); 1917 return m; 1918 } 1919 1920 private void enableSystemUserPackages() { 1921 if (!UserManager.isSplitSystemUser()) { 1922 return; 1923 } 1924 // For system user, enable apps based on the following conditions: 1925 // - app is whitelisted or belong to one of these groups: 1926 // -- system app which has no launcher icons 1927 // -- system app which has INTERACT_ACROSS_USERS permission 1928 // -- system IME app 1929 // - app is not in the blacklist 1930 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1931 Set<String> enableApps = new ArraySet<>(); 1932 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1933 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1934 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1935 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1936 enableApps.addAll(wlApps); 1937 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1938 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1939 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1940 enableApps.removeAll(blApps); 1941 Log.i(TAG, "Applications installed for system user: " + enableApps); 1942 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1943 UserHandle.SYSTEM); 1944 final int allAppsSize = allAps.size(); 1945 synchronized (mPackages) { 1946 for (int i = 0; i < allAppsSize; i++) { 1947 String pName = allAps.get(i); 1948 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1949 // Should not happen, but we shouldn't be failing if it does 1950 if (pkgSetting == null) { 1951 continue; 1952 } 1953 boolean install = enableApps.contains(pName); 1954 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 1955 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 1956 + " for system user"); 1957 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 1958 } 1959 } 1960 } 1961 } 1962 1963 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1964 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1965 Context.DISPLAY_SERVICE); 1966 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1967 } 1968 1969 public PackageManagerService(Context context, Installer installer, 1970 boolean factoryTest, boolean onlyCore) { 1971 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1972 SystemClock.uptimeMillis()); 1973 1974 if (mSdkVersion <= 0) { 1975 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1976 } 1977 1978 mContext = context; 1979 mFactoryTest = factoryTest; 1980 mOnlyCore = onlyCore; 1981 mMetrics = new DisplayMetrics(); 1982 mSettings = new Settings(mPackages); 1983 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1984 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1985 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1986 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1987 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1988 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1989 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1990 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1991 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1992 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1993 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1994 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1995 1996 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1997 if (separateProcesses != null && separateProcesses.length() > 0) { 1998 if ("*".equals(separateProcesses)) { 1999 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2000 mSeparateProcesses = null; 2001 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2002 } else { 2003 mDefParseFlags = 0; 2004 mSeparateProcesses = separateProcesses.split(","); 2005 Slog.w(TAG, "Running with debug.separate_processes: " 2006 + separateProcesses); 2007 } 2008 } else { 2009 mDefParseFlags = 0; 2010 mSeparateProcesses = null; 2011 } 2012 2013 mInstaller = installer; 2014 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2015 "*dexopt*"); 2016 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2017 2018 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2019 FgThread.get().getLooper()); 2020 2021 getDefaultDisplayMetrics(context, mMetrics); 2022 2023 SystemConfig systemConfig = SystemConfig.getInstance(); 2024 mGlobalGids = systemConfig.getGlobalGids(); 2025 mSystemPermissions = systemConfig.getSystemPermissions(); 2026 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2027 2028 synchronized (mInstallLock) { 2029 // writer 2030 synchronized (mPackages) { 2031 mHandlerThread = new ServiceThread(TAG, 2032 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2033 mHandlerThread.start(); 2034 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2035 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2036 2037 File dataDir = Environment.getDataDirectory(); 2038 mAppInstallDir = new File(dataDir, "app"); 2039 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2040 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2041 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2042 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2043 2044 sUserManager = new UserManagerService(context, this, mPackages); 2045 2046 // Propagate permission configuration in to package manager. 2047 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2048 = systemConfig.getPermissions(); 2049 for (int i=0; i<permConfig.size(); i++) { 2050 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2051 BasePermission bp = mSettings.mPermissions.get(perm.name); 2052 if (bp == null) { 2053 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2054 mSettings.mPermissions.put(perm.name, bp); 2055 } 2056 if (perm.gids != null) { 2057 bp.setGids(perm.gids, perm.perUser); 2058 } 2059 } 2060 2061 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2062 for (int i=0; i<libConfig.size(); i++) { 2063 mSharedLibraries.put(libConfig.keyAt(i), 2064 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2065 } 2066 2067 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2068 2069 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2070 2071 String customResolverActivity = Resources.getSystem().getString( 2072 R.string.config_customResolverActivity); 2073 if (TextUtils.isEmpty(customResolverActivity)) { 2074 customResolverActivity = null; 2075 } else { 2076 mCustomResolverComponentName = ComponentName.unflattenFromString( 2077 customResolverActivity); 2078 } 2079 2080 long startTime = SystemClock.uptimeMillis(); 2081 2082 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2083 startTime); 2084 2085 // Set flag to monitor and not change apk file paths when 2086 // scanning install directories. 2087 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2088 2089 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2090 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2091 2092 if (bootClassPath == null) { 2093 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2094 } 2095 2096 if (systemServerClassPath == null) { 2097 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2098 } 2099 2100 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2101 final String[] dexCodeInstructionSets = 2102 getDexCodeInstructionSets( 2103 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2104 2105 /** 2106 * Ensure all external libraries have had dexopt run on them. 2107 */ 2108 if (mSharedLibraries.size() > 0) { 2109 // NOTE: For now, we're compiling these system "shared libraries" 2110 // (and framework jars) into all available architectures. It's possible 2111 // to compile them only when we come across an app that uses them (there's 2112 // already logic for that in scanPackageLI) but that adds some complexity. 2113 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2114 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2115 final String lib = libEntry.path; 2116 if (lib == null) { 2117 continue; 2118 } 2119 2120 try { 2121 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2122 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2123 // Shared libraries do not have profiles so we perform a full 2124 // AOT compilation. 2125 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2126 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2127 StorageManager.UUID_PRIVATE_INTERNAL, 2128 false /*useProfiles*/); 2129 } 2130 } catch (FileNotFoundException e) { 2131 Slog.w(TAG, "Library not found: " + lib); 2132 } catch (IOException | InstallerException e) { 2133 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2134 + e.getMessage()); 2135 } 2136 } 2137 } 2138 } 2139 2140 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2141 2142 final VersionInfo ver = mSettings.getInternalVersion(); 2143 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2144 // when upgrading from pre-M, promote system app permissions from install to runtime 2145 mPromoteSystemApps = 2146 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2147 2148 // save off the names of pre-existing system packages prior to scanning; we don't 2149 // want to automatically grant runtime permissions for new system apps 2150 if (mPromoteSystemApps) { 2151 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2152 while (pkgSettingIter.hasNext()) { 2153 PackageSetting ps = pkgSettingIter.next(); 2154 if (isSystemApp(ps)) { 2155 mExistingSystemPackages.add(ps.name); 2156 } 2157 } 2158 } 2159 2160 // Collect vendor overlay packages. 2161 // (Do this before scanning any apps.) 2162 // For security and version matching reason, only consider 2163 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2164 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2165 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2166 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2167 2168 // Find base frameworks (resource packages without code). 2169 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2170 | PackageParser.PARSE_IS_SYSTEM_DIR 2171 | PackageParser.PARSE_IS_PRIVILEGED, 2172 scanFlags | SCAN_NO_DEX, 0); 2173 2174 // Collected privileged system packages. 2175 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2176 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2177 | PackageParser.PARSE_IS_SYSTEM_DIR 2178 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2179 2180 // Collect ordinary system packages. 2181 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2182 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2183 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2184 2185 // Collect all vendor packages. 2186 File vendorAppDir = new File("/vendor/app"); 2187 try { 2188 vendorAppDir = vendorAppDir.getCanonicalFile(); 2189 } catch (IOException e) { 2190 // failed to look up canonical path, continue with original one 2191 } 2192 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2193 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2194 2195 // Collect all OEM packages. 2196 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2197 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2198 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2199 2200 // Prune any system packages that no longer exist. 2201 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2202 if (!mOnlyCore) { 2203 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2204 while (psit.hasNext()) { 2205 PackageSetting ps = psit.next(); 2206 2207 /* 2208 * If this is not a system app, it can't be a 2209 * disable system app. 2210 */ 2211 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2212 continue; 2213 } 2214 2215 /* 2216 * If the package is scanned, it's not erased. 2217 */ 2218 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2219 if (scannedPkg != null) { 2220 /* 2221 * If the system app is both scanned and in the 2222 * disabled packages list, then it must have been 2223 * added via OTA. Remove it from the currently 2224 * scanned package so the previously user-installed 2225 * application can be scanned. 2226 */ 2227 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2228 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2229 + ps.name + "; removing system app. Last known codePath=" 2230 + ps.codePathString + ", installStatus=" + ps.installStatus 2231 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2232 + scannedPkg.mVersionCode); 2233 removePackageSettingLI(scannedPkg, true); 2234 mExpectingBetter.put(ps.name, ps.codePath); 2235 } 2236 2237 continue; 2238 } 2239 2240 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2241 psit.remove(); 2242 logCriticalInfo(Log.WARN, "System package " + ps.name 2243 + " no longer exists; wiping its data"); 2244 removeDataDirsLI(null, ps.name); 2245 } else { 2246 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2247 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2248 possiblyDeletedUpdatedSystemApps.add(ps.name); 2249 } 2250 } 2251 } 2252 } 2253 2254 //look for any incomplete package installations 2255 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2256 //clean up list 2257 for(int i = 0; i < deletePkgsList.size(); i++) { 2258 //clean up here 2259 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2260 } 2261 //delete tmp files 2262 deleteTempPackageFiles(); 2263 2264 // Remove any shared userIDs that have no associated packages 2265 mSettings.pruneSharedUsersLPw(); 2266 2267 if (!mOnlyCore) { 2268 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2269 SystemClock.uptimeMillis()); 2270 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2271 2272 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2273 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2274 2275 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2276 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2277 2278 /** 2279 * Remove disable package settings for any updated system 2280 * apps that were removed via an OTA. If they're not a 2281 * previously-updated app, remove them completely. 2282 * Otherwise, just revoke their system-level permissions. 2283 */ 2284 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2285 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2286 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2287 2288 String msg; 2289 if (deletedPkg == null) { 2290 msg = "Updated system package " + deletedAppName 2291 + " no longer exists; wiping its data"; 2292 removeDataDirsLI(null, deletedAppName); 2293 } else { 2294 msg = "Updated system app + " + deletedAppName 2295 + " no longer present; removing system privileges for " 2296 + deletedAppName; 2297 2298 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2299 2300 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2301 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2302 } 2303 logCriticalInfo(Log.WARN, msg); 2304 } 2305 2306 /** 2307 * Make sure all system apps that we expected to appear on 2308 * the userdata partition actually showed up. If they never 2309 * appeared, crawl back and revive the system version. 2310 */ 2311 for (int i = 0; i < mExpectingBetter.size(); i++) { 2312 final String packageName = mExpectingBetter.keyAt(i); 2313 if (!mPackages.containsKey(packageName)) { 2314 final File scanFile = mExpectingBetter.valueAt(i); 2315 2316 logCriticalInfo(Log.WARN, "Expected better " + packageName 2317 + " but never showed up; reverting to system"); 2318 2319 final int reparseFlags; 2320 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2321 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2322 | PackageParser.PARSE_IS_SYSTEM_DIR 2323 | PackageParser.PARSE_IS_PRIVILEGED; 2324 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2325 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2326 | PackageParser.PARSE_IS_SYSTEM_DIR; 2327 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2328 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2329 | PackageParser.PARSE_IS_SYSTEM_DIR; 2330 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2331 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2332 | PackageParser.PARSE_IS_SYSTEM_DIR; 2333 } else { 2334 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2335 continue; 2336 } 2337 2338 mSettings.enableSystemPackageLPw(packageName); 2339 2340 try { 2341 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2342 } catch (PackageManagerException e) { 2343 Slog.e(TAG, "Failed to parse original system package: " 2344 + e.getMessage()); 2345 } 2346 } 2347 } 2348 } 2349 mExpectingBetter.clear(); 2350 2351 // Now that we know all of the shared libraries, update all clients to have 2352 // the correct library paths. 2353 updateAllSharedLibrariesLPw(); 2354 2355 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2356 // NOTE: We ignore potential failures here during a system scan (like 2357 // the rest of the commands above) because there's precious little we 2358 // can do about it. A settings error is reported, though. 2359 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2360 false /* boot complete */); 2361 } 2362 2363 // Now that we know all the packages we are keeping, 2364 // read and update their last usage times. 2365 mPackageUsage.readLP(); 2366 2367 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2368 SystemClock.uptimeMillis()); 2369 Slog.i(TAG, "Time to scan packages: " 2370 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2371 + " seconds"); 2372 2373 // If the platform SDK has changed since the last time we booted, 2374 // we need to re-grant app permission to catch any new ones that 2375 // appear. This is really a hack, and means that apps can in some 2376 // cases get permissions that the user didn't initially explicitly 2377 // allow... it would be nice to have some better way to handle 2378 // this situation. 2379 int updateFlags = UPDATE_PERMISSIONS_ALL; 2380 if (ver.sdkVersion != mSdkVersion) { 2381 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2382 + mSdkVersion + "; regranting permissions for internal storage"); 2383 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2384 } 2385 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2386 ver.sdkVersion = mSdkVersion; 2387 2388 // If this is the first boot or an update from pre-M, and it is a normal 2389 // boot, then we need to initialize the default preferred apps across 2390 // all defined users. 2391 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2392 for (UserInfo user : sUserManager.getUsers(true)) { 2393 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2394 applyFactoryDefaultBrowserLPw(user.id); 2395 primeDomainVerificationsLPw(user.id); 2396 } 2397 } 2398 2399 // Prepare storage for system user really early during boot, 2400 // since core system apps like SettingsProvider and SystemUI 2401 // can't wait for user to start 2402 final int storageFlags; 2403 if (StorageManager.isFileBasedEncryptionEnabled()) { 2404 storageFlags = StorageManager.FLAG_STORAGE_DE; 2405 } else { 2406 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2407 } 2408 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2409 storageFlags); 2410 2411 if (!StorageManager.isFileBasedEncryptionEnabled() 2412 && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) { 2413 // When upgrading a non-FBE device, we might need to shuffle 2414 // around the default storage location of system apps 2415 final List<UserInfo> users = sUserManager.getUsers(true); 2416 for (PackageSetting ps : mSettings.mPackages.values()) { 2417 if (ps.pkg == null || !ps.isSystem()) continue; 2418 final int storageTarget = ps.pkg.applicationInfo.isForceDeviceEncrypted() 2419 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 2420 for (UserInfo user : users) { 2421 if (ps.getInstalled(user.id)) { 2422 try { 2423 mInstaller.migrateAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2424 ps.name, user.id, storageTarget); 2425 } catch (InstallerException e) { 2426 logCriticalInfo(Log.WARN, 2427 "Failed to migrate " + ps.name + ": " + e.getMessage()); 2428 } 2429 // We may have just shuffled around app data 2430 // directories, so prepare it one more time 2431 prepareAppData(StorageManager.UUID_PRIVATE_INTERNAL, user.id, 2432 storageFlags, ps.pkg, false); 2433 } 2434 } 2435 } 2436 } 2437 2438 // If this is first boot after an OTA, and a normal boot, then 2439 // we need to clear code cache directories. 2440 if (mIsUpgrade && !onlyCore) { 2441 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2442 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2443 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2444 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2445 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2446 } 2447 } 2448 ver.fingerprint = Build.FINGERPRINT; 2449 } 2450 2451 checkDefaultBrowser(); 2452 2453 // clear only after permissions and other defaults have been updated 2454 mExistingSystemPackages.clear(); 2455 mPromoteSystemApps = false; 2456 2457 // All the changes are done during package scanning. 2458 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2459 2460 // can downgrade to reader 2461 mSettings.writeLPr(); 2462 2463 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2464 SystemClock.uptimeMillis()); 2465 2466 if (!mOnlyCore) { 2467 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2468 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2469 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2470 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2471 mIntentFilterVerifierComponent); 2472 } else { 2473 mRequiredVerifierPackage = null; 2474 mRequiredInstallerPackage = null; 2475 mIntentFilterVerifierComponent = null; 2476 mIntentFilterVerifier = null; 2477 } 2478 2479 mInstallerService = new PackageInstallerService(context, this); 2480 2481 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2482 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2483 // both the installer and resolver must be present to enable ephemeral 2484 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2485 if (DEBUG_EPHEMERAL) { 2486 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2487 + " installer:" + ephemeralInstallerComponent); 2488 } 2489 mEphemeralResolverComponent = ephemeralResolverComponent; 2490 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2491 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2492 mEphemeralResolverConnection = 2493 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2494 } else { 2495 if (DEBUG_EPHEMERAL) { 2496 final String missingComponent = 2497 (ephemeralResolverComponent == null) 2498 ? (ephemeralInstallerComponent == null) 2499 ? "resolver and installer" 2500 : "resolver" 2501 : "installer"; 2502 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2503 } 2504 mEphemeralResolverComponent = null; 2505 mEphemeralInstallerComponent = null; 2506 mEphemeralResolverConnection = null; 2507 } 2508 2509 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2510 } // synchronized (mPackages) 2511 } // synchronized (mInstallLock) 2512 2513 // Now after opening every single application zip, make sure they 2514 // are all flushed. Not really needed, but keeps things nice and 2515 // tidy. 2516 Runtime.getRuntime().gc(); 2517 2518 // The initial scanning above does many calls into installd while 2519 // holding the mPackages lock, but we're mostly interested in yelling 2520 // once we have a booted system. 2521 mInstaller.setWarnIfHeld(mPackages); 2522 2523 // Expose private service for system components to use. 2524 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2525 } 2526 2527 @Override 2528 public boolean isFirstBoot() { 2529 return !mRestoredSettings; 2530 } 2531 2532 @Override 2533 public boolean isOnlyCoreApps() { 2534 return mOnlyCore; 2535 } 2536 2537 @Override 2538 public boolean isUpgrade() { 2539 return mIsUpgrade; 2540 } 2541 2542 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2543 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2544 2545 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2546 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2547 if (matches.size() == 1) { 2548 return matches.get(0).getComponentInfo().packageName; 2549 } else { 2550 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2551 return null; 2552 } 2553 } 2554 2555 private @NonNull String getRequiredInstallerLPr() { 2556 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2557 intent.addCategory(Intent.CATEGORY_DEFAULT); 2558 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2559 2560 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2561 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2562 if (matches.size() == 1) { 2563 return matches.get(0).getComponentInfo().packageName; 2564 } else { 2565 throw new RuntimeException("There must be exactly one installer; found " + matches); 2566 } 2567 } 2568 2569 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2570 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2571 2572 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2573 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2574 ResolveInfo best = null; 2575 final int N = matches.size(); 2576 for (int i = 0; i < N; i++) { 2577 final ResolveInfo cur = matches.get(i); 2578 final String packageName = cur.getComponentInfo().packageName; 2579 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2580 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2581 continue; 2582 } 2583 2584 if (best == null || cur.priority > best.priority) { 2585 best = cur; 2586 } 2587 } 2588 2589 if (best != null) { 2590 return best.getComponentInfo().getComponentName(); 2591 } else { 2592 throw new RuntimeException("There must be at least one intent filter verifier"); 2593 } 2594 } 2595 2596 private @Nullable ComponentName getEphemeralResolverLPr() { 2597 final String[] packageArray = 2598 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2599 if (packageArray.length == 0) { 2600 if (DEBUG_EPHEMERAL) { 2601 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2602 } 2603 return null; 2604 } 2605 2606 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2607 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null, 2608 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2609 2610 final int N = resolvers.size(); 2611 if (N == 0) { 2612 if (DEBUG_EPHEMERAL) { 2613 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2614 } 2615 return null; 2616 } 2617 2618 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2619 for (int i = 0; i < N; i++) { 2620 final ResolveInfo info = resolvers.get(i); 2621 2622 if (info.serviceInfo == null) { 2623 continue; 2624 } 2625 2626 final String packageName = info.serviceInfo.packageName; 2627 if (!possiblePackages.contains(packageName)) { 2628 if (DEBUG_EPHEMERAL) { 2629 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2630 + " pkg: " + packageName + ", info:" + info); 2631 } 2632 continue; 2633 } 2634 2635 if (DEBUG_EPHEMERAL) { 2636 Slog.v(TAG, "Ephemeral resolver found;" 2637 + " pkg: " + packageName + ", info:" + info); 2638 } 2639 return new ComponentName(packageName, info.serviceInfo.name); 2640 } 2641 if (DEBUG_EPHEMERAL) { 2642 Slog.v(TAG, "Ephemeral resolver NOT found"); 2643 } 2644 return null; 2645 } 2646 2647 private @Nullable ComponentName getEphemeralInstallerLPr() { 2648 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2649 intent.addCategory(Intent.CATEGORY_DEFAULT); 2650 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2651 2652 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2653 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2654 if (matches.size() == 0) { 2655 return null; 2656 } else if (matches.size() == 1) { 2657 return matches.get(0).getComponentInfo().getComponentName(); 2658 } else { 2659 throw new RuntimeException( 2660 "There must be at most one ephemeral installer; found " + matches); 2661 } 2662 } 2663 2664 private void primeDomainVerificationsLPw(int userId) { 2665 if (DEBUG_DOMAIN_VERIFICATION) { 2666 Slog.d(TAG, "Priming domain verifications in user " + userId); 2667 } 2668 2669 SystemConfig systemConfig = SystemConfig.getInstance(); 2670 ArraySet<String> packages = systemConfig.getLinkedApps(); 2671 ArraySet<String> domains = new ArraySet<String>(); 2672 2673 for (String packageName : packages) { 2674 PackageParser.Package pkg = mPackages.get(packageName); 2675 if (pkg != null) { 2676 if (!pkg.isSystemApp()) { 2677 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2678 continue; 2679 } 2680 2681 domains.clear(); 2682 for (PackageParser.Activity a : pkg.activities) { 2683 for (ActivityIntentInfo filter : a.intents) { 2684 if (hasValidDomains(filter)) { 2685 domains.addAll(filter.getHostsList()); 2686 } 2687 } 2688 } 2689 2690 if (domains.size() > 0) { 2691 if (DEBUG_DOMAIN_VERIFICATION) { 2692 Slog.v(TAG, " + " + packageName); 2693 } 2694 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2695 // state w.r.t. the formal app-linkage "no verification attempted" state; 2696 // and then 'always' in the per-user state actually used for intent resolution. 2697 final IntentFilterVerificationInfo ivi; 2698 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2699 new ArrayList<String>(domains)); 2700 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2701 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2702 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2703 } else { 2704 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2705 + "' does not handle web links"); 2706 } 2707 } else { 2708 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2709 } 2710 } 2711 2712 scheduleWritePackageRestrictionsLocked(userId); 2713 scheduleWriteSettingsLocked(); 2714 } 2715 2716 private void applyFactoryDefaultBrowserLPw(int userId) { 2717 // The default browser app's package name is stored in a string resource, 2718 // with a product-specific overlay used for vendor customization. 2719 String browserPkg = mContext.getResources().getString( 2720 com.android.internal.R.string.default_browser); 2721 if (!TextUtils.isEmpty(browserPkg)) { 2722 // non-empty string => required to be a known package 2723 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2724 if (ps == null) { 2725 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2726 browserPkg = null; 2727 } else { 2728 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2729 } 2730 } 2731 2732 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2733 // default. If there's more than one, just leave everything alone. 2734 if (browserPkg == null) { 2735 calculateDefaultBrowserLPw(userId); 2736 } 2737 } 2738 2739 private void calculateDefaultBrowserLPw(int userId) { 2740 List<String> allBrowsers = resolveAllBrowserApps(userId); 2741 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2742 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2743 } 2744 2745 private List<String> resolveAllBrowserApps(int userId) { 2746 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2747 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2748 PackageManager.MATCH_ALL, userId); 2749 2750 final int count = list.size(); 2751 List<String> result = new ArrayList<String>(count); 2752 for (int i=0; i<count; i++) { 2753 ResolveInfo info = list.get(i); 2754 if (info.activityInfo == null 2755 || !info.handleAllWebDataURI 2756 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2757 || result.contains(info.activityInfo.packageName)) { 2758 continue; 2759 } 2760 result.add(info.activityInfo.packageName); 2761 } 2762 2763 return result; 2764 } 2765 2766 private boolean packageIsBrowser(String packageName, int userId) { 2767 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2768 PackageManager.MATCH_ALL, userId); 2769 final int N = list.size(); 2770 for (int i = 0; i < N; i++) { 2771 ResolveInfo info = list.get(i); 2772 if (packageName.equals(info.activityInfo.packageName)) { 2773 return true; 2774 } 2775 } 2776 return false; 2777 } 2778 2779 private void checkDefaultBrowser() { 2780 final int myUserId = UserHandle.myUserId(); 2781 final String packageName = getDefaultBrowserPackageName(myUserId); 2782 if (packageName != null) { 2783 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2784 if (info == null) { 2785 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2786 synchronized (mPackages) { 2787 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2788 } 2789 } 2790 } 2791 } 2792 2793 @Override 2794 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2795 throws RemoteException { 2796 try { 2797 return super.onTransact(code, data, reply, flags); 2798 } catch (RuntimeException e) { 2799 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2800 Slog.wtf(TAG, "Package Manager Crash", e); 2801 } 2802 throw e; 2803 } 2804 } 2805 2806 void cleanupInstallFailedPackage(PackageSetting ps) { 2807 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2808 2809 removeDataDirsLI(ps.volumeUuid, ps.name); 2810 if (ps.codePath != null) { 2811 removeCodePathLI(ps.codePath); 2812 } 2813 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2814 if (ps.resourcePath.isDirectory()) { 2815 FileUtils.deleteContents(ps.resourcePath); 2816 } 2817 ps.resourcePath.delete(); 2818 } 2819 mSettings.removePackageLPw(ps.name); 2820 } 2821 2822 static int[] appendInts(int[] cur, int[] add) { 2823 if (add == null) return cur; 2824 if (cur == null) return add; 2825 final int N = add.length; 2826 for (int i=0; i<N; i++) { 2827 cur = appendInt(cur, add[i]); 2828 } 2829 return cur; 2830 } 2831 2832 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2833 if (!sUserManager.exists(userId)) return null; 2834 final PackageSetting ps = (PackageSetting) p.mExtras; 2835 if (ps == null) { 2836 return null; 2837 } 2838 2839 final PermissionsState permissionsState = ps.getPermissionsState(); 2840 2841 final int[] gids = permissionsState.computeGids(userId); 2842 final Set<String> permissions = permissionsState.getPermissions(userId); 2843 final PackageUserState state = ps.readUserState(userId); 2844 2845 return PackageParser.generatePackageInfo(p, gids, flags, 2846 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2847 } 2848 2849 @Override 2850 public void checkPackageStartable(String packageName, int userId) { 2851 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2852 2853 synchronized (mPackages) { 2854 final PackageSetting ps = mSettings.mPackages.get(packageName); 2855 if (ps == null) { 2856 throw new SecurityException("Package " + packageName + " was not found!"); 2857 } 2858 2859 if (ps.frozen) { 2860 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2861 } 2862 2863 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2864 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2865 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2866 } 2867 } 2868 } 2869 2870 @Override 2871 public boolean isPackageAvailable(String packageName, int userId) { 2872 if (!sUserManager.exists(userId)) return false; 2873 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2874 synchronized (mPackages) { 2875 PackageParser.Package p = mPackages.get(packageName); 2876 if (p != null) { 2877 final PackageSetting ps = (PackageSetting) p.mExtras; 2878 if (ps != null) { 2879 final PackageUserState state = ps.readUserState(userId); 2880 if (state != null) { 2881 return PackageParser.isAvailable(state); 2882 } 2883 } 2884 } 2885 } 2886 return false; 2887 } 2888 2889 @Override 2890 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2891 if (!sUserManager.exists(userId)) return null; 2892 flags = updateFlagsForPackage(flags, userId, packageName); 2893 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2894 // reader 2895 synchronized (mPackages) { 2896 PackageParser.Package p = mPackages.get(packageName); 2897 if (DEBUG_PACKAGE_INFO) 2898 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2899 if (p != null) { 2900 return generatePackageInfo(p, flags, userId); 2901 } 2902 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2903 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2904 } 2905 } 2906 return null; 2907 } 2908 2909 @Override 2910 public String[] currentToCanonicalPackageNames(String[] names) { 2911 String[] out = new String[names.length]; 2912 // reader 2913 synchronized (mPackages) { 2914 for (int i=names.length-1; i>=0; i--) { 2915 PackageSetting ps = mSettings.mPackages.get(names[i]); 2916 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2917 } 2918 } 2919 return out; 2920 } 2921 2922 @Override 2923 public String[] canonicalToCurrentPackageNames(String[] names) { 2924 String[] out = new String[names.length]; 2925 // reader 2926 synchronized (mPackages) { 2927 for (int i=names.length-1; i>=0; i--) { 2928 String cur = mSettings.mRenamedPackages.get(names[i]); 2929 out[i] = cur != null ? cur : names[i]; 2930 } 2931 } 2932 return out; 2933 } 2934 2935 @Override 2936 public int getPackageUid(String packageName, int flags, int userId) { 2937 if (!sUserManager.exists(userId)) return -1; 2938 flags = updateFlagsForPackage(flags, userId, packageName); 2939 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2940 2941 // reader 2942 synchronized (mPackages) { 2943 final PackageParser.Package p = mPackages.get(packageName); 2944 if (p != null && p.isMatch(flags)) { 2945 return UserHandle.getUid(userId, p.applicationInfo.uid); 2946 } 2947 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2948 final PackageSetting ps = mSettings.mPackages.get(packageName); 2949 if (ps != null && ps.isMatch(flags)) { 2950 return UserHandle.getUid(userId, ps.appId); 2951 } 2952 } 2953 } 2954 2955 return -1; 2956 } 2957 2958 @Override 2959 public int[] getPackageGids(String packageName, int flags, int userId) { 2960 if (!sUserManager.exists(userId)) return null; 2961 flags = updateFlagsForPackage(flags, userId, packageName); 2962 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2963 "getPackageGids"); 2964 2965 // reader 2966 synchronized (mPackages) { 2967 final PackageParser.Package p = mPackages.get(packageName); 2968 if (p != null && p.isMatch(flags)) { 2969 PackageSetting ps = (PackageSetting) p.mExtras; 2970 return ps.getPermissionsState().computeGids(userId); 2971 } 2972 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2973 final PackageSetting ps = mSettings.mPackages.get(packageName); 2974 if (ps != null && ps.isMatch(flags)) { 2975 return ps.getPermissionsState().computeGids(userId); 2976 } 2977 } 2978 } 2979 2980 return null; 2981 } 2982 2983 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 2984 if (bp.perm != null) { 2985 return PackageParser.generatePermissionInfo(bp.perm, flags); 2986 } 2987 PermissionInfo pi = new PermissionInfo(); 2988 pi.name = bp.name; 2989 pi.packageName = bp.sourcePackage; 2990 pi.nonLocalizedLabel = bp.name; 2991 pi.protectionLevel = bp.protectionLevel; 2992 return pi; 2993 } 2994 2995 @Override 2996 public PermissionInfo getPermissionInfo(String name, int flags) { 2997 // reader 2998 synchronized (mPackages) { 2999 final BasePermission p = mSettings.mPermissions.get(name); 3000 if (p != null) { 3001 return generatePermissionInfo(p, flags); 3002 } 3003 return null; 3004 } 3005 } 3006 3007 @Override 3008 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 3009 // reader 3010 synchronized (mPackages) { 3011 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3012 for (BasePermission p : mSettings.mPermissions.values()) { 3013 if (group == null) { 3014 if (p.perm == null || p.perm.info.group == null) { 3015 out.add(generatePermissionInfo(p, flags)); 3016 } 3017 } else { 3018 if (p.perm != null && group.equals(p.perm.info.group)) { 3019 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3020 } 3021 } 3022 } 3023 3024 if (out.size() > 0) { 3025 return out; 3026 } 3027 return mPermissionGroups.containsKey(group) ? out : null; 3028 } 3029 } 3030 3031 @Override 3032 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3033 // reader 3034 synchronized (mPackages) { 3035 return PackageParser.generatePermissionGroupInfo( 3036 mPermissionGroups.get(name), flags); 3037 } 3038 } 3039 3040 @Override 3041 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3042 // reader 3043 synchronized (mPackages) { 3044 final int N = mPermissionGroups.size(); 3045 ArrayList<PermissionGroupInfo> out 3046 = new ArrayList<PermissionGroupInfo>(N); 3047 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3048 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3049 } 3050 return out; 3051 } 3052 } 3053 3054 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3055 int userId) { 3056 if (!sUserManager.exists(userId)) return null; 3057 PackageSetting ps = mSettings.mPackages.get(packageName); 3058 if (ps != null) { 3059 if (ps.pkg == null) { 3060 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3061 flags, userId); 3062 if (pInfo != null) { 3063 return pInfo.applicationInfo; 3064 } 3065 return null; 3066 } 3067 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3068 ps.readUserState(userId), userId); 3069 } 3070 return null; 3071 } 3072 3073 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3074 int userId) { 3075 if (!sUserManager.exists(userId)) return null; 3076 PackageSetting ps = mSettings.mPackages.get(packageName); 3077 if (ps != null) { 3078 PackageParser.Package pkg = ps.pkg; 3079 if (pkg == null) { 3080 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3081 return null; 3082 } 3083 // Only data remains, so we aren't worried about code paths 3084 pkg = new PackageParser.Package(packageName); 3085 pkg.applicationInfo.packageName = packageName; 3086 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3087 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3088 pkg.applicationInfo.uid = ps.appId; 3089 pkg.applicationInfo.initForUser(userId); 3090 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3091 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3092 } 3093 return generatePackageInfo(pkg, flags, userId); 3094 } 3095 return null; 3096 } 3097 3098 @Override 3099 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3100 if (!sUserManager.exists(userId)) return null; 3101 flags = updateFlagsForApplication(flags, userId, packageName); 3102 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3103 // writer 3104 synchronized (mPackages) { 3105 PackageParser.Package p = mPackages.get(packageName); 3106 if (DEBUG_PACKAGE_INFO) Log.v( 3107 TAG, "getApplicationInfo " + packageName 3108 + ": " + p); 3109 if (p != null) { 3110 PackageSetting ps = mSettings.mPackages.get(packageName); 3111 if (ps == null) return null; 3112 // Note: isEnabledLP() does not apply here - always return info 3113 return PackageParser.generateApplicationInfo( 3114 p, flags, ps.readUserState(userId), userId); 3115 } 3116 if ("android".equals(packageName)||"system".equals(packageName)) { 3117 return mAndroidApplication; 3118 } 3119 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3120 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3121 } 3122 } 3123 return null; 3124 } 3125 3126 @Override 3127 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3128 final IPackageDataObserver observer) { 3129 mContext.enforceCallingOrSelfPermission( 3130 android.Manifest.permission.CLEAR_APP_CACHE, null); 3131 // Queue up an async operation since clearing cache may take a little while. 3132 mHandler.post(new Runnable() { 3133 public void run() { 3134 mHandler.removeCallbacks(this); 3135 boolean success = true; 3136 synchronized (mInstallLock) { 3137 try { 3138 mInstaller.freeCache(volumeUuid, freeStorageSize); 3139 } catch (InstallerException e) { 3140 Slog.w(TAG, "Couldn't clear application caches: " + e); 3141 success = false; 3142 } 3143 } 3144 if (observer != null) { 3145 try { 3146 observer.onRemoveCompleted(null, success); 3147 } catch (RemoteException e) { 3148 Slog.w(TAG, "RemoveException when invoking call back"); 3149 } 3150 } 3151 } 3152 }); 3153 } 3154 3155 @Override 3156 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3157 final IntentSender pi) { 3158 mContext.enforceCallingOrSelfPermission( 3159 android.Manifest.permission.CLEAR_APP_CACHE, null); 3160 // Queue up an async operation since clearing cache may take a little while. 3161 mHandler.post(new Runnable() { 3162 public void run() { 3163 mHandler.removeCallbacks(this); 3164 boolean success = true; 3165 synchronized (mInstallLock) { 3166 try { 3167 mInstaller.freeCache(volumeUuid, freeStorageSize); 3168 } catch (InstallerException e) { 3169 Slog.w(TAG, "Couldn't clear application caches: " + e); 3170 success = false; 3171 } 3172 } 3173 if(pi != null) { 3174 try { 3175 // Callback via pending intent 3176 int code = success ? 1 : 0; 3177 pi.sendIntent(null, code, null, 3178 null, null); 3179 } catch (SendIntentException e1) { 3180 Slog.i(TAG, "Failed to send pending intent"); 3181 } 3182 } 3183 } 3184 }); 3185 } 3186 3187 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3188 synchronized (mInstallLock) { 3189 try { 3190 mInstaller.freeCache(volumeUuid, freeStorageSize); 3191 } catch (InstallerException e) { 3192 throw new IOException("Failed to free enough space", e); 3193 } 3194 } 3195 } 3196 3197 /** 3198 * Return if the user key is currently unlocked. 3199 */ 3200 private boolean isUserKeyUnlocked(int userId) { 3201 if (StorageManager.isFileBasedEncryptionEnabled()) { 3202 final IMountService mount = IMountService.Stub 3203 .asInterface(ServiceManager.getService("mount")); 3204 if (mount == null) { 3205 Slog.w(TAG, "Early during boot, assuming locked"); 3206 return false; 3207 } 3208 final long token = Binder.clearCallingIdentity(); 3209 try { 3210 return mount.isUserKeyUnlocked(userId); 3211 } catch (RemoteException e) { 3212 throw e.rethrowAsRuntimeException(); 3213 } finally { 3214 Binder.restoreCallingIdentity(token); 3215 } 3216 } else { 3217 return true; 3218 } 3219 } 3220 3221 /** 3222 * Update given flags based on encryption status of current user. 3223 */ 3224 private int updateFlags(int flags, int userId) { 3225 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3226 | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) { 3227 // Caller expressed an explicit opinion about what encryption 3228 // aware/unaware components they want to see, so fall through and 3229 // give them what they want 3230 } else { 3231 // Caller expressed no opinion, so match based on user state 3232 if (isUserKeyUnlocked(userId)) { 3233 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 3234 } else { 3235 flags |= PackageManager.MATCH_ENCRYPTION_AWARE; 3236 } 3237 } 3238 3239 // Safe mode means we should ignore any third-party apps 3240 if (mSafeMode) { 3241 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3242 } 3243 3244 return flags; 3245 } 3246 3247 /** 3248 * Update given flags when being used to request {@link PackageInfo}. 3249 */ 3250 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3251 boolean triaged = true; 3252 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3253 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3254 // Caller is asking for component details, so they'd better be 3255 // asking for specific encryption matching behavior, or be triaged 3256 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3257 | PackageManager.MATCH_ENCRYPTION_AWARE 3258 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3259 triaged = false; 3260 } 3261 } 3262 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3263 | PackageManager.MATCH_SYSTEM_ONLY 3264 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3265 triaged = false; 3266 } 3267 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3268 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3269 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3270 } 3271 return updateFlags(flags, userId); 3272 } 3273 3274 /** 3275 * Update given flags when being used to request {@link ApplicationInfo}. 3276 */ 3277 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3278 return updateFlagsForPackage(flags, userId, cookie); 3279 } 3280 3281 /** 3282 * Update given flags when being used to request {@link ComponentInfo}. 3283 */ 3284 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3285 if (cookie instanceof Intent) { 3286 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3287 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3288 } 3289 } 3290 3291 boolean triaged = true; 3292 // Caller is asking for component details, so they'd better be 3293 // asking for specific encryption matching behavior, or be triaged 3294 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3295 | PackageManager.MATCH_ENCRYPTION_AWARE 3296 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3297 triaged = false; 3298 } 3299 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3300 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3301 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3302 } 3303 return updateFlags(flags, userId); 3304 } 3305 3306 /** 3307 * Update given flags when being used to request {@link ResolveInfo}. 3308 */ 3309 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3310 return updateFlagsForComponent(flags, userId, cookie); 3311 } 3312 3313 @Override 3314 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3315 if (!sUserManager.exists(userId)) return null; 3316 flags = updateFlagsForComponent(flags, userId, component); 3317 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3318 synchronized (mPackages) { 3319 PackageParser.Activity a = mActivities.mActivities.get(component); 3320 3321 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3322 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3323 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3324 if (ps == null) return null; 3325 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3326 userId); 3327 } 3328 if (mResolveComponentName.equals(component)) { 3329 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3330 new PackageUserState(), userId); 3331 } 3332 } 3333 return null; 3334 } 3335 3336 @Override 3337 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3338 String resolvedType) { 3339 synchronized (mPackages) { 3340 if (component.equals(mResolveComponentName)) { 3341 // The resolver supports EVERYTHING! 3342 return true; 3343 } 3344 PackageParser.Activity a = mActivities.mActivities.get(component); 3345 if (a == null) { 3346 return false; 3347 } 3348 for (int i=0; i<a.intents.size(); i++) { 3349 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3350 intent.getData(), intent.getCategories(), TAG) >= 0) { 3351 return true; 3352 } 3353 } 3354 return false; 3355 } 3356 } 3357 3358 @Override 3359 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3360 if (!sUserManager.exists(userId)) return null; 3361 flags = updateFlagsForComponent(flags, userId, component); 3362 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3363 synchronized (mPackages) { 3364 PackageParser.Activity a = mReceivers.mActivities.get(component); 3365 if (DEBUG_PACKAGE_INFO) Log.v( 3366 TAG, "getReceiverInfo " + component + ": " + a); 3367 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3368 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3369 if (ps == null) return null; 3370 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3371 userId); 3372 } 3373 } 3374 return null; 3375 } 3376 3377 @Override 3378 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3379 if (!sUserManager.exists(userId)) return null; 3380 flags = updateFlagsForComponent(flags, userId, component); 3381 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3382 synchronized (mPackages) { 3383 PackageParser.Service s = mServices.mServices.get(component); 3384 if (DEBUG_PACKAGE_INFO) Log.v( 3385 TAG, "getServiceInfo " + component + ": " + s); 3386 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3387 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3388 if (ps == null) return null; 3389 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3390 userId); 3391 } 3392 } 3393 return null; 3394 } 3395 3396 @Override 3397 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3398 if (!sUserManager.exists(userId)) return null; 3399 flags = updateFlagsForComponent(flags, userId, component); 3400 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3401 synchronized (mPackages) { 3402 PackageParser.Provider p = mProviders.mProviders.get(component); 3403 if (DEBUG_PACKAGE_INFO) Log.v( 3404 TAG, "getProviderInfo " + component + ": " + p); 3405 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3406 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3407 if (ps == null) return null; 3408 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3409 userId); 3410 } 3411 } 3412 return null; 3413 } 3414 3415 @Override 3416 public String[] getSystemSharedLibraryNames() { 3417 Set<String> libSet; 3418 synchronized (mPackages) { 3419 libSet = mSharedLibraries.keySet(); 3420 int size = libSet.size(); 3421 if (size > 0) { 3422 String[] libs = new String[size]; 3423 libSet.toArray(libs); 3424 return libs; 3425 } 3426 } 3427 return null; 3428 } 3429 3430 @Override 3431 public @Nullable String getServicesSystemSharedLibraryPackageName() { 3432 synchronized (mPackages) { 3433 SharedLibraryEntry libraryEntry = mSharedLibraries.get( 3434 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 3435 if (libraryEntry != null) { 3436 return libraryEntry.apk; 3437 } 3438 } 3439 return null; 3440 } 3441 3442 @Override 3443 public FeatureInfo[] getSystemAvailableFeatures() { 3444 Collection<FeatureInfo> featSet; 3445 synchronized (mPackages) { 3446 featSet = mAvailableFeatures.values(); 3447 int size = featSet.size(); 3448 if (size > 0) { 3449 FeatureInfo[] features = new FeatureInfo[size+1]; 3450 featSet.toArray(features); 3451 FeatureInfo fi = new FeatureInfo(); 3452 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3453 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3454 features[size] = fi; 3455 return features; 3456 } 3457 } 3458 return null; 3459 } 3460 3461 @Override 3462 public boolean hasSystemFeature(String name) { 3463 synchronized (mPackages) { 3464 return mAvailableFeatures.containsKey(name); 3465 } 3466 } 3467 3468 @Override 3469 public int checkPermission(String permName, String pkgName, int userId) { 3470 if (!sUserManager.exists(userId)) { 3471 return PackageManager.PERMISSION_DENIED; 3472 } 3473 3474 synchronized (mPackages) { 3475 final PackageParser.Package p = mPackages.get(pkgName); 3476 if (p != null && p.mExtras != null) { 3477 final PackageSetting ps = (PackageSetting) p.mExtras; 3478 final PermissionsState permissionsState = ps.getPermissionsState(); 3479 if (permissionsState.hasPermission(permName, userId)) { 3480 return PackageManager.PERMISSION_GRANTED; 3481 } 3482 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3483 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3484 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3485 return PackageManager.PERMISSION_GRANTED; 3486 } 3487 } 3488 } 3489 3490 return PackageManager.PERMISSION_DENIED; 3491 } 3492 3493 @Override 3494 public int checkUidPermission(String permName, int uid) { 3495 final int userId = UserHandle.getUserId(uid); 3496 3497 if (!sUserManager.exists(userId)) { 3498 return PackageManager.PERMISSION_DENIED; 3499 } 3500 3501 synchronized (mPackages) { 3502 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3503 if (obj != null) { 3504 final SettingBase ps = (SettingBase) obj; 3505 final PermissionsState permissionsState = ps.getPermissionsState(); 3506 if (permissionsState.hasPermission(permName, userId)) { 3507 return PackageManager.PERMISSION_GRANTED; 3508 } 3509 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3510 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3511 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3512 return PackageManager.PERMISSION_GRANTED; 3513 } 3514 } else { 3515 ArraySet<String> perms = mSystemPermissions.get(uid); 3516 if (perms != null) { 3517 if (perms.contains(permName)) { 3518 return PackageManager.PERMISSION_GRANTED; 3519 } 3520 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3521 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3522 return PackageManager.PERMISSION_GRANTED; 3523 } 3524 } 3525 } 3526 } 3527 3528 return PackageManager.PERMISSION_DENIED; 3529 } 3530 3531 @Override 3532 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3533 if (UserHandle.getCallingUserId() != userId) { 3534 mContext.enforceCallingPermission( 3535 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3536 "isPermissionRevokedByPolicy for user " + userId); 3537 } 3538 3539 if (checkPermission(permission, packageName, userId) 3540 == PackageManager.PERMISSION_GRANTED) { 3541 return false; 3542 } 3543 3544 final long identity = Binder.clearCallingIdentity(); 3545 try { 3546 final int flags = getPermissionFlags(permission, packageName, userId); 3547 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3548 } finally { 3549 Binder.restoreCallingIdentity(identity); 3550 } 3551 } 3552 3553 @Override 3554 public String getPermissionControllerPackageName() { 3555 synchronized (mPackages) { 3556 return mRequiredInstallerPackage; 3557 } 3558 } 3559 3560 /** 3561 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3562 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3563 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3564 * @param message the message to log on security exception 3565 */ 3566 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3567 boolean checkShell, String message) { 3568 if (userId < 0) { 3569 throw new IllegalArgumentException("Invalid userId " + userId); 3570 } 3571 if (checkShell) { 3572 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3573 } 3574 if (userId == UserHandle.getUserId(callingUid)) return; 3575 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3576 if (requireFullPermission) { 3577 mContext.enforceCallingOrSelfPermission( 3578 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3579 } else { 3580 try { 3581 mContext.enforceCallingOrSelfPermission( 3582 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3583 } catch (SecurityException se) { 3584 mContext.enforceCallingOrSelfPermission( 3585 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3586 } 3587 } 3588 } 3589 } 3590 3591 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3592 if (callingUid == Process.SHELL_UID) { 3593 if (userHandle >= 0 3594 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3595 throw new SecurityException("Shell does not have permission to access user " 3596 + userHandle); 3597 } else if (userHandle < 0) { 3598 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3599 + Debug.getCallers(3)); 3600 } 3601 } 3602 } 3603 3604 private BasePermission findPermissionTreeLP(String permName) { 3605 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3606 if (permName.startsWith(bp.name) && 3607 permName.length() > bp.name.length() && 3608 permName.charAt(bp.name.length()) == '.') { 3609 return bp; 3610 } 3611 } 3612 return null; 3613 } 3614 3615 private BasePermission checkPermissionTreeLP(String permName) { 3616 if (permName != null) { 3617 BasePermission bp = findPermissionTreeLP(permName); 3618 if (bp != null) { 3619 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3620 return bp; 3621 } 3622 throw new SecurityException("Calling uid " 3623 + Binder.getCallingUid() 3624 + " is not allowed to add to permission tree " 3625 + bp.name + " owned by uid " + bp.uid); 3626 } 3627 } 3628 throw new SecurityException("No permission tree found for " + permName); 3629 } 3630 3631 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3632 if (s1 == null) { 3633 return s2 == null; 3634 } 3635 if (s2 == null) { 3636 return false; 3637 } 3638 if (s1.getClass() != s2.getClass()) { 3639 return false; 3640 } 3641 return s1.equals(s2); 3642 } 3643 3644 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3645 if (pi1.icon != pi2.icon) return false; 3646 if (pi1.logo != pi2.logo) return false; 3647 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3648 if (!compareStrings(pi1.name, pi2.name)) return false; 3649 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3650 // We'll take care of setting this one. 3651 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3652 // These are not currently stored in settings. 3653 //if (!compareStrings(pi1.group, pi2.group)) return false; 3654 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3655 //if (pi1.labelRes != pi2.labelRes) return false; 3656 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3657 return true; 3658 } 3659 3660 int permissionInfoFootprint(PermissionInfo info) { 3661 int size = info.name.length(); 3662 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3663 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3664 return size; 3665 } 3666 3667 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3668 int size = 0; 3669 for (BasePermission perm : mSettings.mPermissions.values()) { 3670 if (perm.uid == tree.uid) { 3671 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3672 } 3673 } 3674 return size; 3675 } 3676 3677 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3678 // We calculate the max size of permissions defined by this uid and throw 3679 // if that plus the size of 'info' would exceed our stated maximum. 3680 if (tree.uid != Process.SYSTEM_UID) { 3681 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3682 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3683 throw new SecurityException("Permission tree size cap exceeded"); 3684 } 3685 } 3686 } 3687 3688 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3689 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3690 throw new SecurityException("Label must be specified in permission"); 3691 } 3692 BasePermission tree = checkPermissionTreeLP(info.name); 3693 BasePermission bp = mSettings.mPermissions.get(info.name); 3694 boolean added = bp == null; 3695 boolean changed = true; 3696 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3697 if (added) { 3698 enforcePermissionCapLocked(info, tree); 3699 bp = new BasePermission(info.name, tree.sourcePackage, 3700 BasePermission.TYPE_DYNAMIC); 3701 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3702 throw new SecurityException( 3703 "Not allowed to modify non-dynamic permission " 3704 + info.name); 3705 } else { 3706 if (bp.protectionLevel == fixedLevel 3707 && bp.perm.owner.equals(tree.perm.owner) 3708 && bp.uid == tree.uid 3709 && comparePermissionInfos(bp.perm.info, info)) { 3710 changed = false; 3711 } 3712 } 3713 bp.protectionLevel = fixedLevel; 3714 info = new PermissionInfo(info); 3715 info.protectionLevel = fixedLevel; 3716 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3717 bp.perm.info.packageName = tree.perm.info.packageName; 3718 bp.uid = tree.uid; 3719 if (added) { 3720 mSettings.mPermissions.put(info.name, bp); 3721 } 3722 if (changed) { 3723 if (!async) { 3724 mSettings.writeLPr(); 3725 } else { 3726 scheduleWriteSettingsLocked(); 3727 } 3728 } 3729 return added; 3730 } 3731 3732 @Override 3733 public boolean addPermission(PermissionInfo info) { 3734 synchronized (mPackages) { 3735 return addPermissionLocked(info, false); 3736 } 3737 } 3738 3739 @Override 3740 public boolean addPermissionAsync(PermissionInfo info) { 3741 synchronized (mPackages) { 3742 return addPermissionLocked(info, true); 3743 } 3744 } 3745 3746 @Override 3747 public void removePermission(String name) { 3748 synchronized (mPackages) { 3749 checkPermissionTreeLP(name); 3750 BasePermission bp = mSettings.mPermissions.get(name); 3751 if (bp != null) { 3752 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3753 throw new SecurityException( 3754 "Not allowed to modify non-dynamic permission " 3755 + name); 3756 } 3757 mSettings.mPermissions.remove(name); 3758 mSettings.writeLPr(); 3759 } 3760 } 3761 } 3762 3763 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3764 BasePermission bp) { 3765 int index = pkg.requestedPermissions.indexOf(bp.name); 3766 if (index == -1) { 3767 throw new SecurityException("Package " + pkg.packageName 3768 + " has not requested permission " + bp.name); 3769 } 3770 if (!bp.isRuntime() && !bp.isDevelopment()) { 3771 throw new SecurityException("Permission " + bp.name 3772 + " is not a changeable permission type"); 3773 } 3774 } 3775 3776 @Override 3777 public void grantRuntimePermission(String packageName, String name, final int userId) { 3778 if (!sUserManager.exists(userId)) { 3779 Log.e(TAG, "No such user:" + userId); 3780 return; 3781 } 3782 3783 mContext.enforceCallingOrSelfPermission( 3784 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3785 "grantRuntimePermission"); 3786 3787 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3788 "grantRuntimePermission"); 3789 3790 final int uid; 3791 final SettingBase sb; 3792 3793 synchronized (mPackages) { 3794 final PackageParser.Package pkg = mPackages.get(packageName); 3795 if (pkg == null) { 3796 throw new IllegalArgumentException("Unknown package: " + packageName); 3797 } 3798 3799 final BasePermission bp = mSettings.mPermissions.get(name); 3800 if (bp == null) { 3801 throw new IllegalArgumentException("Unknown permission: " + name); 3802 } 3803 3804 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3805 3806 // If a permission review is required for legacy apps we represent 3807 // their permissions as always granted runtime ones since we need 3808 // to keep the review required permission flag per user while an 3809 // install permission's state is shared across all users. 3810 if (Build.PERMISSIONS_REVIEW_REQUIRED 3811 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3812 && bp.isRuntime()) { 3813 return; 3814 } 3815 3816 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3817 sb = (SettingBase) pkg.mExtras; 3818 if (sb == null) { 3819 throw new IllegalArgumentException("Unknown package: " + packageName); 3820 } 3821 3822 final PermissionsState permissionsState = sb.getPermissionsState(); 3823 3824 final int flags = permissionsState.getPermissionFlags(name, userId); 3825 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3826 throw new SecurityException("Cannot grant system fixed permission " 3827 + name + " for package " + packageName); 3828 } 3829 3830 if (bp.isDevelopment()) { 3831 // Development permissions must be handled specially, since they are not 3832 // normal runtime permissions. For now they apply to all users. 3833 if (permissionsState.grantInstallPermission(bp) != 3834 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3835 scheduleWriteSettingsLocked(); 3836 } 3837 return; 3838 } 3839 3840 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3841 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3842 return; 3843 } 3844 3845 final int result = permissionsState.grantRuntimePermission(bp, userId); 3846 switch (result) { 3847 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3848 return; 3849 } 3850 3851 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3852 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3853 mHandler.post(new Runnable() { 3854 @Override 3855 public void run() { 3856 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3857 } 3858 }); 3859 } 3860 break; 3861 } 3862 3863 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3864 3865 // Not critical if that is lost - app has to request again. 3866 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3867 } 3868 3869 // Only need to do this if user is initialized. Otherwise it's a new user 3870 // and there are no processes running as the user yet and there's no need 3871 // to make an expensive call to remount processes for the changed permissions. 3872 if (READ_EXTERNAL_STORAGE.equals(name) 3873 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3874 final long token = Binder.clearCallingIdentity(); 3875 try { 3876 if (sUserManager.isInitialized(userId)) { 3877 MountServiceInternal mountServiceInternal = LocalServices.getService( 3878 MountServiceInternal.class); 3879 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3880 } 3881 } finally { 3882 Binder.restoreCallingIdentity(token); 3883 } 3884 } 3885 } 3886 3887 @Override 3888 public void revokeRuntimePermission(String packageName, String name, int userId) { 3889 if (!sUserManager.exists(userId)) { 3890 Log.e(TAG, "No such user:" + userId); 3891 return; 3892 } 3893 3894 mContext.enforceCallingOrSelfPermission( 3895 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3896 "revokeRuntimePermission"); 3897 3898 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3899 "revokeRuntimePermission"); 3900 3901 final int appId; 3902 3903 synchronized (mPackages) { 3904 final PackageParser.Package pkg = mPackages.get(packageName); 3905 if (pkg == null) { 3906 throw new IllegalArgumentException("Unknown package: " + packageName); 3907 } 3908 3909 final BasePermission bp = mSettings.mPermissions.get(name); 3910 if (bp == null) { 3911 throw new IllegalArgumentException("Unknown permission: " + name); 3912 } 3913 3914 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3915 3916 // If a permission review is required for legacy apps we represent 3917 // their permissions as always granted runtime ones since we need 3918 // to keep the review required permission flag per user while an 3919 // install permission's state is shared across all users. 3920 if (Build.PERMISSIONS_REVIEW_REQUIRED 3921 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3922 && bp.isRuntime()) { 3923 return; 3924 } 3925 3926 SettingBase sb = (SettingBase) pkg.mExtras; 3927 if (sb == null) { 3928 throw new IllegalArgumentException("Unknown package: " + packageName); 3929 } 3930 3931 final PermissionsState permissionsState = sb.getPermissionsState(); 3932 3933 final int flags = permissionsState.getPermissionFlags(name, userId); 3934 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3935 throw new SecurityException("Cannot revoke system fixed permission " 3936 + name + " for package " + packageName); 3937 } 3938 3939 if (bp.isDevelopment()) { 3940 // Development permissions must be handled specially, since they are not 3941 // normal runtime permissions. For now they apply to all users. 3942 if (permissionsState.revokeInstallPermission(bp) != 3943 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3944 scheduleWriteSettingsLocked(); 3945 } 3946 return; 3947 } 3948 3949 if (permissionsState.revokeRuntimePermission(bp, userId) == 3950 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3951 return; 3952 } 3953 3954 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3955 3956 // Critical, after this call app should never have the permission. 3957 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3958 3959 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3960 } 3961 3962 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3963 } 3964 3965 @Override 3966 public void resetRuntimePermissions() { 3967 mContext.enforceCallingOrSelfPermission( 3968 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3969 "revokeRuntimePermission"); 3970 3971 int callingUid = Binder.getCallingUid(); 3972 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3973 mContext.enforceCallingOrSelfPermission( 3974 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3975 "resetRuntimePermissions"); 3976 } 3977 3978 synchronized (mPackages) { 3979 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3980 for (int userId : UserManagerService.getInstance().getUserIds()) { 3981 final int packageCount = mPackages.size(); 3982 for (int i = 0; i < packageCount; i++) { 3983 PackageParser.Package pkg = mPackages.valueAt(i); 3984 if (!(pkg.mExtras instanceof PackageSetting)) { 3985 continue; 3986 } 3987 PackageSetting ps = (PackageSetting) pkg.mExtras; 3988 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3989 } 3990 } 3991 } 3992 } 3993 3994 @Override 3995 public int getPermissionFlags(String name, String packageName, int userId) { 3996 if (!sUserManager.exists(userId)) { 3997 return 0; 3998 } 3999 4000 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4001 4002 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4003 "getPermissionFlags"); 4004 4005 synchronized (mPackages) { 4006 final PackageParser.Package pkg = mPackages.get(packageName); 4007 if (pkg == null) { 4008 throw new IllegalArgumentException("Unknown package: " + packageName); 4009 } 4010 4011 final BasePermission bp = mSettings.mPermissions.get(name); 4012 if (bp == null) { 4013 throw new IllegalArgumentException("Unknown permission: " + name); 4014 } 4015 4016 SettingBase sb = (SettingBase) pkg.mExtras; 4017 if (sb == null) { 4018 throw new IllegalArgumentException("Unknown package: " + packageName); 4019 } 4020 4021 PermissionsState permissionsState = sb.getPermissionsState(); 4022 return permissionsState.getPermissionFlags(name, userId); 4023 } 4024 } 4025 4026 @Override 4027 public void updatePermissionFlags(String name, String packageName, int flagMask, 4028 int flagValues, int userId) { 4029 if (!sUserManager.exists(userId)) { 4030 return; 4031 } 4032 4033 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4034 4035 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4036 "updatePermissionFlags"); 4037 4038 // Only the system can change these flags and nothing else. 4039 if (getCallingUid() != Process.SYSTEM_UID) { 4040 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4041 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4042 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4043 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4044 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4045 } 4046 4047 synchronized (mPackages) { 4048 final PackageParser.Package pkg = mPackages.get(packageName); 4049 if (pkg == null) { 4050 throw new IllegalArgumentException("Unknown package: " + packageName); 4051 } 4052 4053 final BasePermission bp = mSettings.mPermissions.get(name); 4054 if (bp == null) { 4055 throw new IllegalArgumentException("Unknown permission: " + name); 4056 } 4057 4058 SettingBase sb = (SettingBase) pkg.mExtras; 4059 if (sb == null) { 4060 throw new IllegalArgumentException("Unknown package: " + packageName); 4061 } 4062 4063 PermissionsState permissionsState = sb.getPermissionsState(); 4064 4065 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4066 4067 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4068 // Install and runtime permissions are stored in different places, 4069 // so figure out what permission changed and persist the change. 4070 if (permissionsState.getInstallPermissionState(name) != null) { 4071 scheduleWriteSettingsLocked(); 4072 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4073 || hadState) { 4074 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4075 } 4076 } 4077 } 4078 } 4079 4080 /** 4081 * Update the permission flags for all packages and runtime permissions of a user in order 4082 * to allow device or profile owner to remove POLICY_FIXED. 4083 */ 4084 @Override 4085 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4086 if (!sUserManager.exists(userId)) { 4087 return; 4088 } 4089 4090 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4091 4092 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4093 "updatePermissionFlagsForAllApps"); 4094 4095 // Only the system can change system fixed flags. 4096 if (getCallingUid() != Process.SYSTEM_UID) { 4097 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4098 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4099 } 4100 4101 synchronized (mPackages) { 4102 boolean changed = false; 4103 final int packageCount = mPackages.size(); 4104 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4105 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4106 SettingBase sb = (SettingBase) pkg.mExtras; 4107 if (sb == null) { 4108 continue; 4109 } 4110 PermissionsState permissionsState = sb.getPermissionsState(); 4111 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4112 userId, flagMask, flagValues); 4113 } 4114 if (changed) { 4115 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4116 } 4117 } 4118 } 4119 4120 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4121 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4122 != PackageManager.PERMISSION_GRANTED 4123 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4124 != PackageManager.PERMISSION_GRANTED) { 4125 throw new SecurityException(message + " requires " 4126 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4127 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4128 } 4129 } 4130 4131 @Override 4132 public boolean shouldShowRequestPermissionRationale(String permissionName, 4133 String packageName, int userId) { 4134 if (UserHandle.getCallingUserId() != userId) { 4135 mContext.enforceCallingPermission( 4136 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4137 "canShowRequestPermissionRationale for user " + userId); 4138 } 4139 4140 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4141 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4142 return false; 4143 } 4144 4145 if (checkPermission(permissionName, packageName, userId) 4146 == PackageManager.PERMISSION_GRANTED) { 4147 return false; 4148 } 4149 4150 final int flags; 4151 4152 final long identity = Binder.clearCallingIdentity(); 4153 try { 4154 flags = getPermissionFlags(permissionName, 4155 packageName, userId); 4156 } finally { 4157 Binder.restoreCallingIdentity(identity); 4158 } 4159 4160 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4161 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4162 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4163 4164 if ((flags & fixedFlags) != 0) { 4165 return false; 4166 } 4167 4168 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4169 } 4170 4171 @Override 4172 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4173 mContext.enforceCallingOrSelfPermission( 4174 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4175 "addOnPermissionsChangeListener"); 4176 4177 synchronized (mPackages) { 4178 mOnPermissionChangeListeners.addListenerLocked(listener); 4179 } 4180 } 4181 4182 @Override 4183 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4184 synchronized (mPackages) { 4185 mOnPermissionChangeListeners.removeListenerLocked(listener); 4186 } 4187 } 4188 4189 @Override 4190 public boolean isProtectedBroadcast(String actionName) { 4191 synchronized (mPackages) { 4192 if (mProtectedBroadcasts.contains(actionName)) { 4193 return true; 4194 } else if (actionName != null) { 4195 // TODO: remove these terrible hacks 4196 if (actionName.startsWith("android.net.netmon.lingerExpired") 4197 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) { 4198 return true; 4199 } 4200 } 4201 } 4202 return false; 4203 } 4204 4205 @Override 4206 public int checkSignatures(String pkg1, String pkg2) { 4207 synchronized (mPackages) { 4208 final PackageParser.Package p1 = mPackages.get(pkg1); 4209 final PackageParser.Package p2 = mPackages.get(pkg2); 4210 if (p1 == null || p1.mExtras == null 4211 || p2 == null || p2.mExtras == null) { 4212 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4213 } 4214 return compareSignatures(p1.mSignatures, p2.mSignatures); 4215 } 4216 } 4217 4218 @Override 4219 public int checkUidSignatures(int uid1, int uid2) { 4220 // Map to base uids. 4221 uid1 = UserHandle.getAppId(uid1); 4222 uid2 = UserHandle.getAppId(uid2); 4223 // reader 4224 synchronized (mPackages) { 4225 Signature[] s1; 4226 Signature[] s2; 4227 Object obj = mSettings.getUserIdLPr(uid1); 4228 if (obj != null) { 4229 if (obj instanceof SharedUserSetting) { 4230 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4231 } else if (obj instanceof PackageSetting) { 4232 s1 = ((PackageSetting)obj).signatures.mSignatures; 4233 } else { 4234 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4235 } 4236 } else { 4237 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4238 } 4239 obj = mSettings.getUserIdLPr(uid2); 4240 if (obj != null) { 4241 if (obj instanceof SharedUserSetting) { 4242 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4243 } else if (obj instanceof PackageSetting) { 4244 s2 = ((PackageSetting)obj).signatures.mSignatures; 4245 } else { 4246 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4247 } 4248 } else { 4249 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4250 } 4251 return compareSignatures(s1, s2); 4252 } 4253 } 4254 4255 private void killUid(int appId, int userId, String reason) { 4256 final long identity = Binder.clearCallingIdentity(); 4257 try { 4258 IActivityManager am = ActivityManagerNative.getDefault(); 4259 if (am != null) { 4260 try { 4261 am.killUid(appId, userId, reason); 4262 } catch (RemoteException e) { 4263 /* ignore - same process */ 4264 } 4265 } 4266 } finally { 4267 Binder.restoreCallingIdentity(identity); 4268 } 4269 } 4270 4271 /** 4272 * Compares two sets of signatures. Returns: 4273 * <br /> 4274 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4275 * <br /> 4276 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4277 * <br /> 4278 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4279 * <br /> 4280 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4281 * <br /> 4282 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4283 */ 4284 static int compareSignatures(Signature[] s1, Signature[] s2) { 4285 if (s1 == null) { 4286 return s2 == null 4287 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4288 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4289 } 4290 4291 if (s2 == null) { 4292 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4293 } 4294 4295 if (s1.length != s2.length) { 4296 return PackageManager.SIGNATURE_NO_MATCH; 4297 } 4298 4299 // Since both signature sets are of size 1, we can compare without HashSets. 4300 if (s1.length == 1) { 4301 return s1[0].equals(s2[0]) ? 4302 PackageManager.SIGNATURE_MATCH : 4303 PackageManager.SIGNATURE_NO_MATCH; 4304 } 4305 4306 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4307 for (Signature sig : s1) { 4308 set1.add(sig); 4309 } 4310 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4311 for (Signature sig : s2) { 4312 set2.add(sig); 4313 } 4314 // Make sure s2 contains all signatures in s1. 4315 if (set1.equals(set2)) { 4316 return PackageManager.SIGNATURE_MATCH; 4317 } 4318 return PackageManager.SIGNATURE_NO_MATCH; 4319 } 4320 4321 /** 4322 * If the database version for this type of package (internal storage or 4323 * external storage) is less than the version where package signatures 4324 * were updated, return true. 4325 */ 4326 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4327 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4328 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4329 } 4330 4331 /** 4332 * Used for backward compatibility to make sure any packages with 4333 * certificate chains get upgraded to the new style. {@code existingSigs} 4334 * will be in the old format (since they were stored on disk from before the 4335 * system upgrade) and {@code scannedSigs} will be in the newer format. 4336 */ 4337 private int compareSignaturesCompat(PackageSignatures existingSigs, 4338 PackageParser.Package scannedPkg) { 4339 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4340 return PackageManager.SIGNATURE_NO_MATCH; 4341 } 4342 4343 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4344 for (Signature sig : existingSigs.mSignatures) { 4345 existingSet.add(sig); 4346 } 4347 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4348 for (Signature sig : scannedPkg.mSignatures) { 4349 try { 4350 Signature[] chainSignatures = sig.getChainSignatures(); 4351 for (Signature chainSig : chainSignatures) { 4352 scannedCompatSet.add(chainSig); 4353 } 4354 } catch (CertificateEncodingException e) { 4355 scannedCompatSet.add(sig); 4356 } 4357 } 4358 /* 4359 * Make sure the expanded scanned set contains all signatures in the 4360 * existing one. 4361 */ 4362 if (scannedCompatSet.equals(existingSet)) { 4363 // Migrate the old signatures to the new scheme. 4364 existingSigs.assignSignatures(scannedPkg.mSignatures); 4365 // The new KeySets will be re-added later in the scanning process. 4366 synchronized (mPackages) { 4367 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4368 } 4369 return PackageManager.SIGNATURE_MATCH; 4370 } 4371 return PackageManager.SIGNATURE_NO_MATCH; 4372 } 4373 4374 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4375 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4376 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4377 } 4378 4379 private int compareSignaturesRecover(PackageSignatures existingSigs, 4380 PackageParser.Package scannedPkg) { 4381 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4382 return PackageManager.SIGNATURE_NO_MATCH; 4383 } 4384 4385 String msg = null; 4386 try { 4387 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4388 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4389 + scannedPkg.packageName); 4390 return PackageManager.SIGNATURE_MATCH; 4391 } 4392 } catch (CertificateException e) { 4393 msg = e.getMessage(); 4394 } 4395 4396 logCriticalInfo(Log.INFO, 4397 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4398 return PackageManager.SIGNATURE_NO_MATCH; 4399 } 4400 4401 @Override 4402 public String[] getPackagesForUid(int uid) { 4403 uid = UserHandle.getAppId(uid); 4404 // reader 4405 synchronized (mPackages) { 4406 Object obj = mSettings.getUserIdLPr(uid); 4407 if (obj instanceof SharedUserSetting) { 4408 final SharedUserSetting sus = (SharedUserSetting) obj; 4409 final int N = sus.packages.size(); 4410 final String[] res = new String[N]; 4411 final Iterator<PackageSetting> it = sus.packages.iterator(); 4412 int i = 0; 4413 while (it.hasNext()) { 4414 res[i++] = it.next().name; 4415 } 4416 return res; 4417 } else if (obj instanceof PackageSetting) { 4418 final PackageSetting ps = (PackageSetting) obj; 4419 return new String[] { ps.name }; 4420 } 4421 } 4422 return null; 4423 } 4424 4425 @Override 4426 public String getNameForUid(int uid) { 4427 // reader 4428 synchronized (mPackages) { 4429 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4430 if (obj instanceof SharedUserSetting) { 4431 final SharedUserSetting sus = (SharedUserSetting) obj; 4432 return sus.name + ":" + sus.userId; 4433 } else if (obj instanceof PackageSetting) { 4434 final PackageSetting ps = (PackageSetting) obj; 4435 return ps.name; 4436 } 4437 } 4438 return null; 4439 } 4440 4441 @Override 4442 public int getUidForSharedUser(String sharedUserName) { 4443 if(sharedUserName == null) { 4444 return -1; 4445 } 4446 // reader 4447 synchronized (mPackages) { 4448 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4449 if (suid == null) { 4450 return -1; 4451 } 4452 return suid.userId; 4453 } 4454 } 4455 4456 @Override 4457 public int getFlagsForUid(int uid) { 4458 synchronized (mPackages) { 4459 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4460 if (obj instanceof SharedUserSetting) { 4461 final SharedUserSetting sus = (SharedUserSetting) obj; 4462 return sus.pkgFlags; 4463 } else if (obj instanceof PackageSetting) { 4464 final PackageSetting ps = (PackageSetting) obj; 4465 return ps.pkgFlags; 4466 } 4467 } 4468 return 0; 4469 } 4470 4471 @Override 4472 public int getPrivateFlagsForUid(int uid) { 4473 synchronized (mPackages) { 4474 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4475 if (obj instanceof SharedUserSetting) { 4476 final SharedUserSetting sus = (SharedUserSetting) obj; 4477 return sus.pkgPrivateFlags; 4478 } else if (obj instanceof PackageSetting) { 4479 final PackageSetting ps = (PackageSetting) obj; 4480 return ps.pkgPrivateFlags; 4481 } 4482 } 4483 return 0; 4484 } 4485 4486 @Override 4487 public boolean isUidPrivileged(int uid) { 4488 uid = UserHandle.getAppId(uid); 4489 // reader 4490 synchronized (mPackages) { 4491 Object obj = mSettings.getUserIdLPr(uid); 4492 if (obj instanceof SharedUserSetting) { 4493 final SharedUserSetting sus = (SharedUserSetting) obj; 4494 final Iterator<PackageSetting> it = sus.packages.iterator(); 4495 while (it.hasNext()) { 4496 if (it.next().isPrivileged()) { 4497 return true; 4498 } 4499 } 4500 } else if (obj instanceof PackageSetting) { 4501 final PackageSetting ps = (PackageSetting) obj; 4502 return ps.isPrivileged(); 4503 } 4504 } 4505 return false; 4506 } 4507 4508 @Override 4509 public String[] getAppOpPermissionPackages(String permissionName) { 4510 synchronized (mPackages) { 4511 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4512 if (pkgs == null) { 4513 return null; 4514 } 4515 return pkgs.toArray(new String[pkgs.size()]); 4516 } 4517 } 4518 4519 @Override 4520 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4521 int flags, int userId) { 4522 if (!sUserManager.exists(userId)) return null; 4523 flags = updateFlagsForResolve(flags, userId, intent); 4524 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4525 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4526 final ResolveInfo bestChoice = 4527 chooseBestActivity(intent, resolvedType, flags, query, userId); 4528 4529 if (isEphemeralAllowed(intent, query, userId)) { 4530 final EphemeralResolveInfo ai = 4531 getEphemeralResolveInfo(intent, resolvedType, userId); 4532 if (ai != null) { 4533 if (DEBUG_EPHEMERAL) { 4534 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4535 } 4536 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4537 bestChoice.ephemeralResolveInfo = ai; 4538 } 4539 } 4540 return bestChoice; 4541 } 4542 4543 @Override 4544 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4545 IntentFilter filter, int match, ComponentName activity) { 4546 final int userId = UserHandle.getCallingUserId(); 4547 if (DEBUG_PREFERRED) { 4548 Log.v(TAG, "setLastChosenActivity intent=" + intent 4549 + " resolvedType=" + resolvedType 4550 + " flags=" + flags 4551 + " filter=" + filter 4552 + " match=" + match 4553 + " activity=" + activity); 4554 filter.dump(new PrintStreamPrinter(System.out), " "); 4555 } 4556 intent.setComponent(null); 4557 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4558 // Find any earlier preferred or last chosen entries and nuke them 4559 findPreferredActivity(intent, resolvedType, 4560 flags, query, 0, false, true, false, userId); 4561 // Add the new activity as the last chosen for this filter 4562 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4563 "Setting last chosen"); 4564 } 4565 4566 @Override 4567 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4568 final int userId = UserHandle.getCallingUserId(); 4569 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4570 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4571 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4572 false, false, false, userId); 4573 } 4574 4575 4576 private boolean isEphemeralAllowed( 4577 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4578 // Short circuit and return early if possible. 4579 if (DISABLE_EPHEMERAL_APPS) { 4580 return false; 4581 } 4582 final int callingUser = UserHandle.getCallingUserId(); 4583 if (callingUser != UserHandle.USER_SYSTEM) { 4584 return false; 4585 } 4586 if (mEphemeralResolverConnection == null) { 4587 return false; 4588 } 4589 if (intent.getComponent() != null) { 4590 return false; 4591 } 4592 if (intent.getPackage() != null) { 4593 return false; 4594 } 4595 final boolean isWebUri = hasWebURI(intent); 4596 if (!isWebUri) { 4597 return false; 4598 } 4599 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4600 synchronized (mPackages) { 4601 final int count = resolvedActivites.size(); 4602 for (int n = 0; n < count; n++) { 4603 ResolveInfo info = resolvedActivites.get(n); 4604 String packageName = info.activityInfo.packageName; 4605 PackageSetting ps = mSettings.mPackages.get(packageName); 4606 if (ps != null) { 4607 // Try to get the status from User settings first 4608 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4609 int status = (int) (packedStatus >> 32); 4610 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4611 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4612 if (DEBUG_EPHEMERAL) { 4613 Slog.v(TAG, "DENY ephemeral apps;" 4614 + " pkg: " + packageName + ", status: " + status); 4615 } 4616 return false; 4617 } 4618 } 4619 } 4620 } 4621 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4622 return true; 4623 } 4624 4625 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4626 int userId) { 4627 MessageDigest digest = null; 4628 try { 4629 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4630 } catch (NoSuchAlgorithmException e) { 4631 // If we can't create a digest, ignore ephemeral apps. 4632 return null; 4633 } 4634 4635 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4636 final byte[] digestBytes = digest.digest(hostBytes); 4637 int shaPrefix = 4638 digestBytes[0] << 24 4639 | digestBytes[1] << 16 4640 | digestBytes[2] << 8 4641 | digestBytes[3] << 0; 4642 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4643 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4644 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4645 // No hash prefix match; there are no ephemeral apps for this domain. 4646 return null; 4647 } 4648 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4649 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4650 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4651 continue; 4652 } 4653 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4654 // No filters; this should never happen. 4655 if (filters.isEmpty()) { 4656 continue; 4657 } 4658 // We have a domain match; resolve the filters to see if anything matches. 4659 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4660 for (int j = filters.size() - 1; j >= 0; --j) { 4661 final EphemeralResolveIntentInfo intentInfo = 4662 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4663 ephemeralResolver.addFilter(intentInfo); 4664 } 4665 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4666 intent, resolvedType, false /*defaultOnly*/, userId); 4667 if (!matchedResolveInfoList.isEmpty()) { 4668 return matchedResolveInfoList.get(0); 4669 } 4670 } 4671 // Hash or filter mis-match; no ephemeral apps for this domain. 4672 return null; 4673 } 4674 4675 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4676 int flags, List<ResolveInfo> query, int userId) { 4677 if (query != null) { 4678 final int N = query.size(); 4679 if (N == 1) { 4680 return query.get(0); 4681 } else if (N > 1) { 4682 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4683 // If there is more than one activity with the same priority, 4684 // then let the user decide between them. 4685 ResolveInfo r0 = query.get(0); 4686 ResolveInfo r1 = query.get(1); 4687 if (DEBUG_INTENT_MATCHING || debug) { 4688 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4689 + r1.activityInfo.name + "=" + r1.priority); 4690 } 4691 // If the first activity has a higher priority, or a different 4692 // default, then it is always desirable to pick it. 4693 if (r0.priority != r1.priority 4694 || r0.preferredOrder != r1.preferredOrder 4695 || r0.isDefault != r1.isDefault) { 4696 return query.get(0); 4697 } 4698 // If we have saved a preference for a preferred activity for 4699 // this Intent, use that. 4700 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4701 flags, query, r0.priority, true, false, debug, userId); 4702 if (ri != null) { 4703 return ri; 4704 } 4705 ri = new ResolveInfo(mResolveInfo); 4706 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4707 ri.activityInfo.applicationInfo = new ApplicationInfo( 4708 ri.activityInfo.applicationInfo); 4709 if (userId != 0) { 4710 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4711 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4712 } 4713 // Make sure that the resolver is displayable in car mode 4714 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4715 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4716 return ri; 4717 } 4718 } 4719 return null; 4720 } 4721 4722 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4723 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4724 final int N = query.size(); 4725 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4726 .get(userId); 4727 // Get the list of persistent preferred activities that handle the intent 4728 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4729 List<PersistentPreferredActivity> pprefs = ppir != null 4730 ? ppir.queryIntent(intent, resolvedType, 4731 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4732 : null; 4733 if (pprefs != null && pprefs.size() > 0) { 4734 final int M = pprefs.size(); 4735 for (int i=0; i<M; i++) { 4736 final PersistentPreferredActivity ppa = pprefs.get(i); 4737 if (DEBUG_PREFERRED || debug) { 4738 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4739 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4740 + "\n component=" + ppa.mComponent); 4741 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4742 } 4743 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4744 flags | MATCH_DISABLED_COMPONENTS, userId); 4745 if (DEBUG_PREFERRED || debug) { 4746 Slog.v(TAG, "Found persistent preferred activity:"); 4747 if (ai != null) { 4748 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4749 } else { 4750 Slog.v(TAG, " null"); 4751 } 4752 } 4753 if (ai == null) { 4754 // This previously registered persistent preferred activity 4755 // component is no longer known. Ignore it and do NOT remove it. 4756 continue; 4757 } 4758 for (int j=0; j<N; j++) { 4759 final ResolveInfo ri = query.get(j); 4760 if (!ri.activityInfo.applicationInfo.packageName 4761 .equals(ai.applicationInfo.packageName)) { 4762 continue; 4763 } 4764 if (!ri.activityInfo.name.equals(ai.name)) { 4765 continue; 4766 } 4767 // Found a persistent preference that can handle the intent. 4768 if (DEBUG_PREFERRED || debug) { 4769 Slog.v(TAG, "Returning persistent preferred activity: " + 4770 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4771 } 4772 return ri; 4773 } 4774 } 4775 } 4776 return null; 4777 } 4778 4779 // TODO: handle preferred activities missing while user has amnesia 4780 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4781 List<ResolveInfo> query, int priority, boolean always, 4782 boolean removeMatches, boolean debug, int userId) { 4783 if (!sUserManager.exists(userId)) return null; 4784 flags = updateFlagsForResolve(flags, userId, intent); 4785 // writer 4786 synchronized (mPackages) { 4787 if (intent.getSelector() != null) { 4788 intent = intent.getSelector(); 4789 } 4790 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4791 4792 // Try to find a matching persistent preferred activity. 4793 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4794 debug, userId); 4795 4796 // If a persistent preferred activity matched, use it. 4797 if (pri != null) { 4798 return pri; 4799 } 4800 4801 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4802 // Get the list of preferred activities that handle the intent 4803 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4804 List<PreferredActivity> prefs = pir != null 4805 ? pir.queryIntent(intent, resolvedType, 4806 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4807 : null; 4808 if (prefs != null && prefs.size() > 0) { 4809 boolean changed = false; 4810 try { 4811 // First figure out how good the original match set is. 4812 // We will only allow preferred activities that came 4813 // from the same match quality. 4814 int match = 0; 4815 4816 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4817 4818 final int N = query.size(); 4819 for (int j=0; j<N; j++) { 4820 final ResolveInfo ri = query.get(j); 4821 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4822 + ": 0x" + Integer.toHexString(match)); 4823 if (ri.match > match) { 4824 match = ri.match; 4825 } 4826 } 4827 4828 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4829 + Integer.toHexString(match)); 4830 4831 match &= IntentFilter.MATCH_CATEGORY_MASK; 4832 final int M = prefs.size(); 4833 for (int i=0; i<M; i++) { 4834 final PreferredActivity pa = prefs.get(i); 4835 if (DEBUG_PREFERRED || debug) { 4836 Slog.v(TAG, "Checking PreferredActivity ds=" 4837 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4838 + "\n component=" + pa.mPref.mComponent); 4839 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4840 } 4841 if (pa.mPref.mMatch != match) { 4842 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4843 + Integer.toHexString(pa.mPref.mMatch)); 4844 continue; 4845 } 4846 // If it's not an "always" type preferred activity and that's what we're 4847 // looking for, skip it. 4848 if (always && !pa.mPref.mAlways) { 4849 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4850 continue; 4851 } 4852 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4853 flags | MATCH_DISABLED_COMPONENTS, userId); 4854 if (DEBUG_PREFERRED || debug) { 4855 Slog.v(TAG, "Found preferred activity:"); 4856 if (ai != null) { 4857 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4858 } else { 4859 Slog.v(TAG, " null"); 4860 } 4861 } 4862 if (ai == null) { 4863 // This previously registered preferred activity 4864 // component is no longer known. Most likely an update 4865 // to the app was installed and in the new version this 4866 // component no longer exists. Clean it up by removing 4867 // it from the preferred activities list, and skip it. 4868 Slog.w(TAG, "Removing dangling preferred activity: " 4869 + pa.mPref.mComponent); 4870 pir.removeFilter(pa); 4871 changed = true; 4872 continue; 4873 } 4874 for (int j=0; j<N; j++) { 4875 final ResolveInfo ri = query.get(j); 4876 if (!ri.activityInfo.applicationInfo.packageName 4877 .equals(ai.applicationInfo.packageName)) { 4878 continue; 4879 } 4880 if (!ri.activityInfo.name.equals(ai.name)) { 4881 continue; 4882 } 4883 4884 if (removeMatches) { 4885 pir.removeFilter(pa); 4886 changed = true; 4887 if (DEBUG_PREFERRED) { 4888 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4889 } 4890 break; 4891 } 4892 4893 // Okay we found a previously set preferred or last chosen app. 4894 // If the result set is different from when this 4895 // was created, we need to clear it and re-ask the 4896 // user their preference, if we're looking for an "always" type entry. 4897 if (always && !pa.mPref.sameSet(query)) { 4898 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4899 + intent + " type " + resolvedType); 4900 if (DEBUG_PREFERRED) { 4901 Slog.v(TAG, "Removing preferred activity since set changed " 4902 + pa.mPref.mComponent); 4903 } 4904 pir.removeFilter(pa); 4905 // Re-add the filter as a "last chosen" entry (!always) 4906 PreferredActivity lastChosen = new PreferredActivity( 4907 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4908 pir.addFilter(lastChosen); 4909 changed = true; 4910 return null; 4911 } 4912 4913 // Yay! Either the set matched or we're looking for the last chosen 4914 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4915 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4916 return ri; 4917 } 4918 } 4919 } finally { 4920 if (changed) { 4921 if (DEBUG_PREFERRED) { 4922 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4923 } 4924 scheduleWritePackageRestrictionsLocked(userId); 4925 } 4926 } 4927 } 4928 } 4929 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4930 return null; 4931 } 4932 4933 /* 4934 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4935 */ 4936 @Override 4937 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4938 int targetUserId) { 4939 mContext.enforceCallingOrSelfPermission( 4940 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4941 List<CrossProfileIntentFilter> matches = 4942 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4943 if (matches != null) { 4944 int size = matches.size(); 4945 for (int i = 0; i < size; i++) { 4946 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4947 } 4948 } 4949 if (hasWebURI(intent)) { 4950 // cross-profile app linking works only towards the parent. 4951 final UserInfo parent = getProfileParent(sourceUserId); 4952 synchronized(mPackages) { 4953 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4954 intent, resolvedType, 0, sourceUserId, parent.id); 4955 return xpDomainInfo != null; 4956 } 4957 } 4958 return false; 4959 } 4960 4961 private UserInfo getProfileParent(int userId) { 4962 final long identity = Binder.clearCallingIdentity(); 4963 try { 4964 return sUserManager.getProfileParent(userId); 4965 } finally { 4966 Binder.restoreCallingIdentity(identity); 4967 } 4968 } 4969 4970 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4971 String resolvedType, int userId) { 4972 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4973 if (resolver != null) { 4974 return resolver.queryIntent(intent, resolvedType, false, userId); 4975 } 4976 return null; 4977 } 4978 4979 @Override 4980 public List<ResolveInfo> queryIntentActivities(Intent intent, 4981 String resolvedType, int flags, int userId) { 4982 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4983 flags = updateFlagsForResolve(flags, userId, intent); 4984 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4985 ComponentName comp = intent.getComponent(); 4986 if (comp == null) { 4987 if (intent.getSelector() != null) { 4988 intent = intent.getSelector(); 4989 comp = intent.getComponent(); 4990 } 4991 } 4992 4993 if (comp != null) { 4994 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4995 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4996 if (ai != null) { 4997 final ResolveInfo ri = new ResolveInfo(); 4998 ri.activityInfo = ai; 4999 list.add(ri); 5000 } 5001 return list; 5002 } 5003 5004 // reader 5005 synchronized (mPackages) { 5006 final String pkgName = intent.getPackage(); 5007 if (pkgName == null) { 5008 List<CrossProfileIntentFilter> matchingFilters = 5009 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5010 // Check for results that need to skip the current profile. 5011 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5012 resolvedType, flags, userId); 5013 if (xpResolveInfo != null) { 5014 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5015 result.add(xpResolveInfo); 5016 return filterIfNotSystemUser(result, userId); 5017 } 5018 5019 // Check for results in the current profile. 5020 List<ResolveInfo> result = mActivities.queryIntent( 5021 intent, resolvedType, flags, userId); 5022 result = filterIfNotSystemUser(result, userId); 5023 5024 // Check for cross profile results. 5025 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5026 xpResolveInfo = queryCrossProfileIntents( 5027 matchingFilters, intent, resolvedType, flags, userId, 5028 hasNonNegativePriorityResult); 5029 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5030 boolean isVisibleToUser = filterIfNotSystemUser( 5031 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5032 if (isVisibleToUser) { 5033 result.add(xpResolveInfo); 5034 Collections.sort(result, mResolvePrioritySorter); 5035 } 5036 } 5037 if (hasWebURI(intent)) { 5038 CrossProfileDomainInfo xpDomainInfo = null; 5039 final UserInfo parent = getProfileParent(userId); 5040 if (parent != null) { 5041 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5042 flags, userId, parent.id); 5043 } 5044 if (xpDomainInfo != null) { 5045 if (xpResolveInfo != null) { 5046 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5047 // in the result. 5048 result.remove(xpResolveInfo); 5049 } 5050 if (result.size() == 0) { 5051 result.add(xpDomainInfo.resolveInfo); 5052 return result; 5053 } 5054 } else if (result.size() <= 1) { 5055 return result; 5056 } 5057 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5058 xpDomainInfo, userId); 5059 Collections.sort(result, mResolvePrioritySorter); 5060 } 5061 return result; 5062 } 5063 final PackageParser.Package pkg = mPackages.get(pkgName); 5064 if (pkg != null) { 5065 return filterIfNotSystemUser( 5066 mActivities.queryIntentForPackage( 5067 intent, resolvedType, flags, pkg.activities, userId), 5068 userId); 5069 } 5070 return new ArrayList<ResolveInfo>(); 5071 } 5072 } 5073 5074 private static class CrossProfileDomainInfo { 5075 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5076 ResolveInfo resolveInfo; 5077 /* Best domain verification status of the activities found in the other profile */ 5078 int bestDomainVerificationStatus; 5079 } 5080 5081 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5082 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5083 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5084 sourceUserId)) { 5085 return null; 5086 } 5087 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5088 resolvedType, flags, parentUserId); 5089 5090 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5091 return null; 5092 } 5093 CrossProfileDomainInfo result = null; 5094 int size = resultTargetUser.size(); 5095 for (int i = 0; i < size; i++) { 5096 ResolveInfo riTargetUser = resultTargetUser.get(i); 5097 // Intent filter verification is only for filters that specify a host. So don't return 5098 // those that handle all web uris. 5099 if (riTargetUser.handleAllWebDataURI) { 5100 continue; 5101 } 5102 String packageName = riTargetUser.activityInfo.packageName; 5103 PackageSetting ps = mSettings.mPackages.get(packageName); 5104 if (ps == null) { 5105 continue; 5106 } 5107 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5108 int status = (int)(verificationState >> 32); 5109 if (result == null) { 5110 result = new CrossProfileDomainInfo(); 5111 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5112 sourceUserId, parentUserId); 5113 result.bestDomainVerificationStatus = status; 5114 } else { 5115 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5116 result.bestDomainVerificationStatus); 5117 } 5118 } 5119 // Don't consider matches with status NEVER across profiles. 5120 if (result != null && result.bestDomainVerificationStatus 5121 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5122 return null; 5123 } 5124 return result; 5125 } 5126 5127 /** 5128 * Verification statuses are ordered from the worse to the best, except for 5129 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5130 */ 5131 private int bestDomainVerificationStatus(int status1, int status2) { 5132 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5133 return status2; 5134 } 5135 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5136 return status1; 5137 } 5138 return (int) MathUtils.max(status1, status2); 5139 } 5140 5141 private boolean isUserEnabled(int userId) { 5142 long callingId = Binder.clearCallingIdentity(); 5143 try { 5144 UserInfo userInfo = sUserManager.getUserInfo(userId); 5145 return userInfo != null && userInfo.isEnabled(); 5146 } finally { 5147 Binder.restoreCallingIdentity(callingId); 5148 } 5149 } 5150 5151 /** 5152 * Filter out activities with systemUserOnly flag set, when current user is not System. 5153 * 5154 * @return filtered list 5155 */ 5156 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5157 if (userId == UserHandle.USER_SYSTEM) { 5158 return resolveInfos; 5159 } 5160 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5161 ResolveInfo info = resolveInfos.get(i); 5162 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5163 resolveInfos.remove(i); 5164 } 5165 } 5166 return resolveInfos; 5167 } 5168 5169 /** 5170 * @param resolveInfos list of resolve infos in descending priority order 5171 * @return if the list contains a resolve info with non-negative priority 5172 */ 5173 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5174 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5175 } 5176 5177 private static boolean hasWebURI(Intent intent) { 5178 if (intent.getData() == null) { 5179 return false; 5180 } 5181 final String scheme = intent.getScheme(); 5182 if (TextUtils.isEmpty(scheme)) { 5183 return false; 5184 } 5185 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5186 } 5187 5188 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5189 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5190 int userId) { 5191 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5192 5193 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5194 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5195 candidates.size()); 5196 } 5197 5198 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5199 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5200 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5201 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5202 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5203 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5204 5205 synchronized (mPackages) { 5206 final int count = candidates.size(); 5207 // First, try to use linked apps. Partition the candidates into four lists: 5208 // one for the final results, one for the "do not use ever", one for "undefined status" 5209 // and finally one for "browser app type". 5210 for (int n=0; n<count; n++) { 5211 ResolveInfo info = candidates.get(n); 5212 String packageName = info.activityInfo.packageName; 5213 PackageSetting ps = mSettings.mPackages.get(packageName); 5214 if (ps != null) { 5215 // Add to the special match all list (Browser use case) 5216 if (info.handleAllWebDataURI) { 5217 matchAllList.add(info); 5218 continue; 5219 } 5220 // Try to get the status from User settings first 5221 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5222 int status = (int)(packedStatus >> 32); 5223 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5224 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5225 if (DEBUG_DOMAIN_VERIFICATION) { 5226 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5227 + " : linkgen=" + linkGeneration); 5228 } 5229 // Use link-enabled generation as preferredOrder, i.e. 5230 // prefer newly-enabled over earlier-enabled. 5231 info.preferredOrder = linkGeneration; 5232 alwaysList.add(info); 5233 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5234 if (DEBUG_DOMAIN_VERIFICATION) { 5235 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5236 } 5237 neverList.add(info); 5238 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5239 if (DEBUG_DOMAIN_VERIFICATION) { 5240 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5241 } 5242 alwaysAskList.add(info); 5243 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5244 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5245 if (DEBUG_DOMAIN_VERIFICATION) { 5246 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5247 } 5248 undefinedList.add(info); 5249 } 5250 } 5251 } 5252 5253 // We'll want to include browser possibilities in a few cases 5254 boolean includeBrowser = false; 5255 5256 // First try to add the "always" resolution(s) for the current user, if any 5257 if (alwaysList.size() > 0) { 5258 result.addAll(alwaysList); 5259 } else { 5260 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5261 result.addAll(undefinedList); 5262 // Maybe add one for the other profile. 5263 if (xpDomainInfo != null && ( 5264 xpDomainInfo.bestDomainVerificationStatus 5265 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5266 result.add(xpDomainInfo.resolveInfo); 5267 } 5268 includeBrowser = true; 5269 } 5270 5271 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5272 // If there were 'always' entries their preferred order has been set, so we also 5273 // back that off to make the alternatives equivalent 5274 if (alwaysAskList.size() > 0) { 5275 for (ResolveInfo i : result) { 5276 i.preferredOrder = 0; 5277 } 5278 result.addAll(alwaysAskList); 5279 includeBrowser = true; 5280 } 5281 5282 if (includeBrowser) { 5283 // Also add browsers (all of them or only the default one) 5284 if (DEBUG_DOMAIN_VERIFICATION) { 5285 Slog.v(TAG, " ...including browsers in candidate set"); 5286 } 5287 if ((matchFlags & MATCH_ALL) != 0) { 5288 result.addAll(matchAllList); 5289 } else { 5290 // Browser/generic handling case. If there's a default browser, go straight 5291 // to that (but only if there is no other higher-priority match). 5292 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5293 int maxMatchPrio = 0; 5294 ResolveInfo defaultBrowserMatch = null; 5295 final int numCandidates = matchAllList.size(); 5296 for (int n = 0; n < numCandidates; n++) { 5297 ResolveInfo info = matchAllList.get(n); 5298 // track the highest overall match priority... 5299 if (info.priority > maxMatchPrio) { 5300 maxMatchPrio = info.priority; 5301 } 5302 // ...and the highest-priority default browser match 5303 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5304 if (defaultBrowserMatch == null 5305 || (defaultBrowserMatch.priority < info.priority)) { 5306 if (debug) { 5307 Slog.v(TAG, "Considering default browser match " + info); 5308 } 5309 defaultBrowserMatch = info; 5310 } 5311 } 5312 } 5313 if (defaultBrowserMatch != null 5314 && defaultBrowserMatch.priority >= maxMatchPrio 5315 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5316 { 5317 if (debug) { 5318 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5319 } 5320 result.add(defaultBrowserMatch); 5321 } else { 5322 result.addAll(matchAllList); 5323 } 5324 } 5325 5326 // If there is nothing selected, add all candidates and remove the ones that the user 5327 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5328 if (result.size() == 0) { 5329 result.addAll(candidates); 5330 result.removeAll(neverList); 5331 } 5332 } 5333 } 5334 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5335 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5336 result.size()); 5337 for (ResolveInfo info : result) { 5338 Slog.v(TAG, " + " + info.activityInfo); 5339 } 5340 } 5341 return result; 5342 } 5343 5344 // Returns a packed value as a long: 5345 // 5346 // high 'int'-sized word: link status: undefined/ask/never/always. 5347 // low 'int'-sized word: relative priority among 'always' results. 5348 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5349 long result = ps.getDomainVerificationStatusForUser(userId); 5350 // if none available, get the master status 5351 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5352 if (ps.getIntentFilterVerificationInfo() != null) { 5353 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5354 } 5355 } 5356 return result; 5357 } 5358 5359 private ResolveInfo querySkipCurrentProfileIntents( 5360 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5361 int flags, int sourceUserId) { 5362 if (matchingFilters != null) { 5363 int size = matchingFilters.size(); 5364 for (int i = 0; i < size; i ++) { 5365 CrossProfileIntentFilter filter = matchingFilters.get(i); 5366 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5367 // Checking if there are activities in the target user that can handle the 5368 // intent. 5369 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5370 resolvedType, flags, sourceUserId); 5371 if (resolveInfo != null) { 5372 return resolveInfo; 5373 } 5374 } 5375 } 5376 } 5377 return null; 5378 } 5379 5380 // Return matching ResolveInfo in target user if any. 5381 private ResolveInfo queryCrossProfileIntents( 5382 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5383 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5384 if (matchingFilters != null) { 5385 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5386 // match the same intent. For performance reasons, it is better not to 5387 // run queryIntent twice for the same userId 5388 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5389 int size = matchingFilters.size(); 5390 for (int i = 0; i < size; i++) { 5391 CrossProfileIntentFilter filter = matchingFilters.get(i); 5392 int targetUserId = filter.getTargetUserId(); 5393 boolean skipCurrentProfile = 5394 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5395 boolean skipCurrentProfileIfNoMatchFound = 5396 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5397 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5398 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5399 // Checking if there are activities in the target user that can handle the 5400 // intent. 5401 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5402 resolvedType, flags, sourceUserId); 5403 if (resolveInfo != null) return resolveInfo; 5404 alreadyTriedUserIds.put(targetUserId, true); 5405 } 5406 } 5407 } 5408 return null; 5409 } 5410 5411 /** 5412 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5413 * will forward the intent to the filter's target user. 5414 * Otherwise, returns null. 5415 */ 5416 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5417 String resolvedType, int flags, int sourceUserId) { 5418 int targetUserId = filter.getTargetUserId(); 5419 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5420 resolvedType, flags, targetUserId); 5421 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5422 // If all the matches in the target profile are suspended, return null. 5423 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5424 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5425 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5426 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5427 targetUserId); 5428 } 5429 } 5430 } 5431 return null; 5432 } 5433 5434 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5435 int sourceUserId, int targetUserId) { 5436 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5437 long ident = Binder.clearCallingIdentity(); 5438 boolean targetIsProfile; 5439 try { 5440 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5441 } finally { 5442 Binder.restoreCallingIdentity(ident); 5443 } 5444 String className; 5445 if (targetIsProfile) { 5446 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5447 } else { 5448 className = FORWARD_INTENT_TO_PARENT; 5449 } 5450 ComponentName forwardingActivityComponentName = new ComponentName( 5451 mAndroidApplication.packageName, className); 5452 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5453 sourceUserId); 5454 if (!targetIsProfile) { 5455 forwardingActivityInfo.showUserIcon = targetUserId; 5456 forwardingResolveInfo.noResourceId = true; 5457 } 5458 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5459 forwardingResolveInfo.priority = 0; 5460 forwardingResolveInfo.preferredOrder = 0; 5461 forwardingResolveInfo.match = 0; 5462 forwardingResolveInfo.isDefault = true; 5463 forwardingResolveInfo.filter = filter; 5464 forwardingResolveInfo.targetUserId = targetUserId; 5465 return forwardingResolveInfo; 5466 } 5467 5468 @Override 5469 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5470 Intent[] specifics, String[] specificTypes, Intent intent, 5471 String resolvedType, int flags, int userId) { 5472 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5473 flags = updateFlagsForResolve(flags, userId, intent); 5474 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5475 false, "query intent activity options"); 5476 final String resultsAction = intent.getAction(); 5477 5478 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5479 | PackageManager.GET_RESOLVED_FILTER, userId); 5480 5481 if (DEBUG_INTENT_MATCHING) { 5482 Log.v(TAG, "Query " + intent + ": " + results); 5483 } 5484 5485 int specificsPos = 0; 5486 int N; 5487 5488 // todo: note that the algorithm used here is O(N^2). This 5489 // isn't a problem in our current environment, but if we start running 5490 // into situations where we have more than 5 or 10 matches then this 5491 // should probably be changed to something smarter... 5492 5493 // First we go through and resolve each of the specific items 5494 // that were supplied, taking care of removing any corresponding 5495 // duplicate items in the generic resolve list. 5496 if (specifics != null) { 5497 for (int i=0; i<specifics.length; i++) { 5498 final Intent sintent = specifics[i]; 5499 if (sintent == null) { 5500 continue; 5501 } 5502 5503 if (DEBUG_INTENT_MATCHING) { 5504 Log.v(TAG, "Specific #" + i + ": " + sintent); 5505 } 5506 5507 String action = sintent.getAction(); 5508 if (resultsAction != null && resultsAction.equals(action)) { 5509 // If this action was explicitly requested, then don't 5510 // remove things that have it. 5511 action = null; 5512 } 5513 5514 ResolveInfo ri = null; 5515 ActivityInfo ai = null; 5516 5517 ComponentName comp = sintent.getComponent(); 5518 if (comp == null) { 5519 ri = resolveIntent( 5520 sintent, 5521 specificTypes != null ? specificTypes[i] : null, 5522 flags, userId); 5523 if (ri == null) { 5524 continue; 5525 } 5526 if (ri == mResolveInfo) { 5527 // ACK! Must do something better with this. 5528 } 5529 ai = ri.activityInfo; 5530 comp = new ComponentName(ai.applicationInfo.packageName, 5531 ai.name); 5532 } else { 5533 ai = getActivityInfo(comp, flags, userId); 5534 if (ai == null) { 5535 continue; 5536 } 5537 } 5538 5539 // Look for any generic query activities that are duplicates 5540 // of this specific one, and remove them from the results. 5541 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5542 N = results.size(); 5543 int j; 5544 for (j=specificsPos; j<N; j++) { 5545 ResolveInfo sri = results.get(j); 5546 if ((sri.activityInfo.name.equals(comp.getClassName()) 5547 && sri.activityInfo.applicationInfo.packageName.equals( 5548 comp.getPackageName())) 5549 || (action != null && sri.filter.matchAction(action))) { 5550 results.remove(j); 5551 if (DEBUG_INTENT_MATCHING) Log.v( 5552 TAG, "Removing duplicate item from " + j 5553 + " due to specific " + specificsPos); 5554 if (ri == null) { 5555 ri = sri; 5556 } 5557 j--; 5558 N--; 5559 } 5560 } 5561 5562 // Add this specific item to its proper place. 5563 if (ri == null) { 5564 ri = new ResolveInfo(); 5565 ri.activityInfo = ai; 5566 } 5567 results.add(specificsPos, ri); 5568 ri.specificIndex = i; 5569 specificsPos++; 5570 } 5571 } 5572 5573 // Now we go through the remaining generic results and remove any 5574 // duplicate actions that are found here. 5575 N = results.size(); 5576 for (int i=specificsPos; i<N-1; i++) { 5577 final ResolveInfo rii = results.get(i); 5578 if (rii.filter == null) { 5579 continue; 5580 } 5581 5582 // Iterate over all of the actions of this result's intent 5583 // filter... typically this should be just one. 5584 final Iterator<String> it = rii.filter.actionsIterator(); 5585 if (it == null) { 5586 continue; 5587 } 5588 while (it.hasNext()) { 5589 final String action = it.next(); 5590 if (resultsAction != null && resultsAction.equals(action)) { 5591 // If this action was explicitly requested, then don't 5592 // remove things that have it. 5593 continue; 5594 } 5595 for (int j=i+1; j<N; j++) { 5596 final ResolveInfo rij = results.get(j); 5597 if (rij.filter != null && rij.filter.hasAction(action)) { 5598 results.remove(j); 5599 if (DEBUG_INTENT_MATCHING) Log.v( 5600 TAG, "Removing duplicate item from " + j 5601 + " due to action " + action + " at " + i); 5602 j--; 5603 N--; 5604 } 5605 } 5606 } 5607 5608 // If the caller didn't request filter information, drop it now 5609 // so we don't have to marshall/unmarshall it. 5610 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5611 rii.filter = null; 5612 } 5613 } 5614 5615 // Filter out the caller activity if so requested. 5616 if (caller != null) { 5617 N = results.size(); 5618 for (int i=0; i<N; i++) { 5619 ActivityInfo ainfo = results.get(i).activityInfo; 5620 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5621 && caller.getClassName().equals(ainfo.name)) { 5622 results.remove(i); 5623 break; 5624 } 5625 } 5626 } 5627 5628 // If the caller didn't request filter information, 5629 // drop them now so we don't have to 5630 // marshall/unmarshall it. 5631 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5632 N = results.size(); 5633 for (int i=0; i<N; i++) { 5634 results.get(i).filter = null; 5635 } 5636 } 5637 5638 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5639 return results; 5640 } 5641 5642 @Override 5643 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5644 int userId) { 5645 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5646 flags = updateFlagsForResolve(flags, userId, intent); 5647 ComponentName comp = intent.getComponent(); 5648 if (comp == null) { 5649 if (intent.getSelector() != null) { 5650 intent = intent.getSelector(); 5651 comp = intent.getComponent(); 5652 } 5653 } 5654 if (comp != null) { 5655 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5656 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5657 if (ai != null) { 5658 ResolveInfo ri = new ResolveInfo(); 5659 ri.activityInfo = ai; 5660 list.add(ri); 5661 } 5662 return list; 5663 } 5664 5665 // reader 5666 synchronized (mPackages) { 5667 String pkgName = intent.getPackage(); 5668 if (pkgName == null) { 5669 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5670 } 5671 final PackageParser.Package pkg = mPackages.get(pkgName); 5672 if (pkg != null) { 5673 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5674 userId); 5675 } 5676 return null; 5677 } 5678 } 5679 5680 @Override 5681 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5682 if (!sUserManager.exists(userId)) return null; 5683 flags = updateFlagsForResolve(flags, userId, intent); 5684 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5685 if (query != null) { 5686 if (query.size() >= 1) { 5687 // If there is more than one service with the same priority, 5688 // just arbitrarily pick the first one. 5689 return query.get(0); 5690 } 5691 } 5692 return null; 5693 } 5694 5695 @Override 5696 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5697 int userId) { 5698 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5699 flags = updateFlagsForResolve(flags, userId, intent); 5700 ComponentName comp = intent.getComponent(); 5701 if (comp == null) { 5702 if (intent.getSelector() != null) { 5703 intent = intent.getSelector(); 5704 comp = intent.getComponent(); 5705 } 5706 } 5707 if (comp != null) { 5708 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5709 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5710 if (si != null) { 5711 final ResolveInfo ri = new ResolveInfo(); 5712 ri.serviceInfo = si; 5713 list.add(ri); 5714 } 5715 return list; 5716 } 5717 5718 // reader 5719 synchronized (mPackages) { 5720 String pkgName = intent.getPackage(); 5721 if (pkgName == null) { 5722 return mServices.queryIntent(intent, resolvedType, flags, userId); 5723 } 5724 final PackageParser.Package pkg = mPackages.get(pkgName); 5725 if (pkg != null) { 5726 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5727 userId); 5728 } 5729 return null; 5730 } 5731 } 5732 5733 @Override 5734 public List<ResolveInfo> queryIntentContentProviders( 5735 Intent intent, String resolvedType, int flags, int userId) { 5736 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5737 flags = updateFlagsForResolve(flags, userId, intent); 5738 ComponentName comp = intent.getComponent(); 5739 if (comp == null) { 5740 if (intent.getSelector() != null) { 5741 intent = intent.getSelector(); 5742 comp = intent.getComponent(); 5743 } 5744 } 5745 if (comp != null) { 5746 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5747 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5748 if (pi != null) { 5749 final ResolveInfo ri = new ResolveInfo(); 5750 ri.providerInfo = pi; 5751 list.add(ri); 5752 } 5753 return list; 5754 } 5755 5756 // reader 5757 synchronized (mPackages) { 5758 String pkgName = intent.getPackage(); 5759 if (pkgName == null) { 5760 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5761 } 5762 final PackageParser.Package pkg = mPackages.get(pkgName); 5763 if (pkg != null) { 5764 return mProviders.queryIntentForPackage( 5765 intent, resolvedType, flags, pkg.providers, userId); 5766 } 5767 return null; 5768 } 5769 } 5770 5771 @Override 5772 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5773 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5774 flags = updateFlagsForPackage(flags, userId, null); 5775 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5776 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5777 5778 // writer 5779 synchronized (mPackages) { 5780 ArrayList<PackageInfo> list; 5781 if (listUninstalled) { 5782 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5783 for (PackageSetting ps : mSettings.mPackages.values()) { 5784 PackageInfo pi; 5785 if (ps.pkg != null) { 5786 pi = generatePackageInfo(ps.pkg, flags, userId); 5787 } else { 5788 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5789 } 5790 if (pi != null) { 5791 list.add(pi); 5792 } 5793 } 5794 } else { 5795 list = new ArrayList<PackageInfo>(mPackages.size()); 5796 for (PackageParser.Package p : mPackages.values()) { 5797 PackageInfo pi = generatePackageInfo(p, flags, userId); 5798 if (pi != null) { 5799 list.add(pi); 5800 } 5801 } 5802 } 5803 5804 return new ParceledListSlice<PackageInfo>(list); 5805 } 5806 } 5807 5808 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5809 String[] permissions, boolean[] tmp, int flags, int userId) { 5810 int numMatch = 0; 5811 final PermissionsState permissionsState = ps.getPermissionsState(); 5812 for (int i=0; i<permissions.length; i++) { 5813 final String permission = permissions[i]; 5814 if (permissionsState.hasPermission(permission, userId)) { 5815 tmp[i] = true; 5816 numMatch++; 5817 } else { 5818 tmp[i] = false; 5819 } 5820 } 5821 if (numMatch == 0) { 5822 return; 5823 } 5824 PackageInfo pi; 5825 if (ps.pkg != null) { 5826 pi = generatePackageInfo(ps.pkg, flags, userId); 5827 } else { 5828 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5829 } 5830 // The above might return null in cases of uninstalled apps or install-state 5831 // skew across users/profiles. 5832 if (pi != null) { 5833 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5834 if (numMatch == permissions.length) { 5835 pi.requestedPermissions = permissions; 5836 } else { 5837 pi.requestedPermissions = new String[numMatch]; 5838 numMatch = 0; 5839 for (int i=0; i<permissions.length; i++) { 5840 if (tmp[i]) { 5841 pi.requestedPermissions[numMatch] = permissions[i]; 5842 numMatch++; 5843 } 5844 } 5845 } 5846 } 5847 list.add(pi); 5848 } 5849 } 5850 5851 @Override 5852 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5853 String[] permissions, int flags, int userId) { 5854 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5855 flags = updateFlagsForPackage(flags, userId, permissions); 5856 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5857 5858 // writer 5859 synchronized (mPackages) { 5860 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5861 boolean[] tmpBools = new boolean[permissions.length]; 5862 if (listUninstalled) { 5863 for (PackageSetting ps : mSettings.mPackages.values()) { 5864 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5865 } 5866 } else { 5867 for (PackageParser.Package pkg : mPackages.values()) { 5868 PackageSetting ps = (PackageSetting)pkg.mExtras; 5869 if (ps != null) { 5870 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5871 userId); 5872 } 5873 } 5874 } 5875 5876 return new ParceledListSlice<PackageInfo>(list); 5877 } 5878 } 5879 5880 @Override 5881 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5882 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5883 flags = updateFlagsForApplication(flags, userId, null); 5884 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5885 5886 // writer 5887 synchronized (mPackages) { 5888 ArrayList<ApplicationInfo> list; 5889 if (listUninstalled) { 5890 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5891 for (PackageSetting ps : mSettings.mPackages.values()) { 5892 ApplicationInfo ai; 5893 if (ps.pkg != null) { 5894 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5895 ps.readUserState(userId), userId); 5896 } else { 5897 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5898 } 5899 if (ai != null) { 5900 list.add(ai); 5901 } 5902 } 5903 } else { 5904 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5905 for (PackageParser.Package p : mPackages.values()) { 5906 if (p.mExtras != null) { 5907 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5908 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5909 if (ai != null) { 5910 list.add(ai); 5911 } 5912 } 5913 } 5914 } 5915 5916 return new ParceledListSlice<ApplicationInfo>(list); 5917 } 5918 } 5919 5920 @Override 5921 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5922 if (DISABLE_EPHEMERAL_APPS) { 5923 return null; 5924 } 5925 5926 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5927 "getEphemeralApplications"); 5928 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5929 "getEphemeralApplications"); 5930 synchronized (mPackages) { 5931 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5932 .getEphemeralApplicationsLPw(userId); 5933 if (ephemeralApps != null) { 5934 return new ParceledListSlice<>(ephemeralApps); 5935 } 5936 } 5937 return null; 5938 } 5939 5940 @Override 5941 public boolean isEphemeralApplication(String packageName, int userId) { 5942 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5943 "isEphemeral"); 5944 if (DISABLE_EPHEMERAL_APPS) { 5945 return false; 5946 } 5947 5948 if (!isCallerSameApp(packageName)) { 5949 return false; 5950 } 5951 synchronized (mPackages) { 5952 PackageParser.Package pkg = mPackages.get(packageName); 5953 if (pkg != null) { 5954 return pkg.applicationInfo.isEphemeralApp(); 5955 } 5956 } 5957 return false; 5958 } 5959 5960 @Override 5961 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 5962 if (DISABLE_EPHEMERAL_APPS) { 5963 return null; 5964 } 5965 5966 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5967 "getCookie"); 5968 if (!isCallerSameApp(packageName)) { 5969 return null; 5970 } 5971 synchronized (mPackages) { 5972 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 5973 packageName, userId); 5974 } 5975 } 5976 5977 @Override 5978 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 5979 if (DISABLE_EPHEMERAL_APPS) { 5980 return true; 5981 } 5982 5983 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5984 "setCookie"); 5985 if (!isCallerSameApp(packageName)) { 5986 return false; 5987 } 5988 synchronized (mPackages) { 5989 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 5990 packageName, cookie, userId); 5991 } 5992 } 5993 5994 @Override 5995 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 5996 if (DISABLE_EPHEMERAL_APPS) { 5997 return null; 5998 } 5999 6000 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6001 "getEphemeralApplicationIcon"); 6002 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 6003 "getEphemeralApplicationIcon"); 6004 synchronized (mPackages) { 6005 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6006 packageName, userId); 6007 } 6008 } 6009 6010 private boolean isCallerSameApp(String packageName) { 6011 PackageParser.Package pkg = mPackages.get(packageName); 6012 return pkg != null 6013 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6014 } 6015 6016 public List<ApplicationInfo> getPersistentApplications(int flags) { 6017 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6018 6019 // reader 6020 synchronized (mPackages) { 6021 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6022 final int userId = UserHandle.getCallingUserId(); 6023 while (i.hasNext()) { 6024 final PackageParser.Package p = i.next(); 6025 if (p.applicationInfo != null 6026 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 6027 && (!mSafeMode || isSystemApp(p))) { 6028 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6029 if (ps != null) { 6030 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6031 ps.readUserState(userId), userId); 6032 if (ai != null) { 6033 finalList.add(ai); 6034 } 6035 } 6036 } 6037 } 6038 } 6039 6040 return finalList; 6041 } 6042 6043 @Override 6044 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6045 if (!sUserManager.exists(userId)) return null; 6046 flags = updateFlagsForComponent(flags, userId, name); 6047 // reader 6048 synchronized (mPackages) { 6049 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6050 PackageSetting ps = provider != null 6051 ? mSettings.mPackages.get(provider.owner.packageName) 6052 : null; 6053 return ps != null 6054 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6055 ? PackageParser.generateProviderInfo(provider, flags, 6056 ps.readUserState(userId), userId) 6057 : null; 6058 } 6059 } 6060 6061 /** 6062 * @deprecated 6063 */ 6064 @Deprecated 6065 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6066 // reader 6067 synchronized (mPackages) { 6068 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6069 .entrySet().iterator(); 6070 final int userId = UserHandle.getCallingUserId(); 6071 while (i.hasNext()) { 6072 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6073 PackageParser.Provider p = entry.getValue(); 6074 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6075 6076 if (ps != null && p.syncable 6077 && (!mSafeMode || (p.info.applicationInfo.flags 6078 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6079 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6080 ps.readUserState(userId), userId); 6081 if (info != null) { 6082 outNames.add(entry.getKey()); 6083 outInfo.add(info); 6084 } 6085 } 6086 } 6087 } 6088 } 6089 6090 @Override 6091 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6092 int uid, int flags) { 6093 final int userId = processName != null ? UserHandle.getUserId(uid) 6094 : UserHandle.getCallingUserId(); 6095 if (!sUserManager.exists(userId)) return null; 6096 flags = updateFlagsForComponent(flags, userId, processName); 6097 6098 ArrayList<ProviderInfo> finalList = null; 6099 // reader 6100 synchronized (mPackages) { 6101 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6102 while (i.hasNext()) { 6103 final PackageParser.Provider p = i.next(); 6104 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6105 if (ps != null && p.info.authority != null 6106 && (processName == null 6107 || (p.info.processName.equals(processName) 6108 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6109 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6110 if (finalList == null) { 6111 finalList = new ArrayList<ProviderInfo>(3); 6112 } 6113 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6114 ps.readUserState(userId), userId); 6115 if (info != null) { 6116 finalList.add(info); 6117 } 6118 } 6119 } 6120 } 6121 6122 if (finalList != null) { 6123 Collections.sort(finalList, mProviderInitOrderSorter); 6124 return new ParceledListSlice<ProviderInfo>(finalList); 6125 } 6126 6127 return null; 6128 } 6129 6130 @Override 6131 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6132 // reader 6133 synchronized (mPackages) { 6134 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6135 return PackageParser.generateInstrumentationInfo(i, flags); 6136 } 6137 } 6138 6139 @Override 6140 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6141 int flags) { 6142 ArrayList<InstrumentationInfo> finalList = 6143 new ArrayList<InstrumentationInfo>(); 6144 6145 // reader 6146 synchronized (mPackages) { 6147 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6148 while (i.hasNext()) { 6149 final PackageParser.Instrumentation p = i.next(); 6150 if (targetPackage == null 6151 || targetPackage.equals(p.info.targetPackage)) { 6152 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6153 flags); 6154 if (ii != null) { 6155 finalList.add(ii); 6156 } 6157 } 6158 } 6159 } 6160 6161 return finalList; 6162 } 6163 6164 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6165 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6166 if (overlays == null) { 6167 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6168 return; 6169 } 6170 for (PackageParser.Package opkg : overlays.values()) { 6171 // Not much to do if idmap fails: we already logged the error 6172 // and we certainly don't want to abort installation of pkg simply 6173 // because an overlay didn't fit properly. For these reasons, 6174 // ignore the return value of createIdmapForPackagePairLI. 6175 createIdmapForPackagePairLI(pkg, opkg); 6176 } 6177 } 6178 6179 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6180 PackageParser.Package opkg) { 6181 if (!opkg.mTrustedOverlay) { 6182 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6183 opkg.baseCodePath + ": overlay not trusted"); 6184 return false; 6185 } 6186 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6187 if (overlaySet == null) { 6188 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6189 opkg.baseCodePath + " but target package has no known overlays"); 6190 return false; 6191 } 6192 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6193 // TODO: generate idmap for split APKs 6194 try { 6195 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6196 } catch (InstallerException e) { 6197 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6198 + opkg.baseCodePath); 6199 return false; 6200 } 6201 PackageParser.Package[] overlayArray = 6202 overlaySet.values().toArray(new PackageParser.Package[0]); 6203 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6204 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6205 return p1.mOverlayPriority - p2.mOverlayPriority; 6206 } 6207 }; 6208 Arrays.sort(overlayArray, cmp); 6209 6210 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6211 int i = 0; 6212 for (PackageParser.Package p : overlayArray) { 6213 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6214 } 6215 return true; 6216 } 6217 6218 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6219 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6220 try { 6221 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6222 } finally { 6223 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6224 } 6225 } 6226 6227 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6228 final File[] files = dir.listFiles(); 6229 if (ArrayUtils.isEmpty(files)) { 6230 Log.d(TAG, "No files in app dir " + dir); 6231 return; 6232 } 6233 6234 if (DEBUG_PACKAGE_SCANNING) { 6235 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6236 + " flags=0x" + Integer.toHexString(parseFlags)); 6237 } 6238 6239 for (File file : files) { 6240 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6241 && !PackageInstallerService.isStageName(file.getName()); 6242 if (!isPackage) { 6243 // Ignore entries which are not packages 6244 continue; 6245 } 6246 try { 6247 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6248 scanFlags, currentTime, null); 6249 } catch (PackageManagerException e) { 6250 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6251 6252 // Delete invalid userdata apps 6253 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6254 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6255 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6256 removeCodePathLI(file); 6257 } 6258 } 6259 } 6260 } 6261 6262 private static File getSettingsProblemFile() { 6263 File dataDir = Environment.getDataDirectory(); 6264 File systemDir = new File(dataDir, "system"); 6265 File fname = new File(systemDir, "uiderrors.txt"); 6266 return fname; 6267 } 6268 6269 static void reportSettingsProblem(int priority, String msg) { 6270 logCriticalInfo(priority, msg); 6271 } 6272 6273 static void logCriticalInfo(int priority, String msg) { 6274 Slog.println(priority, TAG, msg); 6275 EventLogTags.writePmCriticalInfo(msg); 6276 try { 6277 File fname = getSettingsProblemFile(); 6278 FileOutputStream out = new FileOutputStream(fname, true); 6279 PrintWriter pw = new FastPrintWriter(out); 6280 SimpleDateFormat formatter = new SimpleDateFormat(); 6281 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6282 pw.println(dateString + ": " + msg); 6283 pw.close(); 6284 FileUtils.setPermissions( 6285 fname.toString(), 6286 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6287 -1, -1); 6288 } catch (java.io.IOException e) { 6289 } 6290 } 6291 6292 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6293 int parseFlags) throws PackageManagerException { 6294 if (ps != null 6295 && ps.codePath.equals(srcFile) 6296 && ps.timeStamp == srcFile.lastModified() 6297 && !isCompatSignatureUpdateNeeded(pkg) 6298 && !isRecoverSignatureUpdateNeeded(pkg)) { 6299 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6300 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6301 ArraySet<PublicKey> signingKs; 6302 synchronized (mPackages) { 6303 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6304 } 6305 if (ps.signatures.mSignatures != null 6306 && ps.signatures.mSignatures.length != 0 6307 && signingKs != null) { 6308 // Optimization: reuse the existing cached certificates 6309 // if the package appears to be unchanged. 6310 pkg.mSignatures = ps.signatures.mSignatures; 6311 pkg.mSigningKeys = signingKs; 6312 return; 6313 } 6314 6315 Slog.w(TAG, "PackageSetting for " + ps.name 6316 + " is missing signatures. Collecting certs again to recover them."); 6317 } else { 6318 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6319 } 6320 6321 try { 6322 PackageParser.collectCertificates(pkg, parseFlags); 6323 } catch (PackageParserException e) { 6324 throw PackageManagerException.from(e); 6325 } 6326 } 6327 6328 /** 6329 * Traces a package scan. 6330 * @see #scanPackageLI(File, int, int, long, UserHandle) 6331 */ 6332 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6333 long currentTime, UserHandle user) throws PackageManagerException { 6334 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6335 try { 6336 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6337 } finally { 6338 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6339 } 6340 } 6341 6342 /** 6343 * Scans a package and returns the newly parsed package. 6344 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6345 */ 6346 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6347 long currentTime, UserHandle user) throws PackageManagerException { 6348 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6349 parseFlags |= mDefParseFlags; 6350 PackageParser pp = new PackageParser(); 6351 pp.setSeparateProcesses(mSeparateProcesses); 6352 pp.setOnlyCoreApps(mOnlyCore); 6353 pp.setDisplayMetrics(mMetrics); 6354 6355 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6356 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6357 } 6358 6359 final PackageParser.Package pkg; 6360 try { 6361 pkg = pp.parsePackage(scanFile, parseFlags); 6362 } catch (PackageParserException e) { 6363 throw PackageManagerException.from(e); 6364 } 6365 6366 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6367 } 6368 6369 /** 6370 * Scans a package and returns the newly parsed package. 6371 * @throws PackageManagerException on a parse error. 6372 */ 6373 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6374 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6375 throws PackageManagerException { 6376 // If the package has children and this is the first dive in the function 6377 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6378 // packages (parent and children) would be successfully scanned before the 6379 // actual scan since scanning mutates internal state and we want to atomically 6380 // install the package and its children. 6381 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6382 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6383 scanFlags |= SCAN_CHECK_ONLY; 6384 } 6385 } else { 6386 scanFlags &= ~SCAN_CHECK_ONLY; 6387 } 6388 6389 // Scan the parent 6390 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6391 scanFlags, currentTime, user); 6392 6393 // Scan the children 6394 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6395 for (int i = 0; i < childCount; i++) { 6396 PackageParser.Package childPackage = pkg.childPackages.get(i); 6397 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6398 currentTime, user); 6399 } 6400 6401 6402 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6403 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6404 } 6405 6406 return scannedPkg; 6407 } 6408 6409 /** 6410 * Scans a package and returns the newly parsed package. 6411 * @throws PackageManagerException on a parse error. 6412 */ 6413 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6414 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6415 throws PackageManagerException { 6416 PackageSetting ps = null; 6417 PackageSetting updatedPkg; 6418 // reader 6419 synchronized (mPackages) { 6420 // Look to see if we already know about this package. 6421 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6422 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6423 // This package has been renamed to its original name. Let's 6424 // use that. 6425 ps = mSettings.peekPackageLPr(oldName); 6426 } 6427 // If there was no original package, see one for the real package name. 6428 if (ps == null) { 6429 ps = mSettings.peekPackageLPr(pkg.packageName); 6430 } 6431 // Check to see if this package could be hiding/updating a system 6432 // package. Must look for it either under the original or real 6433 // package name depending on our state. 6434 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6435 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6436 6437 // If this is a package we don't know about on the system partition, we 6438 // may need to remove disabled child packages on the system partition 6439 // or may need to not add child packages if the parent apk is updated 6440 // on the data partition and no longer defines this child package. 6441 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6442 // If this is a parent package for an updated system app and this system 6443 // app got an OTA update which no longer defines some of the child packages 6444 // we have to prune them from the disabled system packages. 6445 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6446 if (disabledPs != null) { 6447 final int scannedChildCount = (pkg.childPackages != null) 6448 ? pkg.childPackages.size() : 0; 6449 final int disabledChildCount = disabledPs.childPackageNames != null 6450 ? disabledPs.childPackageNames.size() : 0; 6451 for (int i = 0; i < disabledChildCount; i++) { 6452 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6453 boolean disabledPackageAvailable = false; 6454 for (int j = 0; j < scannedChildCount; j++) { 6455 PackageParser.Package childPkg = pkg.childPackages.get(j); 6456 if (childPkg.packageName.equals(disabledChildPackageName)) { 6457 disabledPackageAvailable = true; 6458 break; 6459 } 6460 } 6461 if (!disabledPackageAvailable) { 6462 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6463 } 6464 } 6465 } 6466 } 6467 } 6468 6469 boolean updatedPkgBetter = false; 6470 // First check if this is a system package that may involve an update 6471 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6472 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6473 // it needs to drop FLAG_PRIVILEGED. 6474 if (locationIsPrivileged(scanFile)) { 6475 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6476 } else { 6477 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6478 } 6479 6480 if (ps != null && !ps.codePath.equals(scanFile)) { 6481 // The path has changed from what was last scanned... check the 6482 // version of the new path against what we have stored to determine 6483 // what to do. 6484 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6485 if (pkg.mVersionCode <= ps.versionCode) { 6486 // The system package has been updated and the code path does not match 6487 // Ignore entry. Skip it. 6488 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6489 + " ignored: updated version " + ps.versionCode 6490 + " better than this " + pkg.mVersionCode); 6491 if (!updatedPkg.codePath.equals(scanFile)) { 6492 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6493 + ps.name + " changing from " + updatedPkg.codePathString 6494 + " to " + scanFile); 6495 updatedPkg.codePath = scanFile; 6496 updatedPkg.codePathString = scanFile.toString(); 6497 updatedPkg.resourcePath = scanFile; 6498 updatedPkg.resourcePathString = scanFile.toString(); 6499 } 6500 updatedPkg.pkg = pkg; 6501 updatedPkg.versionCode = pkg.mVersionCode; 6502 6503 // Update the disabled system child packages to point to the package too. 6504 final int childCount = updatedPkg.childPackageNames != null 6505 ? updatedPkg.childPackageNames.size() : 0; 6506 for (int i = 0; i < childCount; i++) { 6507 String childPackageName = updatedPkg.childPackageNames.get(i); 6508 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6509 childPackageName); 6510 if (updatedChildPkg != null) { 6511 updatedChildPkg.pkg = pkg; 6512 updatedChildPkg.versionCode = pkg.mVersionCode; 6513 } 6514 } 6515 6516 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6517 + scanFile + " ignored: updated version " + ps.versionCode 6518 + " better than this " + pkg.mVersionCode); 6519 } else { 6520 // The current app on the system partition is better than 6521 // what we have updated to on the data partition; switch 6522 // back to the system partition version. 6523 // At this point, its safely assumed that package installation for 6524 // apps in system partition will go through. If not there won't be a working 6525 // version of the app 6526 // writer 6527 synchronized (mPackages) { 6528 // Just remove the loaded entries from package lists. 6529 mPackages.remove(ps.name); 6530 } 6531 6532 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6533 + " reverting from " + ps.codePathString 6534 + ": new version " + pkg.mVersionCode 6535 + " better than installed " + ps.versionCode); 6536 6537 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6538 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6539 synchronized (mInstallLock) { 6540 args.cleanUpResourcesLI(); 6541 } 6542 synchronized (mPackages) { 6543 mSettings.enableSystemPackageLPw(ps.name); 6544 } 6545 updatedPkgBetter = true; 6546 } 6547 } 6548 } 6549 6550 if (updatedPkg != null) { 6551 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6552 // initially 6553 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6554 6555 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6556 // flag set initially 6557 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6558 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6559 } 6560 } 6561 6562 // Verify certificates against what was last scanned 6563 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6564 6565 /* 6566 * A new system app appeared, but we already had a non-system one of the 6567 * same name installed earlier. 6568 */ 6569 boolean shouldHideSystemApp = false; 6570 if (updatedPkg == null && ps != null 6571 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6572 /* 6573 * Check to make sure the signatures match first. If they don't, 6574 * wipe the installed application and its data. 6575 */ 6576 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6577 != PackageManager.SIGNATURE_MATCH) { 6578 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6579 + " signatures don't match existing userdata copy; removing"); 6580 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false, null); 6581 ps = null; 6582 } else { 6583 /* 6584 * If the newly-added system app is an older version than the 6585 * already installed version, hide it. It will be scanned later 6586 * and re-added like an update. 6587 */ 6588 if (pkg.mVersionCode <= ps.versionCode) { 6589 shouldHideSystemApp = true; 6590 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6591 + " but new version " + pkg.mVersionCode + " better than installed " 6592 + ps.versionCode + "; hiding system"); 6593 } else { 6594 /* 6595 * The newly found system app is a newer version that the 6596 * one previously installed. Simply remove the 6597 * already-installed application and replace it with our own 6598 * while keeping the application data. 6599 */ 6600 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6601 + " reverting from " + ps.codePathString + ": new version " 6602 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6603 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6604 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6605 synchronized (mInstallLock) { 6606 args.cleanUpResourcesLI(); 6607 } 6608 } 6609 } 6610 } 6611 6612 // The apk is forward locked (not public) if its code and resources 6613 // are kept in different files. (except for app in either system or 6614 // vendor path). 6615 // TODO grab this value from PackageSettings 6616 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6617 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6618 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6619 } 6620 } 6621 6622 // TODO: extend to support forward-locked splits 6623 String resourcePath = null; 6624 String baseResourcePath = null; 6625 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6626 if (ps != null && ps.resourcePathString != null) { 6627 resourcePath = ps.resourcePathString; 6628 baseResourcePath = ps.resourcePathString; 6629 } else { 6630 // Should not happen at all. Just log an error. 6631 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6632 } 6633 } else { 6634 resourcePath = pkg.codePath; 6635 baseResourcePath = pkg.baseCodePath; 6636 } 6637 6638 // Set application objects path explicitly. 6639 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6640 pkg.setApplicationInfoCodePath(pkg.codePath); 6641 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6642 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6643 pkg.setApplicationInfoResourcePath(resourcePath); 6644 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6645 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6646 6647 // Note that we invoke the following method only if we are about to unpack an application 6648 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6649 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6650 6651 /* 6652 * If the system app should be overridden by a previously installed 6653 * data, hide the system app now and let the /data/app scan pick it up 6654 * again. 6655 */ 6656 if (shouldHideSystemApp) { 6657 synchronized (mPackages) { 6658 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6659 } 6660 } 6661 6662 return scannedPkg; 6663 } 6664 6665 private static String fixProcessName(String defProcessName, 6666 String processName, int uid) { 6667 if (processName == null) { 6668 return defProcessName; 6669 } 6670 return processName; 6671 } 6672 6673 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6674 throws PackageManagerException { 6675 if (pkgSetting.signatures.mSignatures != null) { 6676 // Already existing package. Make sure signatures match 6677 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6678 == PackageManager.SIGNATURE_MATCH; 6679 if (!match) { 6680 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6681 == PackageManager.SIGNATURE_MATCH; 6682 } 6683 if (!match) { 6684 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6685 == PackageManager.SIGNATURE_MATCH; 6686 } 6687 if (!match) { 6688 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6689 + pkg.packageName + " signatures do not match the " 6690 + "previously installed version; ignoring!"); 6691 } 6692 } 6693 6694 // Check for shared user signatures 6695 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6696 // Already existing package. Make sure signatures match 6697 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6698 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6699 if (!match) { 6700 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6701 == PackageManager.SIGNATURE_MATCH; 6702 } 6703 if (!match) { 6704 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6705 == PackageManager.SIGNATURE_MATCH; 6706 } 6707 if (!match) { 6708 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6709 "Package " + pkg.packageName 6710 + " has no signatures that match those in shared user " 6711 + pkgSetting.sharedUser.name + "; ignoring!"); 6712 } 6713 } 6714 } 6715 6716 /** 6717 * Enforces that only the system UID or root's UID can call a method exposed 6718 * via Binder. 6719 * 6720 * @param message used as message if SecurityException is thrown 6721 * @throws SecurityException if the caller is not system or root 6722 */ 6723 private static final void enforceSystemOrRoot(String message) { 6724 final int uid = Binder.getCallingUid(); 6725 if (uid != Process.SYSTEM_UID && uid != 0) { 6726 throw new SecurityException(message); 6727 } 6728 } 6729 6730 @Override 6731 public void performFstrimIfNeeded() { 6732 enforceSystemOrRoot("Only the system can request fstrim"); 6733 6734 // Before everything else, see whether we need to fstrim. 6735 try { 6736 IMountService ms = PackageHelper.getMountService(); 6737 if (ms != null) { 6738 final boolean isUpgrade = isUpgrade(); 6739 boolean doTrim = isUpgrade; 6740 if (doTrim) { 6741 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6742 } else { 6743 final long interval = android.provider.Settings.Global.getLong( 6744 mContext.getContentResolver(), 6745 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6746 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6747 if (interval > 0) { 6748 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6749 if (timeSinceLast > interval) { 6750 doTrim = true; 6751 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6752 + "; running immediately"); 6753 } 6754 } 6755 } 6756 if (doTrim) { 6757 if (!isFirstBoot()) { 6758 try { 6759 ActivityManagerNative.getDefault().showBootMessage( 6760 mContext.getResources().getString( 6761 R.string.android_upgrading_fstrim), true); 6762 } catch (RemoteException e) { 6763 } 6764 } 6765 ms.runMaintenance(); 6766 } 6767 } else { 6768 Slog.e(TAG, "Mount service unavailable!"); 6769 } 6770 } catch (RemoteException e) { 6771 // Can't happen; MountService is local 6772 } 6773 } 6774 6775 @Override 6776 public void extractPackagesIfNeeded() { 6777 enforceSystemOrRoot("Only the system can request package extraction"); 6778 6779 // Extract pacakges only if profile-guided compilation is enabled because 6780 // otherwise BackgroundDexOptService will not dexopt them later. 6781 if (mUseJitProfiles) { 6782 List<PackageParser.Package> pkgs; 6783 synchronized (mPackages) { 6784 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 6785 } 6786 for (PackageParser.Package pkg : pkgs) { 6787 if (PackageDexOptimizer.canOptimizePackage(pkg)) { 6788 performDexOpt(pkg.packageName, null /* instructionSet */, 6789 false /* useProfiles */, true /* extractOnly */, false /* force */); 6790 } 6791 } 6792 } 6793 } 6794 6795 @Override 6796 public void notifyPackageUse(String packageName) { 6797 synchronized (mPackages) { 6798 PackageParser.Package p = mPackages.get(packageName); 6799 if (p == null) { 6800 return; 6801 } 6802 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6803 } 6804 } 6805 6806 // TODO: this is not used nor needed. Delete it. 6807 @Override 6808 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6809 return performDexOptTraced(packageName, instructionSet, false /* useProfiles */, 6810 false /* extractOnly */, false /* force */); 6811 } 6812 6813 @Override 6814 public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles, 6815 boolean extractOnly, boolean force) { 6816 return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force); 6817 } 6818 6819 private boolean performDexOptTraced(String packageName, String instructionSet, 6820 boolean useProfiles, boolean extractOnly, boolean force) { 6821 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6822 try { 6823 return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly, 6824 force); 6825 } finally { 6826 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6827 } 6828 } 6829 6830 private boolean performDexOptInternal(String packageName, String instructionSet, 6831 boolean useProfiles, boolean extractOnly, boolean force) { 6832 PackageParser.Package p; 6833 final String targetInstructionSet; 6834 synchronized (mPackages) { 6835 p = mPackages.get(packageName); 6836 if (p == null) { 6837 return false; 6838 } 6839 mPackageUsage.write(false); 6840 6841 targetInstructionSet = instructionSet != null ? instructionSet : 6842 getPrimaryInstructionSet(p.applicationInfo); 6843 if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) { 6844 // Skip only if we do not use profiles since they might trigger a recompilation. 6845 return false; 6846 } 6847 } 6848 long callingId = Binder.clearCallingIdentity(); 6849 try { 6850 synchronized (mInstallLock) { 6851 final String[] instructionSets = new String[] { targetInstructionSet }; 6852 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 6853 useProfiles, extractOnly, force); 6854 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6855 } 6856 } finally { 6857 Binder.restoreCallingIdentity(callingId); 6858 } 6859 } 6860 6861 public ArraySet<String> getOptimizablePackages() { 6862 ArraySet<String> pkgs = new ArraySet<String>(); 6863 synchronized (mPackages) { 6864 for (PackageParser.Package p : mPackages.values()) { 6865 if (PackageDexOptimizer.canOptimizePackage(p)) { 6866 pkgs.add(p.packageName); 6867 } 6868 } 6869 } 6870 return pkgs; 6871 } 6872 6873 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 6874 String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) { 6875 // Select the dex optimizer based on the force parameter. 6876 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 6877 // allocate an object here. 6878 PackageDexOptimizer pdo = force 6879 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 6880 : mPackageDexOptimizer; 6881 6882 // Optimize all dependencies first. Note: we ignore the return value and march on 6883 // on errors. 6884 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 6885 if (!deps.isEmpty()) { 6886 for (PackageParser.Package depPackage : deps) { 6887 // TODO: Analyze and investigate if we (should) profile libraries. 6888 // Currently this will do a full compilation of the library. 6889 pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */, 6890 false /* extractOnly */); 6891 } 6892 } 6893 6894 return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly); 6895 } 6896 6897 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 6898 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 6899 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 6900 Set<String> collectedNames = new HashSet<>(); 6901 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 6902 6903 retValue.remove(p); 6904 6905 return retValue; 6906 } else { 6907 return Collections.emptyList(); 6908 } 6909 } 6910 6911 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 6912 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 6913 if (!collectedNames.contains(p.packageName)) { 6914 collectedNames.add(p.packageName); 6915 collected.add(p); 6916 6917 if (p.usesLibraries != null) { 6918 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 6919 } 6920 if (p.usesOptionalLibraries != null) { 6921 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 6922 collectedNames); 6923 } 6924 } 6925 } 6926 6927 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 6928 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 6929 for (String libName : libs) { 6930 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 6931 if (libPkg != null) { 6932 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 6933 } 6934 } 6935 } 6936 6937 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 6938 synchronized (mPackages) { 6939 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 6940 if (lib != null && lib.apk != null) { 6941 return mPackages.get(lib.apk); 6942 } 6943 } 6944 return null; 6945 } 6946 6947 public void shutdown() { 6948 mPackageUsage.write(true); 6949 } 6950 6951 @Override 6952 public void forceDexOpt(String packageName) { 6953 enforceSystemOrRoot("forceDexOpt"); 6954 6955 PackageParser.Package pkg; 6956 synchronized (mPackages) { 6957 pkg = mPackages.get(packageName); 6958 if (pkg == null) { 6959 throw new IllegalArgumentException("Unknown package: " + packageName); 6960 } 6961 } 6962 6963 synchronized (mInstallLock) { 6964 final String[] instructionSets = new String[] { 6965 getPrimaryInstructionSet(pkg.applicationInfo) }; 6966 6967 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6968 6969 // Whoever is calling forceDexOpt wants a fully compiled package. 6970 // Don't use profiles since that may cause compilation to be skipped. 6971 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 6972 false /* useProfiles */, false /* extractOnly */, true /* force */); 6973 6974 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6975 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6976 throw new IllegalStateException("Failed to dexopt: " + res); 6977 } 6978 } 6979 } 6980 6981 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6982 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6983 Slog.w(TAG, "Unable to update from " + oldPkg.name 6984 + " to " + newPkg.packageName 6985 + ": old package not in system partition"); 6986 return false; 6987 } else if (mPackages.get(oldPkg.name) != null) { 6988 Slog.w(TAG, "Unable to update from " + oldPkg.name 6989 + " to " + newPkg.packageName 6990 + ": old package still exists"); 6991 return false; 6992 } 6993 return true; 6994 } 6995 6996 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 6997 // TODO: triage flags as part of 26466827 6998 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 6999 7000 boolean res = true; 7001 final int[] users = sUserManager.getUserIds(); 7002 for (int user : users) { 7003 try { 7004 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7005 } catch (InstallerException e) { 7006 Slog.w(TAG, "Failed to delete data directory", e); 7007 res = false; 7008 } 7009 } 7010 return res; 7011 } 7012 7013 void removeCodePathLI(File codePath) { 7014 if (codePath.isDirectory()) { 7015 try { 7016 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7017 } catch (InstallerException e) { 7018 Slog.w(TAG, "Failed to remove code path", e); 7019 } 7020 } else { 7021 codePath.delete(); 7022 } 7023 } 7024 7025 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7026 try { 7027 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7028 } catch (InstallerException e) { 7029 Slog.w(TAG, "Failed to destroy app data", e); 7030 } 7031 } 7032 7033 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7034 int appId, String seinfo) { 7035 try { 7036 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7037 } catch (InstallerException e) { 7038 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7039 } 7040 } 7041 7042 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7043 final PackageParser.Package pkg; 7044 synchronized (mPackages) { 7045 pkg = mPackages.get(packageName); 7046 } 7047 if (pkg == null) { 7048 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7049 return; 7050 } 7051 deleteCodeCacheDirsLI(pkg); 7052 } 7053 7054 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7055 // TODO: triage flags as part of 26466827 7056 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7057 7058 int[] users = sUserManager.getUserIds(); 7059 int res = 0; 7060 for (int user : users) { 7061 // Remove the parent code cache 7062 try { 7063 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7064 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7065 } catch (InstallerException e) { 7066 Slog.w(TAG, "Failed to delete code cache directory", e); 7067 } 7068 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7069 for (int i = 0; i < childCount; i++) { 7070 PackageParser.Package childPkg = pkg.childPackages.get(i); 7071 // Remove the child code cache 7072 try { 7073 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7074 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7075 } catch (InstallerException e) { 7076 Slog.w(TAG, "Failed to delete code cache directory", e); 7077 } 7078 } 7079 } 7080 } 7081 7082 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7083 long lastUpdateTime) { 7084 // Set parent install/update time 7085 PackageSetting ps = (PackageSetting) pkg.mExtras; 7086 if (ps != null) { 7087 ps.firstInstallTime = firstInstallTime; 7088 ps.lastUpdateTime = lastUpdateTime; 7089 } 7090 // Set children install/update time 7091 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7092 for (int i = 0; i < childCount; i++) { 7093 PackageParser.Package childPkg = pkg.childPackages.get(i); 7094 ps = (PackageSetting) childPkg.mExtras; 7095 if (ps != null) { 7096 ps.firstInstallTime = firstInstallTime; 7097 ps.lastUpdateTime = lastUpdateTime; 7098 } 7099 } 7100 } 7101 7102 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7103 PackageParser.Package changingLib) { 7104 if (file.path != null) { 7105 usesLibraryFiles.add(file.path); 7106 return; 7107 } 7108 PackageParser.Package p = mPackages.get(file.apk); 7109 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7110 // If we are doing this while in the middle of updating a library apk, 7111 // then we need to make sure to use that new apk for determining the 7112 // dependencies here. (We haven't yet finished committing the new apk 7113 // to the package manager state.) 7114 if (p == null || p.packageName.equals(changingLib.packageName)) { 7115 p = changingLib; 7116 } 7117 } 7118 if (p != null) { 7119 usesLibraryFiles.addAll(p.getAllCodePaths()); 7120 } 7121 } 7122 7123 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7124 PackageParser.Package changingLib) throws PackageManagerException { 7125 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7126 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7127 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7128 for (int i=0; i<N; i++) { 7129 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7130 if (file == null) { 7131 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7132 "Package " + pkg.packageName + " requires unavailable shared library " 7133 + pkg.usesLibraries.get(i) + "; failing!"); 7134 } 7135 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7136 } 7137 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7138 for (int i=0; i<N; i++) { 7139 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7140 if (file == null) { 7141 Slog.w(TAG, "Package " + pkg.packageName 7142 + " desires unavailable shared library " 7143 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7144 } else { 7145 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7146 } 7147 } 7148 N = usesLibraryFiles.size(); 7149 if (N > 0) { 7150 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7151 } else { 7152 pkg.usesLibraryFiles = null; 7153 } 7154 } 7155 } 7156 7157 private static boolean hasString(List<String> list, List<String> which) { 7158 if (list == null) { 7159 return false; 7160 } 7161 for (int i=list.size()-1; i>=0; i--) { 7162 for (int j=which.size()-1; j>=0; j--) { 7163 if (which.get(j).equals(list.get(i))) { 7164 return true; 7165 } 7166 } 7167 } 7168 return false; 7169 } 7170 7171 private void updateAllSharedLibrariesLPw() { 7172 for (PackageParser.Package pkg : mPackages.values()) { 7173 try { 7174 updateSharedLibrariesLPw(pkg, null); 7175 } catch (PackageManagerException e) { 7176 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7177 } 7178 } 7179 } 7180 7181 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7182 PackageParser.Package changingPkg) { 7183 ArrayList<PackageParser.Package> res = null; 7184 for (PackageParser.Package pkg : mPackages.values()) { 7185 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7186 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7187 if (res == null) { 7188 res = new ArrayList<PackageParser.Package>(); 7189 } 7190 res.add(pkg); 7191 try { 7192 updateSharedLibrariesLPw(pkg, changingPkg); 7193 } catch (PackageManagerException e) { 7194 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7195 } 7196 } 7197 } 7198 return res; 7199 } 7200 7201 /** 7202 * Derive the value of the {@code cpuAbiOverride} based on the provided 7203 * value and an optional stored value from the package settings. 7204 */ 7205 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7206 String cpuAbiOverride = null; 7207 7208 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7209 cpuAbiOverride = null; 7210 } else if (abiOverride != null) { 7211 cpuAbiOverride = abiOverride; 7212 } else if (settings != null) { 7213 cpuAbiOverride = settings.cpuAbiOverrideString; 7214 } 7215 7216 return cpuAbiOverride; 7217 } 7218 7219 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7220 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7221 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7222 // If the package has children and this is the first dive in the function 7223 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7224 // whether all packages (parent and children) would be successfully scanned 7225 // before the actual scan since scanning mutates internal state and we want 7226 // to atomically install the package and its children. 7227 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7228 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7229 scanFlags |= SCAN_CHECK_ONLY; 7230 } 7231 } else { 7232 scanFlags &= ~SCAN_CHECK_ONLY; 7233 } 7234 7235 final PackageParser.Package scannedPkg; 7236 try { 7237 // Scan the parent 7238 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7239 // Scan the children 7240 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7241 for (int i = 0; i < childCount; i++) { 7242 PackageParser.Package childPkg = pkg.childPackages.get(i); 7243 scanPackageLI(childPkg, parseFlags, 7244 scanFlags, currentTime, user); 7245 } 7246 } finally { 7247 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7248 } 7249 7250 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7251 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7252 } 7253 7254 return scannedPkg; 7255 } 7256 7257 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7258 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7259 boolean success = false; 7260 try { 7261 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7262 currentTime, user); 7263 success = true; 7264 return res; 7265 } finally { 7266 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7267 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7268 } 7269 } 7270 } 7271 7272 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7273 int scanFlags, long currentTime, UserHandle user) 7274 throws PackageManagerException { 7275 final File scanFile = new File(pkg.codePath); 7276 if (pkg.applicationInfo.getCodePath() == null || 7277 pkg.applicationInfo.getResourcePath() == null) { 7278 // Bail out. The resource and code paths haven't been set. 7279 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7280 "Code and resource paths haven't been set correctly"); 7281 } 7282 7283 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7284 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7285 } else { 7286 // Only allow system apps to be flagged as core apps. 7287 pkg.coreApp = false; 7288 } 7289 7290 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7291 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7292 } 7293 7294 if (mCustomResolverComponentName != null && 7295 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7296 setUpCustomResolverActivity(pkg); 7297 } 7298 7299 if (pkg.packageName.equals("android")) { 7300 synchronized (mPackages) { 7301 if (mAndroidApplication != null) { 7302 Slog.w(TAG, "*************************************************"); 7303 Slog.w(TAG, "Core android package being redefined. Skipping."); 7304 Slog.w(TAG, " file=" + scanFile); 7305 Slog.w(TAG, "*************************************************"); 7306 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7307 "Core android package being redefined. Skipping."); 7308 } 7309 7310 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7311 // Set up information for our fall-back user intent resolution activity. 7312 mPlatformPackage = pkg; 7313 pkg.mVersionCode = mSdkVersion; 7314 mAndroidApplication = pkg.applicationInfo; 7315 7316 if (!mResolverReplaced) { 7317 mResolveActivity.applicationInfo = mAndroidApplication; 7318 mResolveActivity.name = ResolverActivity.class.getName(); 7319 mResolveActivity.packageName = mAndroidApplication.packageName; 7320 mResolveActivity.processName = "system:ui"; 7321 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7322 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7323 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7324 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7325 mResolveActivity.exported = true; 7326 mResolveActivity.enabled = true; 7327 mResolveInfo.activityInfo = mResolveActivity; 7328 mResolveInfo.priority = 0; 7329 mResolveInfo.preferredOrder = 0; 7330 mResolveInfo.match = 0; 7331 mResolveComponentName = new ComponentName( 7332 mAndroidApplication.packageName, mResolveActivity.name); 7333 } 7334 } 7335 } 7336 } 7337 7338 if (DEBUG_PACKAGE_SCANNING) { 7339 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7340 Log.d(TAG, "Scanning package " + pkg.packageName); 7341 } 7342 7343 synchronized (mPackages) { 7344 if (mPackages.containsKey(pkg.packageName) 7345 || mSharedLibraries.containsKey(pkg.packageName)) { 7346 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7347 "Application package " + pkg.packageName 7348 + " already installed. Skipping duplicate."); 7349 } 7350 7351 // If we're only installing presumed-existing packages, require that the 7352 // scanned APK is both already known and at the path previously established 7353 // for it. Previously unknown packages we pick up normally, but if we have an 7354 // a priori expectation about this package's install presence, enforce it. 7355 // With a singular exception for new system packages. When an OTA contains 7356 // a new system package, we allow the codepath to change from a system location 7357 // to the user-installed location. If we don't allow this change, any newer, 7358 // user-installed version of the application will be ignored. 7359 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7360 if (mExpectingBetter.containsKey(pkg.packageName)) { 7361 logCriticalInfo(Log.WARN, 7362 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7363 } else { 7364 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7365 if (known != null) { 7366 if (DEBUG_PACKAGE_SCANNING) { 7367 Log.d(TAG, "Examining " + pkg.codePath 7368 + " and requiring known paths " + known.codePathString 7369 + " & " + known.resourcePathString); 7370 } 7371 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7372 || !pkg.applicationInfo.getResourcePath().equals( 7373 known.resourcePathString)) { 7374 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7375 "Application package " + pkg.packageName 7376 + " found at " + pkg.applicationInfo.getCodePath() 7377 + " but expected at " + known.codePathString 7378 + "; ignoring."); 7379 } 7380 } 7381 } 7382 } 7383 } 7384 7385 // Initialize package source and resource directories 7386 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7387 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7388 7389 SharedUserSetting suid = null; 7390 PackageSetting pkgSetting = null; 7391 7392 if (!isSystemApp(pkg)) { 7393 // Only system apps can use these features. 7394 pkg.mOriginalPackages = null; 7395 pkg.mRealPackage = null; 7396 pkg.mAdoptPermissions = null; 7397 } 7398 7399 // Getting the package setting may have a side-effect, so if we 7400 // are only checking if scan would succeed, stash a copy of the 7401 // old setting to restore at the end. 7402 PackageSetting nonMutatedPs = null; 7403 7404 // writer 7405 synchronized (mPackages) { 7406 if (pkg.mSharedUserId != null) { 7407 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7408 if (suid == null) { 7409 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7410 "Creating application package " + pkg.packageName 7411 + " for shared user failed"); 7412 } 7413 if (DEBUG_PACKAGE_SCANNING) { 7414 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7415 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7416 + "): packages=" + suid.packages); 7417 } 7418 } 7419 7420 // Check if we are renaming from an original package name. 7421 PackageSetting origPackage = null; 7422 String realName = null; 7423 if (pkg.mOriginalPackages != null) { 7424 // This package may need to be renamed to a previously 7425 // installed name. Let's check on that... 7426 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7427 if (pkg.mOriginalPackages.contains(renamed)) { 7428 // This package had originally been installed as the 7429 // original name, and we have already taken care of 7430 // transitioning to the new one. Just update the new 7431 // one to continue using the old name. 7432 realName = pkg.mRealPackage; 7433 if (!pkg.packageName.equals(renamed)) { 7434 // Callers into this function may have already taken 7435 // care of renaming the package; only do it here if 7436 // it is not already done. 7437 pkg.setPackageName(renamed); 7438 } 7439 7440 } else { 7441 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7442 if ((origPackage = mSettings.peekPackageLPr( 7443 pkg.mOriginalPackages.get(i))) != null) { 7444 // We do have the package already installed under its 7445 // original name... should we use it? 7446 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7447 // New package is not compatible with original. 7448 origPackage = null; 7449 continue; 7450 } else if (origPackage.sharedUser != null) { 7451 // Make sure uid is compatible between packages. 7452 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7453 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7454 + " to " + pkg.packageName + ": old uid " 7455 + origPackage.sharedUser.name 7456 + " differs from " + pkg.mSharedUserId); 7457 origPackage = null; 7458 continue; 7459 } 7460 } else { 7461 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7462 + pkg.packageName + " to old name " + origPackage.name); 7463 } 7464 break; 7465 } 7466 } 7467 } 7468 } 7469 7470 if (mTransferedPackages.contains(pkg.packageName)) { 7471 Slog.w(TAG, "Package " + pkg.packageName 7472 + " was transferred to another, but its .apk remains"); 7473 } 7474 7475 // See comments in nonMutatedPs declaration 7476 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7477 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7478 if (foundPs != null) { 7479 nonMutatedPs = new PackageSetting(foundPs); 7480 } 7481 } 7482 7483 // Just create the setting, don't add it yet. For already existing packages 7484 // the PkgSetting exists already and doesn't have to be created. 7485 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7486 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7487 pkg.applicationInfo.primaryCpuAbi, 7488 pkg.applicationInfo.secondaryCpuAbi, 7489 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7490 user, false); 7491 if (pkgSetting == null) { 7492 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7493 "Creating application package " + pkg.packageName + " failed"); 7494 } 7495 7496 if (pkgSetting.origPackage != null) { 7497 // If we are first transitioning from an original package, 7498 // fix up the new package's name now. We need to do this after 7499 // looking up the package under its new name, so getPackageLP 7500 // can take care of fiddling things correctly. 7501 pkg.setPackageName(origPackage.name); 7502 7503 // File a report about this. 7504 String msg = "New package " + pkgSetting.realName 7505 + " renamed to replace old package " + pkgSetting.name; 7506 reportSettingsProblem(Log.WARN, msg); 7507 7508 // Make a note of it. 7509 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7510 mTransferedPackages.add(origPackage.name); 7511 } 7512 7513 // No longer need to retain this. 7514 pkgSetting.origPackage = null; 7515 } 7516 7517 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7518 // Make a note of it. 7519 mTransferedPackages.add(pkg.packageName); 7520 } 7521 7522 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7523 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7524 } 7525 7526 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7527 // Check all shared libraries and map to their actual file path. 7528 // We only do this here for apps not on a system dir, because those 7529 // are the only ones that can fail an install due to this. We 7530 // will take care of the system apps by updating all of their 7531 // library paths after the scan is done. 7532 updateSharedLibrariesLPw(pkg, null); 7533 } 7534 7535 if (mFoundPolicyFile) { 7536 SELinuxMMAC.assignSeinfoValue(pkg); 7537 } 7538 7539 pkg.applicationInfo.uid = pkgSetting.appId; 7540 pkg.mExtras = pkgSetting; 7541 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7542 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7543 // We just determined the app is signed correctly, so bring 7544 // over the latest parsed certs. 7545 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7546 } else { 7547 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7548 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7549 "Package " + pkg.packageName + " upgrade keys do not match the " 7550 + "previously installed version"); 7551 } else { 7552 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7553 String msg = "System package " + pkg.packageName 7554 + " signature changed; retaining data."; 7555 reportSettingsProblem(Log.WARN, msg); 7556 } 7557 } 7558 } else { 7559 try { 7560 verifySignaturesLP(pkgSetting, pkg); 7561 // We just determined the app is signed correctly, so bring 7562 // over the latest parsed certs. 7563 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7564 } catch (PackageManagerException e) { 7565 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7566 throw e; 7567 } 7568 // The signature has changed, but this package is in the system 7569 // image... let's recover! 7570 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7571 // However... if this package is part of a shared user, but it 7572 // doesn't match the signature of the shared user, let's fail. 7573 // What this means is that you can't change the signatures 7574 // associated with an overall shared user, which doesn't seem all 7575 // that unreasonable. 7576 if (pkgSetting.sharedUser != null) { 7577 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7578 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7579 throw new PackageManagerException( 7580 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7581 "Signature mismatch for shared user: " 7582 + pkgSetting.sharedUser); 7583 } 7584 } 7585 // File a report about this. 7586 String msg = "System package " + pkg.packageName 7587 + " signature changed; retaining data."; 7588 reportSettingsProblem(Log.WARN, msg); 7589 } 7590 } 7591 // Verify that this new package doesn't have any content providers 7592 // that conflict with existing packages. Only do this if the 7593 // package isn't already installed, since we don't want to break 7594 // things that are installed. 7595 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7596 final int N = pkg.providers.size(); 7597 int i; 7598 for (i=0; i<N; i++) { 7599 PackageParser.Provider p = pkg.providers.get(i); 7600 if (p.info.authority != null) { 7601 String names[] = p.info.authority.split(";"); 7602 for (int j = 0; j < names.length; j++) { 7603 if (mProvidersByAuthority.containsKey(names[j])) { 7604 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7605 final String otherPackageName = 7606 ((other != null && other.getComponentName() != null) ? 7607 other.getComponentName().getPackageName() : "?"); 7608 throw new PackageManagerException( 7609 INSTALL_FAILED_CONFLICTING_PROVIDER, 7610 "Can't install because provider name " + names[j] 7611 + " (in package " + pkg.applicationInfo.packageName 7612 + ") is already used by " + otherPackageName); 7613 } 7614 } 7615 } 7616 } 7617 } 7618 7619 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7620 // This package wants to adopt ownership of permissions from 7621 // another package. 7622 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7623 final String origName = pkg.mAdoptPermissions.get(i); 7624 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7625 if (orig != null) { 7626 if (verifyPackageUpdateLPr(orig, pkg)) { 7627 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7628 + pkg.packageName); 7629 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7630 } 7631 } 7632 } 7633 } 7634 } 7635 7636 final String pkgName = pkg.packageName; 7637 7638 final long scanFileTime = scanFile.lastModified(); 7639 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7640 pkg.applicationInfo.processName = fixProcessName( 7641 pkg.applicationInfo.packageName, 7642 pkg.applicationInfo.processName, 7643 pkg.applicationInfo.uid); 7644 7645 if (pkg != mPlatformPackage) { 7646 // Get all of our default paths setup 7647 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7648 } 7649 7650 final String path = scanFile.getPath(); 7651 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7652 7653 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7654 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7655 7656 // Some system apps still use directory structure for native libraries 7657 // in which case we might end up not detecting abi solely based on apk 7658 // structure. Try to detect abi based on directory structure. 7659 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7660 pkg.applicationInfo.primaryCpuAbi == null) { 7661 setBundledAppAbisAndRoots(pkg, pkgSetting); 7662 setNativeLibraryPaths(pkg); 7663 } 7664 7665 } else { 7666 if ((scanFlags & SCAN_MOVE) != 0) { 7667 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7668 // but we already have this packages package info in the PackageSetting. We just 7669 // use that and derive the native library path based on the new codepath. 7670 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7671 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7672 } 7673 7674 // Set native library paths again. For moves, the path will be updated based on the 7675 // ABIs we've determined above. For non-moves, the path will be updated based on the 7676 // ABIs we determined during compilation, but the path will depend on the final 7677 // package path (after the rename away from the stage path). 7678 setNativeLibraryPaths(pkg); 7679 } 7680 7681 // This is a special case for the "system" package, where the ABI is 7682 // dictated by the zygote configuration (and init.rc). We should keep track 7683 // of this ABI so that we can deal with "normal" applications that run under 7684 // the same UID correctly. 7685 if (mPlatformPackage == pkg) { 7686 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7687 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7688 } 7689 7690 // If there's a mismatch between the abi-override in the package setting 7691 // and the abiOverride specified for the install. Warn about this because we 7692 // would've already compiled the app without taking the package setting into 7693 // account. 7694 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7695 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7696 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7697 " for package " + pkg.packageName); 7698 } 7699 } 7700 7701 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7702 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7703 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7704 7705 // Copy the derived override back to the parsed package, so that we can 7706 // update the package settings accordingly. 7707 pkg.cpuAbiOverride = cpuAbiOverride; 7708 7709 if (DEBUG_ABI_SELECTION) { 7710 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7711 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7712 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7713 } 7714 7715 // Push the derived path down into PackageSettings so we know what to 7716 // clean up at uninstall time. 7717 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7718 7719 if (DEBUG_ABI_SELECTION) { 7720 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7721 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7722 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7723 } 7724 7725 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7726 // We don't do this here during boot because we can do it all 7727 // at once after scanning all existing packages. 7728 // 7729 // We also do this *before* we perform dexopt on this package, so that 7730 // we can avoid redundant dexopts, and also to make sure we've got the 7731 // code and package path correct. 7732 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7733 pkg, true /* boot complete */); 7734 } 7735 7736 if (mFactoryTest && pkg.requestedPermissions.contains( 7737 android.Manifest.permission.FACTORY_TEST)) { 7738 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7739 } 7740 7741 ArrayList<PackageParser.Package> clientLibPkgs = null; 7742 7743 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7744 if (nonMutatedPs != null) { 7745 synchronized (mPackages) { 7746 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 7747 } 7748 } 7749 return pkg; 7750 } 7751 7752 // Only privileged apps and updated privileged apps can add child packages. 7753 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 7754 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 7755 throw new PackageManagerException("Only privileged apps and updated " 7756 + "privileged apps can add child packages. Ignoring package " 7757 + pkg.packageName); 7758 } 7759 final int childCount = pkg.childPackages.size(); 7760 for (int i = 0; i < childCount; i++) { 7761 PackageParser.Package childPkg = pkg.childPackages.get(i); 7762 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 7763 childPkg.packageName)) { 7764 throw new PackageManagerException("Cannot override a child package of " 7765 + "another disabled system app. Ignoring package " + pkg.packageName); 7766 } 7767 } 7768 } 7769 7770 // writer 7771 synchronized (mPackages) { 7772 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7773 // Only system apps can add new shared libraries. 7774 if (pkg.libraryNames != null) { 7775 for (int i=0; i<pkg.libraryNames.size(); i++) { 7776 String name = pkg.libraryNames.get(i); 7777 boolean allowed = false; 7778 if (pkg.isUpdatedSystemApp()) { 7779 // New library entries can only be added through the 7780 // system image. This is important to get rid of a lot 7781 // of nasty edge cases: for example if we allowed a non- 7782 // system update of the app to add a library, then uninstalling 7783 // the update would make the library go away, and assumptions 7784 // we made such as through app install filtering would now 7785 // have allowed apps on the device which aren't compatible 7786 // with it. Better to just have the restriction here, be 7787 // conservative, and create many fewer cases that can negatively 7788 // impact the user experience. 7789 final PackageSetting sysPs = mSettings 7790 .getDisabledSystemPkgLPr(pkg.packageName); 7791 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7792 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7793 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7794 allowed = true; 7795 break; 7796 } 7797 } 7798 } 7799 } else { 7800 allowed = true; 7801 } 7802 if (allowed) { 7803 if (!mSharedLibraries.containsKey(name)) { 7804 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7805 } else if (!name.equals(pkg.packageName)) { 7806 Slog.w(TAG, "Package " + pkg.packageName + " library " 7807 + name + " already exists; skipping"); 7808 } 7809 } else { 7810 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7811 + name + " that is not declared on system image; skipping"); 7812 } 7813 } 7814 if ((scanFlags & SCAN_BOOTING) == 0) { 7815 // If we are not booting, we need to update any applications 7816 // that are clients of our shared library. If we are booting, 7817 // this will all be done once the scan is complete. 7818 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7819 } 7820 } 7821 } 7822 } 7823 7824 // Request the ActivityManager to kill the process(only for existing packages) 7825 // so that we do not end up in a confused state while the user is still using the older 7826 // version of the application while the new one gets installed. 7827 if ((scanFlags & SCAN_REPLACING) != 0) { 7828 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7829 7830 killApplication(pkg.applicationInfo.packageName, 7831 pkg.applicationInfo.uid, "replace pkg"); 7832 7833 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7834 } 7835 7836 // Also need to kill any apps that are dependent on the library. 7837 if (clientLibPkgs != null) { 7838 for (int i=0; i<clientLibPkgs.size(); i++) { 7839 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7840 killApplication(clientPkg.applicationInfo.packageName, 7841 clientPkg.applicationInfo.uid, "update lib"); 7842 } 7843 } 7844 7845 // Make sure we're not adding any bogus keyset info 7846 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7847 ksms.assertScannedPackageValid(pkg); 7848 7849 // writer 7850 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7851 7852 boolean createIdmapFailed = false; 7853 synchronized (mPackages) { 7854 // We don't expect installation to fail beyond this point 7855 7856 // Add the new setting to mSettings 7857 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7858 // Add the new setting to mPackages 7859 mPackages.put(pkg.applicationInfo.packageName, pkg); 7860 // Make sure we don't accidentally delete its data. 7861 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7862 while (iter.hasNext()) { 7863 PackageCleanItem item = iter.next(); 7864 if (pkgName.equals(item.packageName)) { 7865 iter.remove(); 7866 } 7867 } 7868 7869 // Take care of first install / last update times. 7870 if (currentTime != 0) { 7871 if (pkgSetting.firstInstallTime == 0) { 7872 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7873 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7874 pkgSetting.lastUpdateTime = currentTime; 7875 } 7876 } else if (pkgSetting.firstInstallTime == 0) { 7877 // We need *something*. Take time time stamp of the file. 7878 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7879 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7880 if (scanFileTime != pkgSetting.timeStamp) { 7881 // A package on the system image has changed; consider this 7882 // to be an update. 7883 pkgSetting.lastUpdateTime = scanFileTime; 7884 } 7885 } 7886 7887 // Add the package's KeySets to the global KeySetManagerService 7888 ksms.addScannedPackageLPw(pkg); 7889 7890 int N = pkg.providers.size(); 7891 StringBuilder r = null; 7892 int i; 7893 for (i=0; i<N; i++) { 7894 PackageParser.Provider p = pkg.providers.get(i); 7895 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7896 p.info.processName, pkg.applicationInfo.uid); 7897 mProviders.addProvider(p); 7898 p.syncable = p.info.isSyncable; 7899 if (p.info.authority != null) { 7900 String names[] = p.info.authority.split(";"); 7901 p.info.authority = null; 7902 for (int j = 0; j < names.length; j++) { 7903 if (j == 1 && p.syncable) { 7904 // We only want the first authority for a provider to possibly be 7905 // syncable, so if we already added this provider using a different 7906 // authority clear the syncable flag. We copy the provider before 7907 // changing it because the mProviders object contains a reference 7908 // to a provider that we don't want to change. 7909 // Only do this for the second authority since the resulting provider 7910 // object can be the same for all future authorities for this provider. 7911 p = new PackageParser.Provider(p); 7912 p.syncable = false; 7913 } 7914 if (!mProvidersByAuthority.containsKey(names[j])) { 7915 mProvidersByAuthority.put(names[j], p); 7916 if (p.info.authority == null) { 7917 p.info.authority = names[j]; 7918 } else { 7919 p.info.authority = p.info.authority + ";" + names[j]; 7920 } 7921 if (DEBUG_PACKAGE_SCANNING) { 7922 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7923 Log.d(TAG, "Registered content provider: " + names[j] 7924 + ", className = " + p.info.name + ", isSyncable = " 7925 + p.info.isSyncable); 7926 } 7927 } else { 7928 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7929 Slog.w(TAG, "Skipping provider name " + names[j] + 7930 " (in package " + pkg.applicationInfo.packageName + 7931 "): name already used by " 7932 + ((other != null && other.getComponentName() != null) 7933 ? other.getComponentName().getPackageName() : "?")); 7934 } 7935 } 7936 } 7937 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7938 if (r == null) { 7939 r = new StringBuilder(256); 7940 } else { 7941 r.append(' '); 7942 } 7943 r.append(p.info.name); 7944 } 7945 } 7946 if (r != null) { 7947 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7948 } 7949 7950 N = pkg.services.size(); 7951 r = null; 7952 for (i=0; i<N; i++) { 7953 PackageParser.Service s = pkg.services.get(i); 7954 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7955 s.info.processName, pkg.applicationInfo.uid); 7956 mServices.addService(s); 7957 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7958 if (r == null) { 7959 r = new StringBuilder(256); 7960 } else { 7961 r.append(' '); 7962 } 7963 r.append(s.info.name); 7964 } 7965 } 7966 if (r != null) { 7967 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7968 } 7969 7970 N = pkg.receivers.size(); 7971 r = null; 7972 for (i=0; i<N; i++) { 7973 PackageParser.Activity a = pkg.receivers.get(i); 7974 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7975 a.info.processName, pkg.applicationInfo.uid); 7976 mReceivers.addActivity(a, "receiver"); 7977 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7978 if (r == null) { 7979 r = new StringBuilder(256); 7980 } else { 7981 r.append(' '); 7982 } 7983 r.append(a.info.name); 7984 } 7985 } 7986 if (r != null) { 7987 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7988 } 7989 7990 N = pkg.activities.size(); 7991 r = null; 7992 for (i=0; i<N; i++) { 7993 PackageParser.Activity a = pkg.activities.get(i); 7994 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7995 a.info.processName, pkg.applicationInfo.uid); 7996 mActivities.addActivity(a, "activity"); 7997 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7998 if (r == null) { 7999 r = new StringBuilder(256); 8000 } else { 8001 r.append(' '); 8002 } 8003 r.append(a.info.name); 8004 } 8005 } 8006 if (r != null) { 8007 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8008 } 8009 8010 N = pkg.permissionGroups.size(); 8011 r = null; 8012 for (i=0; i<N; i++) { 8013 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8014 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8015 if (cur == null) { 8016 mPermissionGroups.put(pg.info.name, pg); 8017 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8018 if (r == null) { 8019 r = new StringBuilder(256); 8020 } else { 8021 r.append(' '); 8022 } 8023 r.append(pg.info.name); 8024 } 8025 } else { 8026 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8027 + pg.info.packageName + " ignored: original from " 8028 + cur.info.packageName); 8029 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8030 if (r == null) { 8031 r = new StringBuilder(256); 8032 } else { 8033 r.append(' '); 8034 } 8035 r.append("DUP:"); 8036 r.append(pg.info.name); 8037 } 8038 } 8039 } 8040 if (r != null) { 8041 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8042 } 8043 8044 N = pkg.permissions.size(); 8045 r = null; 8046 for (i=0; i<N; i++) { 8047 PackageParser.Permission p = pkg.permissions.get(i); 8048 8049 // Assume by default that we did not install this permission into the system. 8050 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8051 8052 // Now that permission groups have a special meaning, we ignore permission 8053 // groups for legacy apps to prevent unexpected behavior. In particular, 8054 // permissions for one app being granted to someone just becase they happen 8055 // to be in a group defined by another app (before this had no implications). 8056 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8057 p.group = mPermissionGroups.get(p.info.group); 8058 // Warn for a permission in an unknown group. 8059 if (p.info.group != null && p.group == null) { 8060 Slog.w(TAG, "Permission " + p.info.name + " from package " 8061 + p.info.packageName + " in an unknown group " + p.info.group); 8062 } 8063 } 8064 8065 ArrayMap<String, BasePermission> permissionMap = 8066 p.tree ? mSettings.mPermissionTrees 8067 : mSettings.mPermissions; 8068 BasePermission bp = permissionMap.get(p.info.name); 8069 8070 // Allow system apps to redefine non-system permissions 8071 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8072 final boolean currentOwnerIsSystem = (bp.perm != null 8073 && isSystemApp(bp.perm.owner)); 8074 if (isSystemApp(p.owner)) { 8075 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8076 // It's a built-in permission and no owner, take ownership now 8077 bp.packageSetting = pkgSetting; 8078 bp.perm = p; 8079 bp.uid = pkg.applicationInfo.uid; 8080 bp.sourcePackage = p.info.packageName; 8081 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8082 } else if (!currentOwnerIsSystem) { 8083 String msg = "New decl " + p.owner + " of permission " 8084 + p.info.name + " is system; overriding " + bp.sourcePackage; 8085 reportSettingsProblem(Log.WARN, msg); 8086 bp = null; 8087 } 8088 } 8089 } 8090 8091 if (bp == null) { 8092 bp = new BasePermission(p.info.name, p.info.packageName, 8093 BasePermission.TYPE_NORMAL); 8094 permissionMap.put(p.info.name, bp); 8095 } 8096 8097 if (bp.perm == null) { 8098 if (bp.sourcePackage == null 8099 || bp.sourcePackage.equals(p.info.packageName)) { 8100 BasePermission tree = findPermissionTreeLP(p.info.name); 8101 if (tree == null 8102 || tree.sourcePackage.equals(p.info.packageName)) { 8103 bp.packageSetting = pkgSetting; 8104 bp.perm = p; 8105 bp.uid = pkg.applicationInfo.uid; 8106 bp.sourcePackage = p.info.packageName; 8107 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8108 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8109 if (r == null) { 8110 r = new StringBuilder(256); 8111 } else { 8112 r.append(' '); 8113 } 8114 r.append(p.info.name); 8115 } 8116 } else { 8117 Slog.w(TAG, "Permission " + p.info.name + " from package " 8118 + p.info.packageName + " ignored: base tree " 8119 + tree.name + " is from package " 8120 + tree.sourcePackage); 8121 } 8122 } else { 8123 Slog.w(TAG, "Permission " + p.info.name + " from package " 8124 + p.info.packageName + " ignored: original from " 8125 + bp.sourcePackage); 8126 } 8127 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8128 if (r == null) { 8129 r = new StringBuilder(256); 8130 } else { 8131 r.append(' '); 8132 } 8133 r.append("DUP:"); 8134 r.append(p.info.name); 8135 } 8136 if (bp.perm == p) { 8137 bp.protectionLevel = p.info.protectionLevel; 8138 } 8139 } 8140 8141 if (r != null) { 8142 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8143 } 8144 8145 N = pkg.instrumentation.size(); 8146 r = null; 8147 for (i=0; i<N; i++) { 8148 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8149 a.info.packageName = pkg.applicationInfo.packageName; 8150 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8151 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8152 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8153 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8154 a.info.dataDir = pkg.applicationInfo.dataDir; 8155 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 8156 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 8157 8158 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8159 // need other information about the application, like the ABI and what not ? 8160 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8161 mInstrumentation.put(a.getComponentName(), a); 8162 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8163 if (r == null) { 8164 r = new StringBuilder(256); 8165 } else { 8166 r.append(' '); 8167 } 8168 r.append(a.info.name); 8169 } 8170 } 8171 if (r != null) { 8172 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8173 } 8174 8175 if (pkg.protectedBroadcasts != null) { 8176 N = pkg.protectedBroadcasts.size(); 8177 for (i=0; i<N; i++) { 8178 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8179 } 8180 } 8181 8182 pkgSetting.setTimeStamp(scanFileTime); 8183 8184 // Create idmap files for pairs of (packages, overlay packages). 8185 // Note: "android", ie framework-res.apk, is handled by native layers. 8186 if (pkg.mOverlayTarget != null) { 8187 // This is an overlay package. 8188 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8189 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8190 mOverlays.put(pkg.mOverlayTarget, 8191 new ArrayMap<String, PackageParser.Package>()); 8192 } 8193 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8194 map.put(pkg.packageName, pkg); 8195 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8196 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8197 createIdmapFailed = true; 8198 } 8199 } 8200 } else if (mOverlays.containsKey(pkg.packageName) && 8201 !pkg.packageName.equals("android")) { 8202 // This is a regular package, with one or more known overlay packages. 8203 createIdmapsForPackageLI(pkg); 8204 } 8205 } 8206 8207 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8208 8209 if (createIdmapFailed) { 8210 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8211 "scanPackageLI failed to createIdmap"); 8212 } 8213 return pkg; 8214 } 8215 8216 /** 8217 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8218 * is derived purely on the basis of the contents of {@code scanFile} and 8219 * {@code cpuAbiOverride}. 8220 * 8221 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8222 */ 8223 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8224 String cpuAbiOverride, boolean extractLibs) 8225 throws PackageManagerException { 8226 // TODO: We can probably be smarter about this stuff. For installed apps, 8227 // we can calculate this information at install time once and for all. For 8228 // system apps, we can probably assume that this information doesn't change 8229 // after the first boot scan. As things stand, we do lots of unnecessary work. 8230 8231 // Give ourselves some initial paths; we'll come back for another 8232 // pass once we've determined ABI below. 8233 setNativeLibraryPaths(pkg); 8234 8235 // We would never need to extract libs for forward-locked and external packages, 8236 // since the container service will do it for us. We shouldn't attempt to 8237 // extract libs from system app when it was not updated. 8238 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8239 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8240 extractLibs = false; 8241 } 8242 8243 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8244 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8245 8246 NativeLibraryHelper.Handle handle = null; 8247 try { 8248 handle = NativeLibraryHelper.Handle.create(pkg); 8249 // TODO(multiArch): This can be null for apps that didn't go through the 8250 // usual installation process. We can calculate it again, like we 8251 // do during install time. 8252 // 8253 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8254 // unnecessary. 8255 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8256 8257 // Null out the abis so that they can be recalculated. 8258 pkg.applicationInfo.primaryCpuAbi = null; 8259 pkg.applicationInfo.secondaryCpuAbi = null; 8260 if (isMultiArch(pkg.applicationInfo)) { 8261 // Warn if we've set an abiOverride for multi-lib packages.. 8262 // By definition, we need to copy both 32 and 64 bit libraries for 8263 // such packages. 8264 if (pkg.cpuAbiOverride != null 8265 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8266 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8267 } 8268 8269 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8270 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8271 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8272 if (extractLibs) { 8273 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8274 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8275 useIsaSpecificSubdirs); 8276 } else { 8277 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8278 } 8279 } 8280 8281 maybeThrowExceptionForMultiArchCopy( 8282 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8283 8284 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8285 if (extractLibs) { 8286 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8287 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8288 useIsaSpecificSubdirs); 8289 } else { 8290 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8291 } 8292 } 8293 8294 maybeThrowExceptionForMultiArchCopy( 8295 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8296 8297 if (abi64 >= 0) { 8298 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8299 } 8300 8301 if (abi32 >= 0) { 8302 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8303 if (abi64 >= 0) { 8304 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8305 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8306 pkg.applicationInfo.primaryCpuAbi = abi; 8307 } else { 8308 pkg.applicationInfo.secondaryCpuAbi = abi; 8309 } 8310 } else { 8311 pkg.applicationInfo.primaryCpuAbi = abi; 8312 } 8313 } 8314 8315 } else { 8316 String[] abiList = (cpuAbiOverride != null) ? 8317 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8318 8319 // Enable gross and lame hacks for apps that are built with old 8320 // SDK tools. We must scan their APKs for renderscript bitcode and 8321 // not launch them if it's present. Don't bother checking on devices 8322 // that don't have 64 bit support. 8323 boolean needsRenderScriptOverride = false; 8324 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8325 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8326 abiList = Build.SUPPORTED_32_BIT_ABIS; 8327 needsRenderScriptOverride = true; 8328 } 8329 8330 final int copyRet; 8331 if (extractLibs) { 8332 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8333 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8334 } else { 8335 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8336 } 8337 8338 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8339 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8340 "Error unpackaging native libs for app, errorCode=" + copyRet); 8341 } 8342 8343 if (copyRet >= 0) { 8344 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8345 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8346 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8347 } else if (needsRenderScriptOverride) { 8348 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8349 } 8350 } 8351 } catch (IOException ioe) { 8352 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8353 } finally { 8354 IoUtils.closeQuietly(handle); 8355 } 8356 8357 // Now that we've calculated the ABIs and determined if it's an internal app, 8358 // we will go ahead and populate the nativeLibraryPath. 8359 setNativeLibraryPaths(pkg); 8360 } 8361 8362 /** 8363 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8364 * i.e, so that all packages can be run inside a single process if required. 8365 * 8366 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8367 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8368 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8369 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8370 * updating a package that belongs to a shared user. 8371 * 8372 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8373 * adds unnecessary complexity. 8374 */ 8375 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8376 PackageParser.Package scannedPackage, boolean bootComplete) { 8377 String requiredInstructionSet = null; 8378 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8379 requiredInstructionSet = VMRuntime.getInstructionSet( 8380 scannedPackage.applicationInfo.primaryCpuAbi); 8381 } 8382 8383 PackageSetting requirer = null; 8384 for (PackageSetting ps : packagesForUser) { 8385 // If packagesForUser contains scannedPackage, we skip it. This will happen 8386 // when scannedPackage is an update of an existing package. Without this check, 8387 // we will never be able to change the ABI of any package belonging to a shared 8388 // user, even if it's compatible with other packages. 8389 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8390 if (ps.primaryCpuAbiString == null) { 8391 continue; 8392 } 8393 8394 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8395 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8396 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8397 // this but there's not much we can do. 8398 String errorMessage = "Instruction set mismatch, " 8399 + ((requirer == null) ? "[caller]" : requirer) 8400 + " requires " + requiredInstructionSet + " whereas " + ps 8401 + " requires " + instructionSet; 8402 Slog.w(TAG, errorMessage); 8403 } 8404 8405 if (requiredInstructionSet == null) { 8406 requiredInstructionSet = instructionSet; 8407 requirer = ps; 8408 } 8409 } 8410 } 8411 8412 if (requiredInstructionSet != null) { 8413 String adjustedAbi; 8414 if (requirer != null) { 8415 // requirer != null implies that either scannedPackage was null or that scannedPackage 8416 // did not require an ABI, in which case we have to adjust scannedPackage to match 8417 // the ABI of the set (which is the same as requirer's ABI) 8418 adjustedAbi = requirer.primaryCpuAbiString; 8419 if (scannedPackage != null) { 8420 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8421 } 8422 } else { 8423 // requirer == null implies that we're updating all ABIs in the set to 8424 // match scannedPackage. 8425 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8426 } 8427 8428 for (PackageSetting ps : packagesForUser) { 8429 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8430 if (ps.primaryCpuAbiString != null) { 8431 continue; 8432 } 8433 8434 ps.primaryCpuAbiString = adjustedAbi; 8435 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8436 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8437 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8438 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8439 + " (requirer=" 8440 + (requirer == null ? "null" : requirer.pkg.packageName) 8441 + ", scannedPackage=" 8442 + (scannedPackage != null ? scannedPackage.packageName : "null") 8443 + ")"); 8444 try { 8445 mInstaller.rmdex(ps.codePathString, 8446 getDexCodeInstructionSet(getPreferredInstructionSet())); 8447 } catch (InstallerException ignored) { 8448 } 8449 } 8450 } 8451 } 8452 } 8453 } 8454 8455 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8456 synchronized (mPackages) { 8457 mResolverReplaced = true; 8458 // Set up information for custom user intent resolution activity. 8459 mResolveActivity.applicationInfo = pkg.applicationInfo; 8460 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8461 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8462 mResolveActivity.processName = pkg.applicationInfo.packageName; 8463 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8464 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8465 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8466 mResolveActivity.theme = 0; 8467 mResolveActivity.exported = true; 8468 mResolveActivity.enabled = true; 8469 mResolveInfo.activityInfo = mResolveActivity; 8470 mResolveInfo.priority = 0; 8471 mResolveInfo.preferredOrder = 0; 8472 mResolveInfo.match = 0; 8473 mResolveComponentName = mCustomResolverComponentName; 8474 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8475 mResolveComponentName); 8476 } 8477 } 8478 8479 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8480 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8481 8482 // Set up information for ephemeral installer activity 8483 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8484 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8485 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8486 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8487 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8488 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8489 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8490 mEphemeralInstallerActivity.theme = 0; 8491 mEphemeralInstallerActivity.exported = true; 8492 mEphemeralInstallerActivity.enabled = true; 8493 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8494 mEphemeralInstallerInfo.priority = 0; 8495 mEphemeralInstallerInfo.preferredOrder = 0; 8496 mEphemeralInstallerInfo.match = 0; 8497 8498 if (DEBUG_EPHEMERAL) { 8499 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8500 } 8501 } 8502 8503 private static String calculateBundledApkRoot(final String codePathString) { 8504 final File codePath = new File(codePathString); 8505 final File codeRoot; 8506 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8507 codeRoot = Environment.getRootDirectory(); 8508 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8509 codeRoot = Environment.getOemDirectory(); 8510 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8511 codeRoot = Environment.getVendorDirectory(); 8512 } else { 8513 // Unrecognized code path; take its top real segment as the apk root: 8514 // e.g. /something/app/blah.apk => /something 8515 try { 8516 File f = codePath.getCanonicalFile(); 8517 File parent = f.getParentFile(); // non-null because codePath is a file 8518 File tmp; 8519 while ((tmp = parent.getParentFile()) != null) { 8520 f = parent; 8521 parent = tmp; 8522 } 8523 codeRoot = f; 8524 Slog.w(TAG, "Unrecognized code path " 8525 + codePath + " - using " + codeRoot); 8526 } catch (IOException e) { 8527 // Can't canonicalize the code path -- shenanigans? 8528 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8529 return Environment.getRootDirectory().getPath(); 8530 } 8531 } 8532 return codeRoot.getPath(); 8533 } 8534 8535 /** 8536 * Derive and set the location of native libraries for the given package, 8537 * which varies depending on where and how the package was installed. 8538 */ 8539 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8540 final ApplicationInfo info = pkg.applicationInfo; 8541 final String codePath = pkg.codePath; 8542 final File codeFile = new File(codePath); 8543 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8544 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8545 8546 info.nativeLibraryRootDir = null; 8547 info.nativeLibraryRootRequiresIsa = false; 8548 info.nativeLibraryDir = null; 8549 info.secondaryNativeLibraryDir = null; 8550 8551 if (isApkFile(codeFile)) { 8552 // Monolithic install 8553 if (bundledApp) { 8554 // If "/system/lib64/apkname" exists, assume that is the per-package 8555 // native library directory to use; otherwise use "/system/lib/apkname". 8556 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8557 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8558 getPrimaryInstructionSet(info)); 8559 8560 // This is a bundled system app so choose the path based on the ABI. 8561 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8562 // is just the default path. 8563 final String apkName = deriveCodePathName(codePath); 8564 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8565 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8566 apkName).getAbsolutePath(); 8567 8568 if (info.secondaryCpuAbi != null) { 8569 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8570 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8571 secondaryLibDir, apkName).getAbsolutePath(); 8572 } 8573 } else if (asecApp) { 8574 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8575 .getAbsolutePath(); 8576 } else { 8577 final String apkName = deriveCodePathName(codePath); 8578 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8579 .getAbsolutePath(); 8580 } 8581 8582 info.nativeLibraryRootRequiresIsa = false; 8583 info.nativeLibraryDir = info.nativeLibraryRootDir; 8584 } else { 8585 // Cluster install 8586 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8587 info.nativeLibraryRootRequiresIsa = true; 8588 8589 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8590 getPrimaryInstructionSet(info)).getAbsolutePath(); 8591 8592 if (info.secondaryCpuAbi != null) { 8593 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8594 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8595 } 8596 } 8597 } 8598 8599 /** 8600 * Calculate the abis and roots for a bundled app. These can uniquely 8601 * be determined from the contents of the system partition, i.e whether 8602 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8603 * of this information, and instead assume that the system was built 8604 * sensibly. 8605 */ 8606 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8607 PackageSetting pkgSetting) { 8608 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8609 8610 // If "/system/lib64/apkname" exists, assume that is the per-package 8611 // native library directory to use; otherwise use "/system/lib/apkname". 8612 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8613 setBundledAppAbi(pkg, apkRoot, apkName); 8614 // pkgSetting might be null during rescan following uninstall of updates 8615 // to a bundled app, so accommodate that possibility. The settings in 8616 // that case will be established later from the parsed package. 8617 // 8618 // If the settings aren't null, sync them up with what we've just derived. 8619 // note that apkRoot isn't stored in the package settings. 8620 if (pkgSetting != null) { 8621 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8622 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8623 } 8624 } 8625 8626 /** 8627 * Deduces the ABI of a bundled app and sets the relevant fields on the 8628 * parsed pkg object. 8629 * 8630 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8631 * under which system libraries are installed. 8632 * @param apkName the name of the installed package. 8633 */ 8634 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8635 final File codeFile = new File(pkg.codePath); 8636 8637 final boolean has64BitLibs; 8638 final boolean has32BitLibs; 8639 if (isApkFile(codeFile)) { 8640 // Monolithic install 8641 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8642 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8643 } else { 8644 // Cluster install 8645 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8646 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8647 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8648 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8649 has64BitLibs = (new File(rootDir, isa)).exists(); 8650 } else { 8651 has64BitLibs = false; 8652 } 8653 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8654 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8655 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8656 has32BitLibs = (new File(rootDir, isa)).exists(); 8657 } else { 8658 has32BitLibs = false; 8659 } 8660 } 8661 8662 if (has64BitLibs && !has32BitLibs) { 8663 // The package has 64 bit libs, but not 32 bit libs. Its primary 8664 // ABI should be 64 bit. We can safely assume here that the bundled 8665 // native libraries correspond to the most preferred ABI in the list. 8666 8667 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8668 pkg.applicationInfo.secondaryCpuAbi = null; 8669 } else if (has32BitLibs && !has64BitLibs) { 8670 // The package has 32 bit libs but not 64 bit libs. Its primary 8671 // ABI should be 32 bit. 8672 8673 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8674 pkg.applicationInfo.secondaryCpuAbi = null; 8675 } else if (has32BitLibs && has64BitLibs) { 8676 // The application has both 64 and 32 bit bundled libraries. We check 8677 // here that the app declares multiArch support, and warn if it doesn't. 8678 // 8679 // We will be lenient here and record both ABIs. The primary will be the 8680 // ABI that's higher on the list, i.e, a device that's configured to prefer 8681 // 64 bit apps will see a 64 bit primary ABI, 8682 8683 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8684 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8685 } 8686 8687 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8688 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8689 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8690 } else { 8691 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8692 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8693 } 8694 } else { 8695 pkg.applicationInfo.primaryCpuAbi = null; 8696 pkg.applicationInfo.secondaryCpuAbi = null; 8697 } 8698 } 8699 8700 private void killPackage(PackageParser.Package pkg, String reason) { 8701 // Kill the parent package 8702 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8703 // Kill the child packages 8704 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8705 for (int i = 0; i < childCount; i++) { 8706 PackageParser.Package childPkg = pkg.childPackages.get(i); 8707 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8708 } 8709 } 8710 8711 private void killApplication(String pkgName, int appId, String reason) { 8712 // Request the ActivityManager to kill the process(only for existing packages) 8713 // so that we do not end up in a confused state while the user is still using the older 8714 // version of the application while the new one gets installed. 8715 IActivityManager am = ActivityManagerNative.getDefault(); 8716 if (am != null) { 8717 try { 8718 am.killApplicationWithAppId(pkgName, appId, reason); 8719 } catch (RemoteException e) { 8720 } 8721 } 8722 } 8723 8724 private void removePackageSettingLI(PackageParser.Package pkg, boolean chatty) { 8725 // Remove the parent package setting 8726 PackageSetting ps = (PackageSetting) pkg.mExtras; 8727 if (ps != null) { 8728 removePackageSettingLI(ps, chatty); 8729 } 8730 // Remove the child package setting 8731 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8732 for (int i = 0; i < childCount; i++) { 8733 PackageParser.Package childPkg = pkg.childPackages.get(i); 8734 ps = (PackageSetting) childPkg.mExtras; 8735 if (ps != null) { 8736 removePackageSettingLI(ps, chatty); 8737 } 8738 } 8739 } 8740 8741 void removePackageSettingLI(PackageSetting ps, boolean chatty) { 8742 if (DEBUG_INSTALL) { 8743 if (chatty) 8744 Log.d(TAG, "Removing package " + ps.name); 8745 } 8746 8747 // writer 8748 synchronized (mPackages) { 8749 mPackages.remove(ps.name); 8750 final PackageParser.Package pkg = ps.pkg; 8751 if (pkg != null) { 8752 cleanPackageDataStructuresLILPw(pkg, chatty); 8753 } 8754 } 8755 } 8756 8757 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8758 if (DEBUG_INSTALL) { 8759 if (chatty) 8760 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8761 } 8762 8763 // writer 8764 synchronized (mPackages) { 8765 // Remove the parent package 8766 mPackages.remove(pkg.applicationInfo.packageName); 8767 cleanPackageDataStructuresLILPw(pkg, chatty); 8768 8769 // Remove the child packages 8770 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8771 for (int i = 0; i < childCount; i++) { 8772 PackageParser.Package childPkg = pkg.childPackages.get(i); 8773 mPackages.remove(childPkg.applicationInfo.packageName); 8774 cleanPackageDataStructuresLILPw(childPkg, chatty); 8775 } 8776 } 8777 } 8778 8779 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8780 int N = pkg.providers.size(); 8781 StringBuilder r = null; 8782 int i; 8783 for (i=0; i<N; i++) { 8784 PackageParser.Provider p = pkg.providers.get(i); 8785 mProviders.removeProvider(p); 8786 if (p.info.authority == null) { 8787 8788 /* There was another ContentProvider with this authority when 8789 * this app was installed so this authority is null, 8790 * Ignore it as we don't have to unregister the provider. 8791 */ 8792 continue; 8793 } 8794 String names[] = p.info.authority.split(";"); 8795 for (int j = 0; j < names.length; j++) { 8796 if (mProvidersByAuthority.get(names[j]) == p) { 8797 mProvidersByAuthority.remove(names[j]); 8798 if (DEBUG_REMOVE) { 8799 if (chatty) 8800 Log.d(TAG, "Unregistered content provider: " + names[j] 8801 + ", className = " + p.info.name + ", isSyncable = " 8802 + p.info.isSyncable); 8803 } 8804 } 8805 } 8806 if (DEBUG_REMOVE && chatty) { 8807 if (r == null) { 8808 r = new StringBuilder(256); 8809 } else { 8810 r.append(' '); 8811 } 8812 r.append(p.info.name); 8813 } 8814 } 8815 if (r != null) { 8816 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8817 } 8818 8819 N = pkg.services.size(); 8820 r = null; 8821 for (i=0; i<N; i++) { 8822 PackageParser.Service s = pkg.services.get(i); 8823 mServices.removeService(s); 8824 if (chatty) { 8825 if (r == null) { 8826 r = new StringBuilder(256); 8827 } else { 8828 r.append(' '); 8829 } 8830 r.append(s.info.name); 8831 } 8832 } 8833 if (r != null) { 8834 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8835 } 8836 8837 N = pkg.receivers.size(); 8838 r = null; 8839 for (i=0; i<N; i++) { 8840 PackageParser.Activity a = pkg.receivers.get(i); 8841 mReceivers.removeActivity(a, "receiver"); 8842 if (DEBUG_REMOVE && chatty) { 8843 if (r == null) { 8844 r = new StringBuilder(256); 8845 } else { 8846 r.append(' '); 8847 } 8848 r.append(a.info.name); 8849 } 8850 } 8851 if (r != null) { 8852 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8853 } 8854 8855 N = pkg.activities.size(); 8856 r = null; 8857 for (i=0; i<N; i++) { 8858 PackageParser.Activity a = pkg.activities.get(i); 8859 mActivities.removeActivity(a, "activity"); 8860 if (DEBUG_REMOVE && chatty) { 8861 if (r == null) { 8862 r = new StringBuilder(256); 8863 } else { 8864 r.append(' '); 8865 } 8866 r.append(a.info.name); 8867 } 8868 } 8869 if (r != null) { 8870 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8871 } 8872 8873 N = pkg.permissions.size(); 8874 r = null; 8875 for (i=0; i<N; i++) { 8876 PackageParser.Permission p = pkg.permissions.get(i); 8877 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8878 if (bp == null) { 8879 bp = mSettings.mPermissionTrees.get(p.info.name); 8880 } 8881 if (bp != null && bp.perm == p) { 8882 bp.perm = null; 8883 if (DEBUG_REMOVE && chatty) { 8884 if (r == null) { 8885 r = new StringBuilder(256); 8886 } else { 8887 r.append(' '); 8888 } 8889 r.append(p.info.name); 8890 } 8891 } 8892 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8893 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8894 if (appOpPkgs != null) { 8895 appOpPkgs.remove(pkg.packageName); 8896 } 8897 } 8898 } 8899 if (r != null) { 8900 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8901 } 8902 8903 N = pkg.requestedPermissions.size(); 8904 r = null; 8905 for (i=0; i<N; i++) { 8906 String perm = pkg.requestedPermissions.get(i); 8907 BasePermission bp = mSettings.mPermissions.get(perm); 8908 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8909 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8910 if (appOpPkgs != null) { 8911 appOpPkgs.remove(pkg.packageName); 8912 if (appOpPkgs.isEmpty()) { 8913 mAppOpPermissionPackages.remove(perm); 8914 } 8915 } 8916 } 8917 } 8918 if (r != null) { 8919 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8920 } 8921 8922 N = pkg.instrumentation.size(); 8923 r = null; 8924 for (i=0; i<N; i++) { 8925 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8926 mInstrumentation.remove(a.getComponentName()); 8927 if (DEBUG_REMOVE && chatty) { 8928 if (r == null) { 8929 r = new StringBuilder(256); 8930 } else { 8931 r.append(' '); 8932 } 8933 r.append(a.info.name); 8934 } 8935 } 8936 if (r != null) { 8937 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8938 } 8939 8940 r = null; 8941 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8942 // Only system apps can hold shared libraries. 8943 if (pkg.libraryNames != null) { 8944 for (i=0; i<pkg.libraryNames.size(); i++) { 8945 String name = pkg.libraryNames.get(i); 8946 SharedLibraryEntry cur = mSharedLibraries.get(name); 8947 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8948 mSharedLibraries.remove(name); 8949 if (DEBUG_REMOVE && chatty) { 8950 if (r == null) { 8951 r = new StringBuilder(256); 8952 } else { 8953 r.append(' '); 8954 } 8955 r.append(name); 8956 } 8957 } 8958 } 8959 } 8960 } 8961 if (r != null) { 8962 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8963 } 8964 } 8965 8966 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8967 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8968 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8969 return true; 8970 } 8971 } 8972 return false; 8973 } 8974 8975 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8976 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8977 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8978 8979 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 8980 // Update the parent permissions 8981 updatePermissionsLPw(pkg.packageName, pkg, flags); 8982 // Update the child permissions 8983 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8984 for (int i = 0; i < childCount; i++) { 8985 PackageParser.Package childPkg = pkg.childPackages.get(i); 8986 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 8987 } 8988 } 8989 8990 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8991 int flags) { 8992 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8993 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8994 } 8995 8996 private void updatePermissionsLPw(String changingPkg, 8997 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8998 // Make sure there are no dangling permission trees. 8999 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9000 while (it.hasNext()) { 9001 final BasePermission bp = it.next(); 9002 if (bp.packageSetting == null) { 9003 // We may not yet have parsed the package, so just see if 9004 // we still know about its settings. 9005 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9006 } 9007 if (bp.packageSetting == null) { 9008 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9009 + " from package " + bp.sourcePackage); 9010 it.remove(); 9011 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9012 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9013 Slog.i(TAG, "Removing old permission tree: " + bp.name 9014 + " from package " + bp.sourcePackage); 9015 flags |= UPDATE_PERMISSIONS_ALL; 9016 it.remove(); 9017 } 9018 } 9019 } 9020 9021 // Make sure all dynamic permissions have been assigned to a package, 9022 // and make sure there are no dangling permissions. 9023 it = mSettings.mPermissions.values().iterator(); 9024 while (it.hasNext()) { 9025 final BasePermission bp = it.next(); 9026 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9027 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9028 + bp.name + " pkg=" + bp.sourcePackage 9029 + " info=" + bp.pendingInfo); 9030 if (bp.packageSetting == null && bp.pendingInfo != null) { 9031 final BasePermission tree = findPermissionTreeLP(bp.name); 9032 if (tree != null && tree.perm != null) { 9033 bp.packageSetting = tree.packageSetting; 9034 bp.perm = new PackageParser.Permission(tree.perm.owner, 9035 new PermissionInfo(bp.pendingInfo)); 9036 bp.perm.info.packageName = tree.perm.info.packageName; 9037 bp.perm.info.name = bp.name; 9038 bp.uid = tree.uid; 9039 } 9040 } 9041 } 9042 if (bp.packageSetting == null) { 9043 // We may not yet have parsed the package, so just see if 9044 // we still know about its settings. 9045 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9046 } 9047 if (bp.packageSetting == null) { 9048 Slog.w(TAG, "Removing dangling permission: " + bp.name 9049 + " from package " + bp.sourcePackage); 9050 it.remove(); 9051 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9052 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9053 Slog.i(TAG, "Removing old permission: " + bp.name 9054 + " from package " + bp.sourcePackage); 9055 flags |= UPDATE_PERMISSIONS_ALL; 9056 it.remove(); 9057 } 9058 } 9059 } 9060 9061 // Now update the permissions for all packages, in particular 9062 // replace the granted permissions of the system packages. 9063 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9064 for (PackageParser.Package pkg : mPackages.values()) { 9065 if (pkg != pkgInfo) { 9066 // Only replace for packages on requested volume 9067 final String volumeUuid = getVolumeUuidForPackage(pkg); 9068 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9069 && Objects.equals(replaceVolumeUuid, volumeUuid); 9070 grantPermissionsLPw(pkg, replace, changingPkg); 9071 } 9072 } 9073 } 9074 9075 if (pkgInfo != null) { 9076 // Only replace for packages on requested volume 9077 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9078 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9079 && Objects.equals(replaceVolumeUuid, volumeUuid); 9080 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9081 } 9082 } 9083 9084 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9085 String packageOfInterest) { 9086 // IMPORTANT: There are two types of permissions: install and runtime. 9087 // Install time permissions are granted when the app is installed to 9088 // all device users and users added in the future. Runtime permissions 9089 // are granted at runtime explicitly to specific users. Normal and signature 9090 // protected permissions are install time permissions. Dangerous permissions 9091 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9092 // otherwise they are runtime permissions. This function does not manage 9093 // runtime permissions except for the case an app targeting Lollipop MR1 9094 // being upgraded to target a newer SDK, in which case dangerous permissions 9095 // are transformed from install time to runtime ones. 9096 9097 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9098 if (ps == null) { 9099 return; 9100 } 9101 9102 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9103 9104 PermissionsState permissionsState = ps.getPermissionsState(); 9105 PermissionsState origPermissions = permissionsState; 9106 9107 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9108 9109 boolean runtimePermissionsRevoked = false; 9110 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9111 9112 boolean changedInstallPermission = false; 9113 9114 if (replace) { 9115 ps.installPermissionsFixed = false; 9116 if (!ps.isSharedUser()) { 9117 origPermissions = new PermissionsState(permissionsState); 9118 permissionsState.reset(); 9119 } else { 9120 // We need to know only about runtime permission changes since the 9121 // calling code always writes the install permissions state but 9122 // the runtime ones are written only if changed. The only cases of 9123 // changed runtime permissions here are promotion of an install to 9124 // runtime and revocation of a runtime from a shared user. 9125 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9126 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9127 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9128 runtimePermissionsRevoked = true; 9129 } 9130 } 9131 } 9132 9133 permissionsState.setGlobalGids(mGlobalGids); 9134 9135 final int N = pkg.requestedPermissions.size(); 9136 for (int i=0; i<N; i++) { 9137 final String name = pkg.requestedPermissions.get(i); 9138 final BasePermission bp = mSettings.mPermissions.get(name); 9139 9140 if (DEBUG_INSTALL) { 9141 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9142 } 9143 9144 if (bp == null || bp.packageSetting == null) { 9145 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9146 Slog.w(TAG, "Unknown permission " + name 9147 + " in package " + pkg.packageName); 9148 } 9149 continue; 9150 } 9151 9152 final String perm = bp.name; 9153 boolean allowedSig = false; 9154 int grant = GRANT_DENIED; 9155 9156 // Keep track of app op permissions. 9157 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9158 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9159 if (pkgs == null) { 9160 pkgs = new ArraySet<>(); 9161 mAppOpPermissionPackages.put(bp.name, pkgs); 9162 } 9163 pkgs.add(pkg.packageName); 9164 } 9165 9166 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9167 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9168 >= Build.VERSION_CODES.M; 9169 switch (level) { 9170 case PermissionInfo.PROTECTION_NORMAL: { 9171 // For all apps normal permissions are install time ones. 9172 grant = GRANT_INSTALL; 9173 } break; 9174 9175 case PermissionInfo.PROTECTION_DANGEROUS: { 9176 // If a permission review is required for legacy apps we represent 9177 // their permissions as always granted runtime ones since we need 9178 // to keep the review required permission flag per user while an 9179 // install permission's state is shared across all users. 9180 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9181 // For legacy apps dangerous permissions are install time ones. 9182 grant = GRANT_INSTALL; 9183 } else if (origPermissions.hasInstallPermission(bp.name)) { 9184 // For legacy apps that became modern, install becomes runtime. 9185 grant = GRANT_UPGRADE; 9186 } else if (mPromoteSystemApps 9187 && isSystemApp(ps) 9188 && mExistingSystemPackages.contains(ps.name)) { 9189 // For legacy system apps, install becomes runtime. 9190 // We cannot check hasInstallPermission() for system apps since those 9191 // permissions were granted implicitly and not persisted pre-M. 9192 grant = GRANT_UPGRADE; 9193 } else { 9194 // For modern apps keep runtime permissions unchanged. 9195 grant = GRANT_RUNTIME; 9196 } 9197 } break; 9198 9199 case PermissionInfo.PROTECTION_SIGNATURE: { 9200 // For all apps signature permissions are install time ones. 9201 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9202 if (allowedSig) { 9203 grant = GRANT_INSTALL; 9204 } 9205 } break; 9206 } 9207 9208 if (DEBUG_INSTALL) { 9209 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9210 } 9211 9212 if (grant != GRANT_DENIED) { 9213 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9214 // If this is an existing, non-system package, then 9215 // we can't add any new permissions to it. 9216 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9217 // Except... if this is a permission that was added 9218 // to the platform (note: need to only do this when 9219 // updating the platform). 9220 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9221 grant = GRANT_DENIED; 9222 } 9223 } 9224 } 9225 9226 switch (grant) { 9227 case GRANT_INSTALL: { 9228 // Revoke this as runtime permission to handle the case of 9229 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9230 for (int userId : UserManagerService.getInstance().getUserIds()) { 9231 if (origPermissions.getRuntimePermissionState( 9232 bp.name, userId) != null) { 9233 // Revoke the runtime permission and clear the flags. 9234 origPermissions.revokeRuntimePermission(bp, userId); 9235 origPermissions.updatePermissionFlags(bp, userId, 9236 PackageManager.MASK_PERMISSION_FLAGS, 0); 9237 // If we revoked a permission permission, we have to write. 9238 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9239 changedRuntimePermissionUserIds, userId); 9240 } 9241 } 9242 // Grant an install permission. 9243 if (permissionsState.grantInstallPermission(bp) != 9244 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9245 changedInstallPermission = true; 9246 } 9247 } break; 9248 9249 case GRANT_RUNTIME: { 9250 // Grant previously granted runtime permissions. 9251 for (int userId : UserManagerService.getInstance().getUserIds()) { 9252 PermissionState permissionState = origPermissions 9253 .getRuntimePermissionState(bp.name, userId); 9254 int flags = permissionState != null 9255 ? permissionState.getFlags() : 0; 9256 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9257 if (permissionsState.grantRuntimePermission(bp, userId) == 9258 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9259 // If we cannot put the permission as it was, we have to write. 9260 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9261 changedRuntimePermissionUserIds, userId); 9262 } 9263 // If the app supports runtime permissions no need for a review. 9264 if (Build.PERMISSIONS_REVIEW_REQUIRED 9265 && appSupportsRuntimePermissions 9266 && (flags & PackageManager 9267 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9268 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9269 // Since we changed the flags, we have to write. 9270 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9271 changedRuntimePermissionUserIds, userId); 9272 } 9273 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9274 && !appSupportsRuntimePermissions) { 9275 // For legacy apps that need a permission review, every new 9276 // runtime permission is granted but it is pending a review. 9277 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9278 permissionsState.grantRuntimePermission(bp, userId); 9279 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9280 // We changed the permission and flags, hence have to write. 9281 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9282 changedRuntimePermissionUserIds, userId); 9283 } 9284 } 9285 // Propagate the permission flags. 9286 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9287 } 9288 } break; 9289 9290 case GRANT_UPGRADE: { 9291 // Grant runtime permissions for a previously held install permission. 9292 PermissionState permissionState = origPermissions 9293 .getInstallPermissionState(bp.name); 9294 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9295 9296 if (origPermissions.revokeInstallPermission(bp) 9297 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9298 // We will be transferring the permission flags, so clear them. 9299 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9300 PackageManager.MASK_PERMISSION_FLAGS, 0); 9301 changedInstallPermission = true; 9302 } 9303 9304 // If the permission is not to be promoted to runtime we ignore it and 9305 // also its other flags as they are not applicable to install permissions. 9306 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9307 for (int userId : currentUserIds) { 9308 if (permissionsState.grantRuntimePermission(bp, userId) != 9309 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9310 // Transfer the permission flags. 9311 permissionsState.updatePermissionFlags(bp, userId, 9312 flags, flags); 9313 // If we granted the permission, we have to write. 9314 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9315 changedRuntimePermissionUserIds, userId); 9316 } 9317 } 9318 } 9319 } break; 9320 9321 default: { 9322 if (packageOfInterest == null 9323 || packageOfInterest.equals(pkg.packageName)) { 9324 Slog.w(TAG, "Not granting permission " + perm 9325 + " to package " + pkg.packageName 9326 + " because it was previously installed without"); 9327 } 9328 } break; 9329 } 9330 } else { 9331 if (permissionsState.revokeInstallPermission(bp) != 9332 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9333 // Also drop the permission flags. 9334 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9335 PackageManager.MASK_PERMISSION_FLAGS, 0); 9336 changedInstallPermission = true; 9337 Slog.i(TAG, "Un-granting permission " + perm 9338 + " from package " + pkg.packageName 9339 + " (protectionLevel=" + bp.protectionLevel 9340 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9341 + ")"); 9342 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9343 // Don't print warning for app op permissions, since it is fine for them 9344 // not to be granted, there is a UI for the user to decide. 9345 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9346 Slog.w(TAG, "Not granting permission " + perm 9347 + " to package " + pkg.packageName 9348 + " (protectionLevel=" + bp.protectionLevel 9349 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9350 + ")"); 9351 } 9352 } 9353 } 9354 } 9355 9356 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9357 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9358 // This is the first that we have heard about this package, so the 9359 // permissions we have now selected are fixed until explicitly 9360 // changed. 9361 ps.installPermissionsFixed = true; 9362 } 9363 9364 // Persist the runtime permissions state for users with changes. If permissions 9365 // were revoked because no app in the shared user declares them we have to 9366 // write synchronously to avoid losing runtime permissions state. 9367 for (int userId : changedRuntimePermissionUserIds) { 9368 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9369 } 9370 9371 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9372 } 9373 9374 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9375 boolean allowed = false; 9376 final int NP = PackageParser.NEW_PERMISSIONS.length; 9377 for (int ip=0; ip<NP; ip++) { 9378 final PackageParser.NewPermissionInfo npi 9379 = PackageParser.NEW_PERMISSIONS[ip]; 9380 if (npi.name.equals(perm) 9381 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9382 allowed = true; 9383 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9384 + pkg.packageName); 9385 break; 9386 } 9387 } 9388 return allowed; 9389 } 9390 9391 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9392 BasePermission bp, PermissionsState origPermissions) { 9393 boolean allowed; 9394 allowed = (compareSignatures( 9395 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9396 == PackageManager.SIGNATURE_MATCH) 9397 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9398 == PackageManager.SIGNATURE_MATCH); 9399 if (!allowed && (bp.protectionLevel 9400 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9401 if (isSystemApp(pkg)) { 9402 // For updated system applications, a system permission 9403 // is granted only if it had been defined by the original application. 9404 if (pkg.isUpdatedSystemApp()) { 9405 final PackageSetting sysPs = mSettings 9406 .getDisabledSystemPkgLPr(pkg.packageName); 9407 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9408 // If the original was granted this permission, we take 9409 // that grant decision as read and propagate it to the 9410 // update. 9411 if (sysPs.isPrivileged()) { 9412 allowed = true; 9413 } 9414 } else { 9415 // The system apk may have been updated with an older 9416 // version of the one on the data partition, but which 9417 // granted a new system permission that it didn't have 9418 // before. In this case we do want to allow the app to 9419 // now get the new permission if the ancestral apk is 9420 // privileged to get it. 9421 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9422 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9423 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9424 allowed = true; 9425 break; 9426 } 9427 } 9428 } 9429 // Also if a privileged parent package on the system image or any of 9430 // its children requested a privileged permission, the updated child 9431 // packages can also get the permission. 9432 if (pkg.parentPackage != null) { 9433 final PackageSetting disabledSysParentPs = mSettings 9434 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9435 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9436 && disabledSysParentPs.isPrivileged()) { 9437 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9438 allowed = true; 9439 } else if (disabledSysParentPs.pkg.childPackages != null) { 9440 final int count = disabledSysParentPs.pkg.childPackages.size(); 9441 for (int i = 0; i < count; i++) { 9442 PackageParser.Package disabledSysChildPkg = 9443 disabledSysParentPs.pkg.childPackages.get(i); 9444 if (isPackageRequestingPermission(disabledSysChildPkg, 9445 perm)) { 9446 allowed = true; 9447 break; 9448 } 9449 } 9450 } 9451 } 9452 } 9453 } 9454 } else { 9455 allowed = isPrivilegedApp(pkg); 9456 } 9457 } 9458 } 9459 if (!allowed) { 9460 if (!allowed && (bp.protectionLevel 9461 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9462 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9463 // If this was a previously normal/dangerous permission that got moved 9464 // to a system permission as part of the runtime permission redesign, then 9465 // we still want to blindly grant it to old apps. 9466 allowed = true; 9467 } 9468 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9469 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9470 // If this permission is to be granted to the system installer and 9471 // this app is an installer, then it gets the permission. 9472 allowed = true; 9473 } 9474 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9475 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9476 // If this permission is to be granted to the system verifier and 9477 // this app is a verifier, then it gets the permission. 9478 allowed = true; 9479 } 9480 if (!allowed && (bp.protectionLevel 9481 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9482 && isSystemApp(pkg)) { 9483 // Any pre-installed system app is allowed to get this permission. 9484 allowed = true; 9485 } 9486 if (!allowed && (bp.protectionLevel 9487 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9488 // For development permissions, a development permission 9489 // is granted only if it was already granted. 9490 allowed = origPermissions.hasInstallPermission(perm); 9491 } 9492 } 9493 return allowed; 9494 } 9495 9496 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9497 final int permCount = pkg.requestedPermissions.size(); 9498 for (int j = 0; j < permCount; j++) { 9499 String requestedPermission = pkg.requestedPermissions.get(j); 9500 if (permission.equals(requestedPermission)) { 9501 return true; 9502 } 9503 } 9504 return false; 9505 } 9506 9507 final class ActivityIntentResolver 9508 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9509 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9510 boolean defaultOnly, int userId) { 9511 if (!sUserManager.exists(userId)) return null; 9512 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9513 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9514 } 9515 9516 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9517 int userId) { 9518 if (!sUserManager.exists(userId)) return null; 9519 mFlags = flags; 9520 return super.queryIntent(intent, resolvedType, 9521 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9522 } 9523 9524 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9525 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9526 if (!sUserManager.exists(userId)) return null; 9527 if (packageActivities == null) { 9528 return null; 9529 } 9530 mFlags = flags; 9531 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9532 final int N = packageActivities.size(); 9533 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9534 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9535 9536 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9537 for (int i = 0; i < N; ++i) { 9538 intentFilters = packageActivities.get(i).intents; 9539 if (intentFilters != null && intentFilters.size() > 0) { 9540 PackageParser.ActivityIntentInfo[] array = 9541 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9542 intentFilters.toArray(array); 9543 listCut.add(array); 9544 } 9545 } 9546 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9547 } 9548 9549 public final void addActivity(PackageParser.Activity a, String type) { 9550 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9551 mActivities.put(a.getComponentName(), a); 9552 if (DEBUG_SHOW_INFO) 9553 Log.v( 9554 TAG, " " + type + " " + 9555 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9556 if (DEBUG_SHOW_INFO) 9557 Log.v(TAG, " Class=" + a.info.name); 9558 final int NI = a.intents.size(); 9559 for (int j=0; j<NI; j++) { 9560 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9561 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9562 intent.setPriority(0); 9563 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9564 + a.className + " with priority > 0, forcing to 0"); 9565 } 9566 if (DEBUG_SHOW_INFO) { 9567 Log.v(TAG, " IntentFilter:"); 9568 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9569 } 9570 if (!intent.debugCheck()) { 9571 Log.w(TAG, "==> For Activity " + a.info.name); 9572 } 9573 addFilter(intent); 9574 } 9575 } 9576 9577 public final void removeActivity(PackageParser.Activity a, String type) { 9578 mActivities.remove(a.getComponentName()); 9579 if (DEBUG_SHOW_INFO) { 9580 Log.v(TAG, " " + type + " " 9581 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9582 : a.info.name) + ":"); 9583 Log.v(TAG, " Class=" + a.info.name); 9584 } 9585 final int NI = a.intents.size(); 9586 for (int j=0; j<NI; j++) { 9587 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9588 if (DEBUG_SHOW_INFO) { 9589 Log.v(TAG, " IntentFilter:"); 9590 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9591 } 9592 removeFilter(intent); 9593 } 9594 } 9595 9596 @Override 9597 protected boolean allowFilterResult( 9598 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9599 ActivityInfo filterAi = filter.activity.info; 9600 for (int i=dest.size()-1; i>=0; i--) { 9601 ActivityInfo destAi = dest.get(i).activityInfo; 9602 if (destAi.name == filterAi.name 9603 && destAi.packageName == filterAi.packageName) { 9604 return false; 9605 } 9606 } 9607 return true; 9608 } 9609 9610 @Override 9611 protected ActivityIntentInfo[] newArray(int size) { 9612 return new ActivityIntentInfo[size]; 9613 } 9614 9615 @Override 9616 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9617 if (!sUserManager.exists(userId)) return true; 9618 PackageParser.Package p = filter.activity.owner; 9619 if (p != null) { 9620 PackageSetting ps = (PackageSetting)p.mExtras; 9621 if (ps != null) { 9622 // System apps are never considered stopped for purposes of 9623 // filtering, because there may be no way for the user to 9624 // actually re-launch them. 9625 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9626 && ps.getStopped(userId); 9627 } 9628 } 9629 return false; 9630 } 9631 9632 @Override 9633 protected boolean isPackageForFilter(String packageName, 9634 PackageParser.ActivityIntentInfo info) { 9635 return packageName.equals(info.activity.owner.packageName); 9636 } 9637 9638 @Override 9639 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9640 int match, int userId) { 9641 if (!sUserManager.exists(userId)) return null; 9642 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9643 return null; 9644 } 9645 final PackageParser.Activity activity = info.activity; 9646 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9647 if (ps == null) { 9648 return null; 9649 } 9650 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9651 ps.readUserState(userId), userId); 9652 if (ai == null) { 9653 return null; 9654 } 9655 final ResolveInfo res = new ResolveInfo(); 9656 res.activityInfo = ai; 9657 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9658 res.filter = info; 9659 } 9660 if (info != null) { 9661 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9662 } 9663 res.priority = info.getPriority(); 9664 res.preferredOrder = activity.owner.mPreferredOrder; 9665 //System.out.println("Result: " + res.activityInfo.className + 9666 // " = " + res.priority); 9667 res.match = match; 9668 res.isDefault = info.hasDefault; 9669 res.labelRes = info.labelRes; 9670 res.nonLocalizedLabel = info.nonLocalizedLabel; 9671 if (userNeedsBadging(userId)) { 9672 res.noResourceId = true; 9673 } else { 9674 res.icon = info.icon; 9675 } 9676 res.iconResourceId = info.icon; 9677 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9678 return res; 9679 } 9680 9681 @Override 9682 protected void sortResults(List<ResolveInfo> results) { 9683 Collections.sort(results, mResolvePrioritySorter); 9684 } 9685 9686 @Override 9687 protected void dumpFilter(PrintWriter out, String prefix, 9688 PackageParser.ActivityIntentInfo filter) { 9689 out.print(prefix); out.print( 9690 Integer.toHexString(System.identityHashCode(filter.activity))); 9691 out.print(' '); 9692 filter.activity.printComponentShortName(out); 9693 out.print(" filter "); 9694 out.println(Integer.toHexString(System.identityHashCode(filter))); 9695 } 9696 9697 @Override 9698 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9699 return filter.activity; 9700 } 9701 9702 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9703 PackageParser.Activity activity = (PackageParser.Activity)label; 9704 out.print(prefix); out.print( 9705 Integer.toHexString(System.identityHashCode(activity))); 9706 out.print(' '); 9707 activity.printComponentShortName(out); 9708 if (count > 1) { 9709 out.print(" ("); out.print(count); out.print(" filters)"); 9710 } 9711 out.println(); 9712 } 9713 9714// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9715// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9716// final List<ResolveInfo> retList = Lists.newArrayList(); 9717// while (i.hasNext()) { 9718// final ResolveInfo resolveInfo = i.next(); 9719// if (isEnabledLP(resolveInfo.activityInfo)) { 9720// retList.add(resolveInfo); 9721// } 9722// } 9723// return retList; 9724// } 9725 9726 // Keys are String (activity class name), values are Activity. 9727 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9728 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9729 private int mFlags; 9730 } 9731 9732 private final class ServiceIntentResolver 9733 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9734 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9735 boolean defaultOnly, int userId) { 9736 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9737 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9738 } 9739 9740 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9741 int userId) { 9742 if (!sUserManager.exists(userId)) return null; 9743 mFlags = flags; 9744 return super.queryIntent(intent, resolvedType, 9745 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9746 } 9747 9748 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9749 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9750 if (!sUserManager.exists(userId)) return null; 9751 if (packageServices == null) { 9752 return null; 9753 } 9754 mFlags = flags; 9755 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9756 final int N = packageServices.size(); 9757 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9758 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9759 9760 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9761 for (int i = 0; i < N; ++i) { 9762 intentFilters = packageServices.get(i).intents; 9763 if (intentFilters != null && intentFilters.size() > 0) { 9764 PackageParser.ServiceIntentInfo[] array = 9765 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9766 intentFilters.toArray(array); 9767 listCut.add(array); 9768 } 9769 } 9770 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9771 } 9772 9773 public final void addService(PackageParser.Service s) { 9774 mServices.put(s.getComponentName(), s); 9775 if (DEBUG_SHOW_INFO) { 9776 Log.v(TAG, " " 9777 + (s.info.nonLocalizedLabel != null 9778 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9779 Log.v(TAG, " Class=" + s.info.name); 9780 } 9781 final int NI = s.intents.size(); 9782 int j; 9783 for (j=0; j<NI; j++) { 9784 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9785 if (DEBUG_SHOW_INFO) { 9786 Log.v(TAG, " IntentFilter:"); 9787 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9788 } 9789 if (!intent.debugCheck()) { 9790 Log.w(TAG, "==> For Service " + s.info.name); 9791 } 9792 addFilter(intent); 9793 } 9794 } 9795 9796 public final void removeService(PackageParser.Service s) { 9797 mServices.remove(s.getComponentName()); 9798 if (DEBUG_SHOW_INFO) { 9799 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9800 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9801 Log.v(TAG, " Class=" + s.info.name); 9802 } 9803 final int NI = s.intents.size(); 9804 int j; 9805 for (j=0; j<NI; j++) { 9806 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9807 if (DEBUG_SHOW_INFO) { 9808 Log.v(TAG, " IntentFilter:"); 9809 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9810 } 9811 removeFilter(intent); 9812 } 9813 } 9814 9815 @Override 9816 protected boolean allowFilterResult( 9817 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9818 ServiceInfo filterSi = filter.service.info; 9819 for (int i=dest.size()-1; i>=0; i--) { 9820 ServiceInfo destAi = dest.get(i).serviceInfo; 9821 if (destAi.name == filterSi.name 9822 && destAi.packageName == filterSi.packageName) { 9823 return false; 9824 } 9825 } 9826 return true; 9827 } 9828 9829 @Override 9830 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9831 return new PackageParser.ServiceIntentInfo[size]; 9832 } 9833 9834 @Override 9835 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9836 if (!sUserManager.exists(userId)) return true; 9837 PackageParser.Package p = filter.service.owner; 9838 if (p != null) { 9839 PackageSetting ps = (PackageSetting)p.mExtras; 9840 if (ps != null) { 9841 // System apps are never considered stopped for purposes of 9842 // filtering, because there may be no way for the user to 9843 // actually re-launch them. 9844 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9845 && ps.getStopped(userId); 9846 } 9847 } 9848 return false; 9849 } 9850 9851 @Override 9852 protected boolean isPackageForFilter(String packageName, 9853 PackageParser.ServiceIntentInfo info) { 9854 return packageName.equals(info.service.owner.packageName); 9855 } 9856 9857 @Override 9858 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9859 int match, int userId) { 9860 if (!sUserManager.exists(userId)) return null; 9861 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9862 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9863 return null; 9864 } 9865 final PackageParser.Service service = info.service; 9866 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9867 if (ps == null) { 9868 return null; 9869 } 9870 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9871 ps.readUserState(userId), userId); 9872 if (si == null) { 9873 return null; 9874 } 9875 final ResolveInfo res = new ResolveInfo(); 9876 res.serviceInfo = si; 9877 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9878 res.filter = filter; 9879 } 9880 res.priority = info.getPriority(); 9881 res.preferredOrder = service.owner.mPreferredOrder; 9882 res.match = match; 9883 res.isDefault = info.hasDefault; 9884 res.labelRes = info.labelRes; 9885 res.nonLocalizedLabel = info.nonLocalizedLabel; 9886 res.icon = info.icon; 9887 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9888 return res; 9889 } 9890 9891 @Override 9892 protected void sortResults(List<ResolveInfo> results) { 9893 Collections.sort(results, mResolvePrioritySorter); 9894 } 9895 9896 @Override 9897 protected void dumpFilter(PrintWriter out, String prefix, 9898 PackageParser.ServiceIntentInfo filter) { 9899 out.print(prefix); out.print( 9900 Integer.toHexString(System.identityHashCode(filter.service))); 9901 out.print(' '); 9902 filter.service.printComponentShortName(out); 9903 out.print(" filter "); 9904 out.println(Integer.toHexString(System.identityHashCode(filter))); 9905 } 9906 9907 @Override 9908 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9909 return filter.service; 9910 } 9911 9912 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9913 PackageParser.Service service = (PackageParser.Service)label; 9914 out.print(prefix); out.print( 9915 Integer.toHexString(System.identityHashCode(service))); 9916 out.print(' '); 9917 service.printComponentShortName(out); 9918 if (count > 1) { 9919 out.print(" ("); out.print(count); out.print(" filters)"); 9920 } 9921 out.println(); 9922 } 9923 9924// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9925// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9926// final List<ResolveInfo> retList = Lists.newArrayList(); 9927// while (i.hasNext()) { 9928// final ResolveInfo resolveInfo = (ResolveInfo) i; 9929// if (isEnabledLP(resolveInfo.serviceInfo)) { 9930// retList.add(resolveInfo); 9931// } 9932// } 9933// return retList; 9934// } 9935 9936 // Keys are String (activity class name), values are Activity. 9937 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9938 = new ArrayMap<ComponentName, PackageParser.Service>(); 9939 private int mFlags; 9940 }; 9941 9942 private final class ProviderIntentResolver 9943 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9944 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9945 boolean defaultOnly, int userId) { 9946 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9947 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9948 } 9949 9950 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9951 int userId) { 9952 if (!sUserManager.exists(userId)) 9953 return null; 9954 mFlags = flags; 9955 return super.queryIntent(intent, resolvedType, 9956 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9957 } 9958 9959 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9960 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9961 if (!sUserManager.exists(userId)) 9962 return null; 9963 if (packageProviders == null) { 9964 return null; 9965 } 9966 mFlags = flags; 9967 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9968 final int N = packageProviders.size(); 9969 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9970 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9971 9972 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9973 for (int i = 0; i < N; ++i) { 9974 intentFilters = packageProviders.get(i).intents; 9975 if (intentFilters != null && intentFilters.size() > 0) { 9976 PackageParser.ProviderIntentInfo[] array = 9977 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9978 intentFilters.toArray(array); 9979 listCut.add(array); 9980 } 9981 } 9982 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9983 } 9984 9985 public final void addProvider(PackageParser.Provider p) { 9986 if (mProviders.containsKey(p.getComponentName())) { 9987 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9988 return; 9989 } 9990 9991 mProviders.put(p.getComponentName(), p); 9992 if (DEBUG_SHOW_INFO) { 9993 Log.v(TAG, " " 9994 + (p.info.nonLocalizedLabel != null 9995 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9996 Log.v(TAG, " Class=" + p.info.name); 9997 } 9998 final int NI = p.intents.size(); 9999 int j; 10000 for (j = 0; j < NI; j++) { 10001 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10002 if (DEBUG_SHOW_INFO) { 10003 Log.v(TAG, " IntentFilter:"); 10004 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10005 } 10006 if (!intent.debugCheck()) { 10007 Log.w(TAG, "==> For Provider " + p.info.name); 10008 } 10009 addFilter(intent); 10010 } 10011 } 10012 10013 public final void removeProvider(PackageParser.Provider p) { 10014 mProviders.remove(p.getComponentName()); 10015 if (DEBUG_SHOW_INFO) { 10016 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10017 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10018 Log.v(TAG, " Class=" + p.info.name); 10019 } 10020 final int NI = p.intents.size(); 10021 int j; 10022 for (j = 0; j < NI; j++) { 10023 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10024 if (DEBUG_SHOW_INFO) { 10025 Log.v(TAG, " IntentFilter:"); 10026 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10027 } 10028 removeFilter(intent); 10029 } 10030 } 10031 10032 @Override 10033 protected boolean allowFilterResult( 10034 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10035 ProviderInfo filterPi = filter.provider.info; 10036 for (int i = dest.size() - 1; i >= 0; i--) { 10037 ProviderInfo destPi = dest.get(i).providerInfo; 10038 if (destPi.name == filterPi.name 10039 && destPi.packageName == filterPi.packageName) { 10040 return false; 10041 } 10042 } 10043 return true; 10044 } 10045 10046 @Override 10047 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10048 return new PackageParser.ProviderIntentInfo[size]; 10049 } 10050 10051 @Override 10052 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10053 if (!sUserManager.exists(userId)) 10054 return true; 10055 PackageParser.Package p = filter.provider.owner; 10056 if (p != null) { 10057 PackageSetting ps = (PackageSetting) p.mExtras; 10058 if (ps != null) { 10059 // System apps are never considered stopped for purposes of 10060 // filtering, because there may be no way for the user to 10061 // actually re-launch them. 10062 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10063 && ps.getStopped(userId); 10064 } 10065 } 10066 return false; 10067 } 10068 10069 @Override 10070 protected boolean isPackageForFilter(String packageName, 10071 PackageParser.ProviderIntentInfo info) { 10072 return packageName.equals(info.provider.owner.packageName); 10073 } 10074 10075 @Override 10076 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10077 int match, int userId) { 10078 if (!sUserManager.exists(userId)) 10079 return null; 10080 final PackageParser.ProviderIntentInfo info = filter; 10081 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10082 return null; 10083 } 10084 final PackageParser.Provider provider = info.provider; 10085 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10086 if (ps == null) { 10087 return null; 10088 } 10089 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10090 ps.readUserState(userId), userId); 10091 if (pi == null) { 10092 return null; 10093 } 10094 final ResolveInfo res = new ResolveInfo(); 10095 res.providerInfo = pi; 10096 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10097 res.filter = filter; 10098 } 10099 res.priority = info.getPriority(); 10100 res.preferredOrder = provider.owner.mPreferredOrder; 10101 res.match = match; 10102 res.isDefault = info.hasDefault; 10103 res.labelRes = info.labelRes; 10104 res.nonLocalizedLabel = info.nonLocalizedLabel; 10105 res.icon = info.icon; 10106 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10107 return res; 10108 } 10109 10110 @Override 10111 protected void sortResults(List<ResolveInfo> results) { 10112 Collections.sort(results, mResolvePrioritySorter); 10113 } 10114 10115 @Override 10116 protected void dumpFilter(PrintWriter out, String prefix, 10117 PackageParser.ProviderIntentInfo filter) { 10118 out.print(prefix); 10119 out.print( 10120 Integer.toHexString(System.identityHashCode(filter.provider))); 10121 out.print(' '); 10122 filter.provider.printComponentShortName(out); 10123 out.print(" filter "); 10124 out.println(Integer.toHexString(System.identityHashCode(filter))); 10125 } 10126 10127 @Override 10128 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10129 return filter.provider; 10130 } 10131 10132 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10133 PackageParser.Provider provider = (PackageParser.Provider)label; 10134 out.print(prefix); out.print( 10135 Integer.toHexString(System.identityHashCode(provider))); 10136 out.print(' '); 10137 provider.printComponentShortName(out); 10138 if (count > 1) { 10139 out.print(" ("); out.print(count); out.print(" filters)"); 10140 } 10141 out.println(); 10142 } 10143 10144 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10145 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10146 private int mFlags; 10147 } 10148 10149 private static final class EphemeralIntentResolver 10150 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10151 @Override 10152 protected EphemeralResolveIntentInfo[] newArray(int size) { 10153 return new EphemeralResolveIntentInfo[size]; 10154 } 10155 10156 @Override 10157 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10158 return true; 10159 } 10160 10161 @Override 10162 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10163 int userId) { 10164 if (!sUserManager.exists(userId)) { 10165 return null; 10166 } 10167 return info.getEphemeralResolveInfo(); 10168 } 10169 } 10170 10171 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10172 new Comparator<ResolveInfo>() { 10173 public int compare(ResolveInfo r1, ResolveInfo r2) { 10174 int v1 = r1.priority; 10175 int v2 = r2.priority; 10176 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10177 if (v1 != v2) { 10178 return (v1 > v2) ? -1 : 1; 10179 } 10180 v1 = r1.preferredOrder; 10181 v2 = r2.preferredOrder; 10182 if (v1 != v2) { 10183 return (v1 > v2) ? -1 : 1; 10184 } 10185 if (r1.isDefault != r2.isDefault) { 10186 return r1.isDefault ? -1 : 1; 10187 } 10188 v1 = r1.match; 10189 v2 = r2.match; 10190 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10191 if (v1 != v2) { 10192 return (v1 > v2) ? -1 : 1; 10193 } 10194 if (r1.system != r2.system) { 10195 return r1.system ? -1 : 1; 10196 } 10197 if (r1.activityInfo != null) { 10198 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10199 } 10200 if (r1.serviceInfo != null) { 10201 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10202 } 10203 if (r1.providerInfo != null) { 10204 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10205 } 10206 return 0; 10207 } 10208 }; 10209 10210 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10211 new Comparator<ProviderInfo>() { 10212 public int compare(ProviderInfo p1, ProviderInfo p2) { 10213 final int v1 = p1.initOrder; 10214 final int v2 = p2.initOrder; 10215 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10216 } 10217 }; 10218 10219 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10220 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10221 final int[] userIds) { 10222 mHandler.post(new Runnable() { 10223 @Override 10224 public void run() { 10225 try { 10226 final IActivityManager am = ActivityManagerNative.getDefault(); 10227 if (am == null) return; 10228 final int[] resolvedUserIds; 10229 if (userIds == null) { 10230 resolvedUserIds = am.getRunningUserIds(); 10231 } else { 10232 resolvedUserIds = userIds; 10233 } 10234 for (int id : resolvedUserIds) { 10235 final Intent intent = new Intent(action, 10236 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10237 if (extras != null) { 10238 intent.putExtras(extras); 10239 } 10240 if (targetPkg != null) { 10241 intent.setPackage(targetPkg); 10242 } 10243 // Modify the UID when posting to other users 10244 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10245 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10246 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10247 intent.putExtra(Intent.EXTRA_UID, uid); 10248 } 10249 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10250 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10251 if (DEBUG_BROADCASTS) { 10252 RuntimeException here = new RuntimeException("here"); 10253 here.fillInStackTrace(); 10254 Slog.d(TAG, "Sending to user " + id + ": " 10255 + intent.toShortString(false, true, false, false) 10256 + " " + intent.getExtras(), here); 10257 } 10258 am.broadcastIntent(null, intent, null, finishedReceiver, 10259 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10260 null, finishedReceiver != null, false, id); 10261 } 10262 } catch (RemoteException ex) { 10263 } 10264 } 10265 }); 10266 } 10267 10268 /** 10269 * Check if the external storage media is available. This is true if there 10270 * is a mounted external storage medium or if the external storage is 10271 * emulated. 10272 */ 10273 private boolean isExternalMediaAvailable() { 10274 return mMediaMounted || Environment.isExternalStorageEmulated(); 10275 } 10276 10277 @Override 10278 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10279 // writer 10280 synchronized (mPackages) { 10281 if (!isExternalMediaAvailable()) { 10282 // If the external storage is no longer mounted at this point, 10283 // the caller may not have been able to delete all of this 10284 // packages files and can not delete any more. Bail. 10285 return null; 10286 } 10287 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10288 if (lastPackage != null) { 10289 pkgs.remove(lastPackage); 10290 } 10291 if (pkgs.size() > 0) { 10292 return pkgs.get(0); 10293 } 10294 } 10295 return null; 10296 } 10297 10298 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10299 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10300 userId, andCode ? 1 : 0, packageName); 10301 if (mSystemReady) { 10302 msg.sendToTarget(); 10303 } else { 10304 if (mPostSystemReadyMessages == null) { 10305 mPostSystemReadyMessages = new ArrayList<>(); 10306 } 10307 mPostSystemReadyMessages.add(msg); 10308 } 10309 } 10310 10311 void startCleaningPackages() { 10312 // reader 10313 synchronized (mPackages) { 10314 if (!isExternalMediaAvailable()) { 10315 return; 10316 } 10317 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10318 return; 10319 } 10320 } 10321 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10322 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10323 IActivityManager am = ActivityManagerNative.getDefault(); 10324 if (am != null) { 10325 try { 10326 am.startService(null, intent, null, mContext.getOpPackageName(), 10327 UserHandle.USER_SYSTEM); 10328 } catch (RemoteException e) { 10329 } 10330 } 10331 } 10332 10333 @Override 10334 public void installPackage(String originPath, IPackageInstallObserver2 observer, 10335 int installFlags, String installerPackageName, VerificationParams verificationParams, 10336 String packageAbiOverride) { 10337 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 10338 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 10339 } 10340 10341 @Override 10342 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10343 int installFlags, String installerPackageName, VerificationParams verificationParams, 10344 String packageAbiOverride, int userId) { 10345 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10346 10347 final int callingUid = Binder.getCallingUid(); 10348 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 10349 10350 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10351 try { 10352 if (observer != null) { 10353 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10354 } 10355 } catch (RemoteException re) { 10356 } 10357 return; 10358 } 10359 10360 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10361 installFlags |= PackageManager.INSTALL_FROM_ADB; 10362 10363 } else { 10364 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10365 // about installerPackageName. 10366 10367 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10368 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10369 } 10370 10371 UserHandle user; 10372 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10373 user = UserHandle.ALL; 10374 } else { 10375 user = new UserHandle(userId); 10376 } 10377 10378 // Only system components can circumvent runtime permissions when installing. 10379 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10380 && mContext.checkCallingOrSelfPermission(Manifest.permission 10381 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10382 throw new SecurityException("You need the " 10383 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10384 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10385 } 10386 10387 verificationParams.setInstallerUid(callingUid); 10388 10389 final File originFile = new File(originPath); 10390 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10391 10392 final Message msg = mHandler.obtainMessage(INIT_COPY); 10393 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 10394 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 10395 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10396 msg.obj = params; 10397 10398 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10399 System.identityHashCode(msg.obj)); 10400 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10401 System.identityHashCode(msg.obj)); 10402 10403 mHandler.sendMessage(msg); 10404 } 10405 10406 void installStage(String packageName, File stagedDir, String stagedCid, 10407 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10408 String installerPackageName, int installerUid, UserHandle user) { 10409 if (DEBUG_EPHEMERAL) { 10410 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10411 Slog.d(TAG, "Ephemeral install of " + packageName); 10412 } 10413 } 10414 final VerificationParams verifParams = new VerificationParams( 10415 null, sessionParams.originatingUri, sessionParams.referrerUri, 10416 sessionParams.originatingUid); 10417 verifParams.setInstallerUid(installerUid); 10418 10419 final OriginInfo origin; 10420 if (stagedDir != null) { 10421 origin = OriginInfo.fromStagedFile(stagedDir); 10422 } else { 10423 origin = OriginInfo.fromStagedContainer(stagedCid); 10424 } 10425 10426 final Message msg = mHandler.obtainMessage(INIT_COPY); 10427 final InstallParams params = new InstallParams(origin, null, observer, 10428 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10429 verifParams, user, sessionParams.abiOverride, 10430 sessionParams.grantedRuntimePermissions); 10431 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10432 msg.obj = params; 10433 10434 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10435 System.identityHashCode(msg.obj)); 10436 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10437 System.identityHashCode(msg.obj)); 10438 10439 mHandler.sendMessage(msg); 10440 } 10441 10442 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 10443 Bundle extras = new Bundle(1); 10444 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 10445 10446 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10447 packageName, extras, 0, null, null, new int[] {userId}); 10448 try { 10449 IActivityManager am = ActivityManagerNative.getDefault(); 10450 final boolean isSystem = 10451 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10452 if (isSystem && am.isUserRunning(userId, 0)) { 10453 // The just-installed/enabled app is bundled on the system, so presumed 10454 // to be able to run automatically without needing an explicit launch. 10455 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10456 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10457 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10458 .setPackage(packageName); 10459 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10460 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10461 } 10462 } catch (RemoteException e) { 10463 // shouldn't happen 10464 Slog.w(TAG, "Unable to bootstrap installed package", e); 10465 } 10466 } 10467 10468 @Override 10469 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10470 int userId) { 10471 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10472 PackageSetting pkgSetting; 10473 final int uid = Binder.getCallingUid(); 10474 enforceCrossUserPermission(uid, userId, true, true, 10475 "setApplicationHiddenSetting for user " + userId); 10476 10477 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10478 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10479 return false; 10480 } 10481 10482 long callingId = Binder.clearCallingIdentity(); 10483 try { 10484 boolean sendAdded = false; 10485 boolean sendRemoved = false; 10486 // writer 10487 synchronized (mPackages) { 10488 pkgSetting = mSettings.mPackages.get(packageName); 10489 if (pkgSetting == null) { 10490 return false; 10491 } 10492 if (pkgSetting.getHidden(userId) != hidden) { 10493 pkgSetting.setHidden(hidden, userId); 10494 mSettings.writePackageRestrictionsLPr(userId); 10495 if (hidden) { 10496 sendRemoved = true; 10497 } else { 10498 sendAdded = true; 10499 } 10500 } 10501 } 10502 if (sendAdded) { 10503 sendPackageAddedForUser(packageName, pkgSetting, userId); 10504 return true; 10505 } 10506 if (sendRemoved) { 10507 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10508 "hiding pkg"); 10509 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10510 return true; 10511 } 10512 } finally { 10513 Binder.restoreCallingIdentity(callingId); 10514 } 10515 return false; 10516 } 10517 10518 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10519 int userId) { 10520 final PackageRemovedInfo info = new PackageRemovedInfo(); 10521 info.removedPackage = packageName; 10522 info.removedUsers = new int[] {userId}; 10523 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10524 info.sendBroadcast(false, false, false); 10525 } 10526 10527 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10528 if (pkgList.length > 0) { 10529 Bundle extras = new Bundle(1); 10530 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10531 10532 sendPackageBroadcast( 10533 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10534 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10535 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10536 new int[] {userId}); 10537 } 10538 } 10539 10540 /** 10541 * Returns true if application is not found or there was an error. Otherwise it returns 10542 * the hidden state of the package for the given user. 10543 */ 10544 @Override 10545 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10546 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10547 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10548 false, "getApplicationHidden for user " + userId); 10549 PackageSetting pkgSetting; 10550 long callingId = Binder.clearCallingIdentity(); 10551 try { 10552 // writer 10553 synchronized (mPackages) { 10554 pkgSetting = mSettings.mPackages.get(packageName); 10555 if (pkgSetting == null) { 10556 return true; 10557 } 10558 return pkgSetting.getHidden(userId); 10559 } 10560 } finally { 10561 Binder.restoreCallingIdentity(callingId); 10562 } 10563 } 10564 10565 /** 10566 * @hide 10567 */ 10568 @Override 10569 public int installExistingPackageAsUser(String packageName, int userId) { 10570 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10571 null); 10572 PackageSetting pkgSetting; 10573 final int uid = Binder.getCallingUid(); 10574 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10575 + userId); 10576 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10577 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10578 } 10579 10580 long callingId = Binder.clearCallingIdentity(); 10581 try { 10582 boolean installed = false; 10583 10584 // writer 10585 synchronized (mPackages) { 10586 pkgSetting = mSettings.mPackages.get(packageName); 10587 if (pkgSetting == null) { 10588 return PackageManager.INSTALL_FAILED_INVALID_URI; 10589 } 10590 if (!pkgSetting.getInstalled(userId)) { 10591 pkgSetting.setInstalled(true, userId); 10592 pkgSetting.setHidden(false, userId); 10593 mSettings.writePackageRestrictionsLPr(userId); 10594 if (pkgSetting.pkg != null) { 10595 prepareAppDataAfterInstall(pkgSetting.pkg); 10596 } 10597 installed = true; 10598 } 10599 } 10600 10601 if (installed) { 10602 sendPackageAddedForUser(packageName, pkgSetting, userId); 10603 } 10604 } finally { 10605 Binder.restoreCallingIdentity(callingId); 10606 } 10607 10608 return PackageManager.INSTALL_SUCCEEDED; 10609 } 10610 10611 boolean isUserRestricted(int userId, String restrictionKey) { 10612 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10613 if (restrictions.getBoolean(restrictionKey, false)) { 10614 Log.w(TAG, "User is restricted: " + restrictionKey); 10615 return true; 10616 } 10617 return false; 10618 } 10619 10620 @Override 10621 public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) { 10622 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10623 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true, 10624 "setPackageSuspended for user " + userId); 10625 10626 // TODO: investigate and add more restrictions for suspending crucial packages. 10627 if (isPackageDeviceAdmin(packageName, userId)) { 10628 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10629 + "\": has active device admin"); 10630 return false; 10631 } 10632 10633 long callingId = Binder.clearCallingIdentity(); 10634 try { 10635 boolean changed = false; 10636 boolean success = false; 10637 int appId = -1; 10638 synchronized (mPackages) { 10639 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10640 if (pkgSetting != null) { 10641 if (pkgSetting.getSuspended(userId) != suspended) { 10642 pkgSetting.setSuspended(suspended, userId); 10643 mSettings.writePackageRestrictionsLPr(userId); 10644 appId = pkgSetting.appId; 10645 changed = true; 10646 } 10647 success = true; 10648 } 10649 } 10650 10651 if (changed) { 10652 sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended); 10653 if (suspended) { 10654 killApplication(packageName, UserHandle.getUid(userId, appId), 10655 "suspending package"); 10656 } 10657 } 10658 return success; 10659 } finally { 10660 Binder.restoreCallingIdentity(callingId); 10661 } 10662 } 10663 10664 @Override 10665 public boolean isPackageSuspendedForUser(String packageName, int userId) { 10666 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10667 false, "isPackageSuspendedForUser for user " + userId); 10668 synchronized (mPackages) { 10669 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10670 return pkgSetting != null && pkgSetting.getSuspended(userId); 10671 } 10672 } 10673 10674 @Override 10675 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10676 mContext.enforceCallingOrSelfPermission( 10677 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10678 "Only package verification agents can verify applications"); 10679 10680 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10681 final PackageVerificationResponse response = new PackageVerificationResponse( 10682 verificationCode, Binder.getCallingUid()); 10683 msg.arg1 = id; 10684 msg.obj = response; 10685 mHandler.sendMessage(msg); 10686 } 10687 10688 @Override 10689 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10690 long millisecondsToDelay) { 10691 mContext.enforceCallingOrSelfPermission( 10692 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10693 "Only package verification agents can extend verification timeouts"); 10694 10695 final PackageVerificationState state = mPendingVerification.get(id); 10696 final PackageVerificationResponse response = new PackageVerificationResponse( 10697 verificationCodeAtTimeout, Binder.getCallingUid()); 10698 10699 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10700 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10701 } 10702 if (millisecondsToDelay < 0) { 10703 millisecondsToDelay = 0; 10704 } 10705 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10706 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10707 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10708 } 10709 10710 if ((state != null) && !state.timeoutExtended()) { 10711 state.extendTimeout(); 10712 10713 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10714 msg.arg1 = id; 10715 msg.obj = response; 10716 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10717 } 10718 } 10719 10720 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10721 int verificationCode, UserHandle user) { 10722 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10723 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10724 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10725 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10726 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10727 10728 mContext.sendBroadcastAsUser(intent, user, 10729 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10730 } 10731 10732 private ComponentName matchComponentForVerifier(String packageName, 10733 List<ResolveInfo> receivers) { 10734 ActivityInfo targetReceiver = null; 10735 10736 final int NR = receivers.size(); 10737 for (int i = 0; i < NR; i++) { 10738 final ResolveInfo info = receivers.get(i); 10739 if (info.activityInfo == null) { 10740 continue; 10741 } 10742 10743 if (packageName.equals(info.activityInfo.packageName)) { 10744 targetReceiver = info.activityInfo; 10745 break; 10746 } 10747 } 10748 10749 if (targetReceiver == null) { 10750 return null; 10751 } 10752 10753 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10754 } 10755 10756 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10757 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10758 if (pkgInfo.verifiers.length == 0) { 10759 return null; 10760 } 10761 10762 final int N = pkgInfo.verifiers.length; 10763 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10764 for (int i = 0; i < N; i++) { 10765 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10766 10767 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10768 receivers); 10769 if (comp == null) { 10770 continue; 10771 } 10772 10773 final int verifierUid = getUidForVerifier(verifierInfo); 10774 if (verifierUid == -1) { 10775 continue; 10776 } 10777 10778 if (DEBUG_VERIFY) { 10779 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10780 + " with the correct signature"); 10781 } 10782 sufficientVerifiers.add(comp); 10783 verificationState.addSufficientVerifier(verifierUid); 10784 } 10785 10786 return sufficientVerifiers; 10787 } 10788 10789 private int getUidForVerifier(VerifierInfo verifierInfo) { 10790 synchronized (mPackages) { 10791 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10792 if (pkg == null) { 10793 return -1; 10794 } else if (pkg.mSignatures.length != 1) { 10795 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10796 + " has more than one signature; ignoring"); 10797 return -1; 10798 } 10799 10800 /* 10801 * If the public key of the package's signature does not match 10802 * our expected public key, then this is a different package and 10803 * we should skip. 10804 */ 10805 10806 final byte[] expectedPublicKey; 10807 try { 10808 final Signature verifierSig = pkg.mSignatures[0]; 10809 final PublicKey publicKey = verifierSig.getPublicKey(); 10810 expectedPublicKey = publicKey.getEncoded(); 10811 } catch (CertificateException e) { 10812 return -1; 10813 } 10814 10815 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10816 10817 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10818 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10819 + " does not have the expected public key; ignoring"); 10820 return -1; 10821 } 10822 10823 return pkg.applicationInfo.uid; 10824 } 10825 } 10826 10827 @Override 10828 public void finishPackageInstall(int token) { 10829 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10830 10831 if (DEBUG_INSTALL) { 10832 Slog.v(TAG, "BM finishing package install for " + token); 10833 } 10834 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10835 10836 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10837 mHandler.sendMessage(msg); 10838 } 10839 10840 /** 10841 * Get the verification agent timeout. 10842 * 10843 * @return verification timeout in milliseconds 10844 */ 10845 private long getVerificationTimeout() { 10846 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10847 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10848 DEFAULT_VERIFICATION_TIMEOUT); 10849 } 10850 10851 /** 10852 * Get the default verification agent response code. 10853 * 10854 * @return default verification response code 10855 */ 10856 private int getDefaultVerificationResponse() { 10857 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10858 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10859 DEFAULT_VERIFICATION_RESPONSE); 10860 } 10861 10862 /** 10863 * Check whether or not package verification has been enabled. 10864 * 10865 * @return true if verification should be performed 10866 */ 10867 private boolean isVerificationEnabled(int userId, int installFlags) { 10868 if (!DEFAULT_VERIFY_ENABLE) { 10869 return false; 10870 } 10871 // Ephemeral apps don't get the full verification treatment 10872 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10873 if (DEBUG_EPHEMERAL) { 10874 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10875 } 10876 return false; 10877 } 10878 10879 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10880 10881 // Check if installing from ADB 10882 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10883 // Do not run verification in a test harness environment 10884 if (ActivityManager.isRunningInTestHarness()) { 10885 return false; 10886 } 10887 if (ensureVerifyAppsEnabled) { 10888 return true; 10889 } 10890 // Check if the developer does not want package verification for ADB installs 10891 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10892 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10893 return false; 10894 } 10895 } 10896 10897 if (ensureVerifyAppsEnabled) { 10898 return true; 10899 } 10900 10901 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10902 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10903 } 10904 10905 @Override 10906 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10907 throws RemoteException { 10908 mContext.enforceCallingOrSelfPermission( 10909 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10910 "Only intentfilter verification agents can verify applications"); 10911 10912 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10913 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10914 Binder.getCallingUid(), verificationCode, failedDomains); 10915 msg.arg1 = id; 10916 msg.obj = response; 10917 mHandler.sendMessage(msg); 10918 } 10919 10920 @Override 10921 public int getIntentVerificationStatus(String packageName, int userId) { 10922 synchronized (mPackages) { 10923 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10924 } 10925 } 10926 10927 @Override 10928 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10929 mContext.enforceCallingOrSelfPermission( 10930 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10931 10932 boolean result = false; 10933 synchronized (mPackages) { 10934 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10935 } 10936 if (result) { 10937 scheduleWritePackageRestrictionsLocked(userId); 10938 } 10939 return result; 10940 } 10941 10942 @Override 10943 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10944 synchronized (mPackages) { 10945 return mSettings.getIntentFilterVerificationsLPr(packageName); 10946 } 10947 } 10948 10949 @Override 10950 public List<IntentFilter> getAllIntentFilters(String packageName) { 10951 if (TextUtils.isEmpty(packageName)) { 10952 return Collections.<IntentFilter>emptyList(); 10953 } 10954 synchronized (mPackages) { 10955 PackageParser.Package pkg = mPackages.get(packageName); 10956 if (pkg == null || pkg.activities == null) { 10957 return Collections.<IntentFilter>emptyList(); 10958 } 10959 final int count = pkg.activities.size(); 10960 ArrayList<IntentFilter> result = new ArrayList<>(); 10961 for (int n=0; n<count; n++) { 10962 PackageParser.Activity activity = pkg.activities.get(n); 10963 if (activity.intents != null && activity.intents.size() > 0) { 10964 result.addAll(activity.intents); 10965 } 10966 } 10967 return result; 10968 } 10969 } 10970 10971 @Override 10972 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10973 mContext.enforceCallingOrSelfPermission( 10974 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10975 10976 synchronized (mPackages) { 10977 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10978 if (packageName != null) { 10979 result |= updateIntentVerificationStatus(packageName, 10980 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10981 userId); 10982 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10983 packageName, userId); 10984 } 10985 return result; 10986 } 10987 } 10988 10989 @Override 10990 public String getDefaultBrowserPackageName(int userId) { 10991 synchronized (mPackages) { 10992 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10993 } 10994 } 10995 10996 /** 10997 * Get the "allow unknown sources" setting. 10998 * 10999 * @return the current "allow unknown sources" setting 11000 */ 11001 private int getUnknownSourcesSettings() { 11002 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11003 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 11004 -1); 11005 } 11006 11007 @Override 11008 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11009 final int uid = Binder.getCallingUid(); 11010 // writer 11011 synchronized (mPackages) { 11012 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11013 if (targetPackageSetting == null) { 11014 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11015 } 11016 11017 PackageSetting installerPackageSetting; 11018 if (installerPackageName != null) { 11019 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11020 if (installerPackageSetting == null) { 11021 throw new IllegalArgumentException("Unknown installer package: " 11022 + installerPackageName); 11023 } 11024 } else { 11025 installerPackageSetting = null; 11026 } 11027 11028 Signature[] callerSignature; 11029 Object obj = mSettings.getUserIdLPr(uid); 11030 if (obj != null) { 11031 if (obj instanceof SharedUserSetting) { 11032 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11033 } else if (obj instanceof PackageSetting) { 11034 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11035 } else { 11036 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11037 } 11038 } else { 11039 throw new SecurityException("Unknown calling UID: " + uid); 11040 } 11041 11042 // Verify: can't set installerPackageName to a package that is 11043 // not signed with the same cert as the caller. 11044 if (installerPackageSetting != null) { 11045 if (compareSignatures(callerSignature, 11046 installerPackageSetting.signatures.mSignatures) 11047 != PackageManager.SIGNATURE_MATCH) { 11048 throw new SecurityException( 11049 "Caller does not have same cert as new installer package " 11050 + installerPackageName); 11051 } 11052 } 11053 11054 // Verify: if target already has an installer package, it must 11055 // be signed with the same cert as the caller. 11056 if (targetPackageSetting.installerPackageName != null) { 11057 PackageSetting setting = mSettings.mPackages.get( 11058 targetPackageSetting.installerPackageName); 11059 // If the currently set package isn't valid, then it's always 11060 // okay to change it. 11061 if (setting != null) { 11062 if (compareSignatures(callerSignature, 11063 setting.signatures.mSignatures) 11064 != PackageManager.SIGNATURE_MATCH) { 11065 throw new SecurityException( 11066 "Caller does not have same cert as old installer package " 11067 + targetPackageSetting.installerPackageName); 11068 } 11069 } 11070 } 11071 11072 // Okay! 11073 targetPackageSetting.installerPackageName = installerPackageName; 11074 scheduleWriteSettingsLocked(); 11075 } 11076 } 11077 11078 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11079 // Queue up an async operation since the package installation may take a little while. 11080 mHandler.post(new Runnable() { 11081 public void run() { 11082 mHandler.removeCallbacks(this); 11083 // Result object to be returned 11084 PackageInstalledInfo res = new PackageInstalledInfo(); 11085 res.returnCode = currentStatus; 11086 res.uid = -1; 11087 res.pkg = null; 11088 res.removedInfo = new PackageRemovedInfo(); 11089 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11090 args.doPreInstall(res.returnCode); 11091 synchronized (mInstallLock) { 11092 installPackageTracedLI(args, res); 11093 } 11094 args.doPostInstall(res.returnCode, res.uid); 11095 } 11096 11097 // A restore should be performed at this point if (a) the install 11098 // succeeded, (b) the operation is not an update, and (c) the new 11099 // package has not opted out of backup participation. 11100 final boolean update = res.removedInfo.removedPackage != null; 11101 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11102 boolean doRestore = !update 11103 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11104 11105 // Set up the post-install work request bookkeeping. This will be used 11106 // and cleaned up by the post-install event handling regardless of whether 11107 // there's a restore pass performed. Token values are >= 1. 11108 int token; 11109 if (mNextInstallToken < 0) mNextInstallToken = 1; 11110 token = mNextInstallToken++; 11111 11112 PostInstallData data = new PostInstallData(args, res); 11113 mRunningInstalls.put(token, data); 11114 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11115 11116 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11117 // Pass responsibility to the Backup Manager. It will perform a 11118 // restore if appropriate, then pass responsibility back to the 11119 // Package Manager to run the post-install observer callbacks 11120 // and broadcasts. 11121 IBackupManager bm = IBackupManager.Stub.asInterface( 11122 ServiceManager.getService(Context.BACKUP_SERVICE)); 11123 if (bm != null) { 11124 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11125 + " to BM for possible restore"); 11126 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11127 try { 11128 // TODO: http://b/22388012 11129 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11130 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11131 } else { 11132 doRestore = false; 11133 } 11134 } catch (RemoteException e) { 11135 // can't happen; the backup manager is local 11136 } catch (Exception e) { 11137 Slog.e(TAG, "Exception trying to enqueue restore", e); 11138 doRestore = false; 11139 } 11140 } else { 11141 Slog.e(TAG, "Backup Manager not found!"); 11142 doRestore = false; 11143 } 11144 } 11145 11146 if (!doRestore) { 11147 // No restore possible, or the Backup Manager was mysteriously not 11148 // available -- just fire the post-install work request directly. 11149 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11150 11151 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11152 11153 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11154 mHandler.sendMessage(msg); 11155 } 11156 } 11157 }); 11158 } 11159 11160 private abstract class HandlerParams { 11161 private static final int MAX_RETRIES = 4; 11162 11163 /** 11164 * Number of times startCopy() has been attempted and had a non-fatal 11165 * error. 11166 */ 11167 private int mRetries = 0; 11168 11169 /** User handle for the user requesting the information or installation. */ 11170 private final UserHandle mUser; 11171 String traceMethod; 11172 int traceCookie; 11173 11174 HandlerParams(UserHandle user) { 11175 mUser = user; 11176 } 11177 11178 UserHandle getUser() { 11179 return mUser; 11180 } 11181 11182 HandlerParams setTraceMethod(String traceMethod) { 11183 this.traceMethod = traceMethod; 11184 return this; 11185 } 11186 11187 HandlerParams setTraceCookie(int traceCookie) { 11188 this.traceCookie = traceCookie; 11189 return this; 11190 } 11191 11192 final boolean startCopy() { 11193 boolean res; 11194 try { 11195 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11196 11197 if (++mRetries > MAX_RETRIES) { 11198 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11199 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11200 handleServiceError(); 11201 return false; 11202 } else { 11203 handleStartCopy(); 11204 res = true; 11205 } 11206 } catch (RemoteException e) { 11207 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11208 mHandler.sendEmptyMessage(MCS_RECONNECT); 11209 res = false; 11210 } 11211 handleReturnCode(); 11212 return res; 11213 } 11214 11215 final void serviceError() { 11216 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11217 handleServiceError(); 11218 handleReturnCode(); 11219 } 11220 11221 abstract void handleStartCopy() throws RemoteException; 11222 abstract void handleServiceError(); 11223 abstract void handleReturnCode(); 11224 } 11225 11226 class MeasureParams extends HandlerParams { 11227 private final PackageStats mStats; 11228 private boolean mSuccess; 11229 11230 private final IPackageStatsObserver mObserver; 11231 11232 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11233 super(new UserHandle(stats.userHandle)); 11234 mObserver = observer; 11235 mStats = stats; 11236 } 11237 11238 @Override 11239 public String toString() { 11240 return "MeasureParams{" 11241 + Integer.toHexString(System.identityHashCode(this)) 11242 + " " + mStats.packageName + "}"; 11243 } 11244 11245 @Override 11246 void handleStartCopy() throws RemoteException { 11247 synchronized (mInstallLock) { 11248 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11249 } 11250 11251 if (mSuccess) { 11252 final boolean mounted; 11253 if (Environment.isExternalStorageEmulated()) { 11254 mounted = true; 11255 } else { 11256 final String status = Environment.getExternalStorageState(); 11257 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11258 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11259 } 11260 11261 if (mounted) { 11262 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11263 11264 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11265 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11266 11267 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11268 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11269 11270 // Always subtract cache size, since it's a subdirectory 11271 mStats.externalDataSize -= mStats.externalCacheSize; 11272 11273 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11274 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11275 11276 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11277 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11278 } 11279 } 11280 } 11281 11282 @Override 11283 void handleReturnCode() { 11284 if (mObserver != null) { 11285 try { 11286 mObserver.onGetStatsCompleted(mStats, mSuccess); 11287 } catch (RemoteException e) { 11288 Slog.i(TAG, "Observer no longer exists."); 11289 } 11290 } 11291 } 11292 11293 @Override 11294 void handleServiceError() { 11295 Slog.e(TAG, "Could not measure application " + mStats.packageName 11296 + " external storage"); 11297 } 11298 } 11299 11300 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11301 throws RemoteException { 11302 long result = 0; 11303 for (File path : paths) { 11304 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11305 } 11306 return result; 11307 } 11308 11309 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11310 for (File path : paths) { 11311 try { 11312 mcs.clearDirectory(path.getAbsolutePath()); 11313 } catch (RemoteException e) { 11314 } 11315 } 11316 } 11317 11318 static class OriginInfo { 11319 /** 11320 * Location where install is coming from, before it has been 11321 * copied/renamed into place. This could be a single monolithic APK 11322 * file, or a cluster directory. This location may be untrusted. 11323 */ 11324 final File file; 11325 final String cid; 11326 11327 /** 11328 * Flag indicating that {@link #file} or {@link #cid} has already been 11329 * staged, meaning downstream users don't need to defensively copy the 11330 * contents. 11331 */ 11332 final boolean staged; 11333 11334 /** 11335 * Flag indicating that {@link #file} or {@link #cid} is an already 11336 * installed app that is being moved. 11337 */ 11338 final boolean existing; 11339 11340 final String resolvedPath; 11341 final File resolvedFile; 11342 11343 static OriginInfo fromNothing() { 11344 return new OriginInfo(null, null, false, false); 11345 } 11346 11347 static OriginInfo fromUntrustedFile(File file) { 11348 return new OriginInfo(file, null, false, false); 11349 } 11350 11351 static OriginInfo fromExistingFile(File file) { 11352 return new OriginInfo(file, null, false, true); 11353 } 11354 11355 static OriginInfo fromStagedFile(File file) { 11356 return new OriginInfo(file, null, true, false); 11357 } 11358 11359 static OriginInfo fromStagedContainer(String cid) { 11360 return new OriginInfo(null, cid, true, false); 11361 } 11362 11363 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 11364 this.file = file; 11365 this.cid = cid; 11366 this.staged = staged; 11367 this.existing = existing; 11368 11369 if (cid != null) { 11370 resolvedPath = PackageHelper.getSdDir(cid); 11371 resolvedFile = new File(resolvedPath); 11372 } else if (file != null) { 11373 resolvedPath = file.getAbsolutePath(); 11374 resolvedFile = file; 11375 } else { 11376 resolvedPath = null; 11377 resolvedFile = null; 11378 } 11379 } 11380 } 11381 11382 static class MoveInfo { 11383 final int moveId; 11384 final String fromUuid; 11385 final String toUuid; 11386 final String packageName; 11387 final String dataAppName; 11388 final int appId; 11389 final String seinfo; 11390 final int targetSdkVersion; 11391 11392 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 11393 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 11394 this.moveId = moveId; 11395 this.fromUuid = fromUuid; 11396 this.toUuid = toUuid; 11397 this.packageName = packageName; 11398 this.dataAppName = dataAppName; 11399 this.appId = appId; 11400 this.seinfo = seinfo; 11401 this.targetSdkVersion = targetSdkVersion; 11402 } 11403 } 11404 11405 class InstallParams extends HandlerParams { 11406 final OriginInfo origin; 11407 final MoveInfo move; 11408 final IPackageInstallObserver2 observer; 11409 int installFlags; 11410 final String installerPackageName; 11411 final String volumeUuid; 11412 final VerificationParams verificationParams; 11413 private InstallArgs mArgs; 11414 private int mRet; 11415 final String packageAbiOverride; 11416 final String[] grantedRuntimePermissions; 11417 11418 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11419 int installFlags, String installerPackageName, String volumeUuid, 11420 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 11421 String[] grantedPermissions) { 11422 super(user); 11423 this.origin = origin; 11424 this.move = move; 11425 this.observer = observer; 11426 this.installFlags = installFlags; 11427 this.installerPackageName = installerPackageName; 11428 this.volumeUuid = volumeUuid; 11429 this.verificationParams = verificationParams; 11430 this.packageAbiOverride = packageAbiOverride; 11431 this.grantedRuntimePermissions = grantedPermissions; 11432 } 11433 11434 @Override 11435 public String toString() { 11436 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11437 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11438 } 11439 11440 private int installLocationPolicy(PackageInfoLite pkgLite) { 11441 String packageName = pkgLite.packageName; 11442 int installLocation = pkgLite.installLocation; 11443 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11444 // reader 11445 synchronized (mPackages) { 11446 PackageParser.Package pkg = mPackages.get(packageName); 11447 if (pkg != null) { 11448 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11449 // Check for downgrading. 11450 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 11451 try { 11452 checkDowngrade(pkg, pkgLite); 11453 } catch (PackageManagerException e) { 11454 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11455 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11456 } 11457 } 11458 // Check for updated system application. 11459 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11460 if (onSd) { 11461 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11462 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11463 } 11464 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11465 } else { 11466 if (onSd) { 11467 // Install flag overrides everything. 11468 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11469 } 11470 // If current upgrade specifies particular preference 11471 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11472 // Application explicitly specified internal. 11473 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11474 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11475 // App explictly prefers external. Let policy decide 11476 } else { 11477 // Prefer previous location 11478 if (isExternal(pkg)) { 11479 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11480 } 11481 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11482 } 11483 } 11484 } else { 11485 // Invalid install. Return error code 11486 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11487 } 11488 } 11489 } 11490 // All the special cases have been taken care of. 11491 // Return result based on recommended install location. 11492 if (onSd) { 11493 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11494 } 11495 return pkgLite.recommendedInstallLocation; 11496 } 11497 11498 /* 11499 * Invoke remote method to get package information and install 11500 * location values. Override install location based on default 11501 * policy if needed and then create install arguments based 11502 * on the install location. 11503 */ 11504 public void handleStartCopy() throws RemoteException { 11505 int ret = PackageManager.INSTALL_SUCCEEDED; 11506 11507 // If we're already staged, we've firmly committed to an install location 11508 if (origin.staged) { 11509 if (origin.file != null) { 11510 installFlags |= PackageManager.INSTALL_INTERNAL; 11511 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11512 } else if (origin.cid != null) { 11513 installFlags |= PackageManager.INSTALL_EXTERNAL; 11514 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11515 } else { 11516 throw new IllegalStateException("Invalid stage location"); 11517 } 11518 } 11519 11520 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11521 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11522 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11523 PackageInfoLite pkgLite = null; 11524 11525 if (onInt && onSd) { 11526 // Check if both bits are set. 11527 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11528 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11529 } else if (onSd && ephemeral) { 11530 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11531 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11532 } else { 11533 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11534 packageAbiOverride); 11535 11536 if (DEBUG_EPHEMERAL && ephemeral) { 11537 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11538 } 11539 11540 /* 11541 * If we have too little free space, try to free cache 11542 * before giving up. 11543 */ 11544 if (!origin.staged && pkgLite.recommendedInstallLocation 11545 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11546 // TODO: focus freeing disk space on the target device 11547 final StorageManager storage = StorageManager.from(mContext); 11548 final long lowThreshold = storage.getStorageLowBytes( 11549 Environment.getDataDirectory()); 11550 11551 final long sizeBytes = mContainerService.calculateInstalledSize( 11552 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11553 11554 try { 11555 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11556 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11557 installFlags, packageAbiOverride); 11558 } catch (InstallerException e) { 11559 Slog.w(TAG, "Failed to free cache", e); 11560 } 11561 11562 /* 11563 * The cache free must have deleted the file we 11564 * downloaded to install. 11565 * 11566 * TODO: fix the "freeCache" call to not delete 11567 * the file we care about. 11568 */ 11569 if (pkgLite.recommendedInstallLocation 11570 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11571 pkgLite.recommendedInstallLocation 11572 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11573 } 11574 } 11575 } 11576 11577 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11578 int loc = pkgLite.recommendedInstallLocation; 11579 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11580 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11581 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11582 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11583 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11584 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11585 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11586 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11587 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11588 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11589 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11590 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11591 } else { 11592 // Override with defaults if needed. 11593 loc = installLocationPolicy(pkgLite); 11594 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11595 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11596 } else if (!onSd && !onInt) { 11597 // Override install location with flags 11598 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11599 // Set the flag to install on external media. 11600 installFlags |= PackageManager.INSTALL_EXTERNAL; 11601 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11602 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11603 if (DEBUG_EPHEMERAL) { 11604 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11605 } 11606 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11607 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11608 |PackageManager.INSTALL_INTERNAL); 11609 } else { 11610 // Make sure the flag for installing on external 11611 // media is unset 11612 installFlags |= PackageManager.INSTALL_INTERNAL; 11613 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11614 } 11615 } 11616 } 11617 } 11618 11619 final InstallArgs args = createInstallArgs(this); 11620 mArgs = args; 11621 11622 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11623 // TODO: http://b/22976637 11624 // Apps installed for "all" users use the device owner to verify the app 11625 UserHandle verifierUser = getUser(); 11626 if (verifierUser == UserHandle.ALL) { 11627 verifierUser = UserHandle.SYSTEM; 11628 } 11629 11630 /* 11631 * Determine if we have any installed package verifiers. If we 11632 * do, then we'll defer to them to verify the packages. 11633 */ 11634 final int requiredUid = mRequiredVerifierPackage == null ? -1 11635 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11636 verifierUser.getIdentifier()); 11637 if (!origin.existing && requiredUid != -1 11638 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11639 final Intent verification = new Intent( 11640 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11641 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11642 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11643 PACKAGE_MIME_TYPE); 11644 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11645 11646 // Query all live verifiers based on current user state 11647 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11648 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11649 11650 if (DEBUG_VERIFY) { 11651 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11652 + verification.toString() + " with " + pkgLite.verifiers.length 11653 + " optional verifiers"); 11654 } 11655 11656 final int verificationId = mPendingVerificationToken++; 11657 11658 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11659 11660 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11661 installerPackageName); 11662 11663 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11664 installFlags); 11665 11666 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11667 pkgLite.packageName); 11668 11669 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11670 pkgLite.versionCode); 11671 11672 if (verificationParams != null) { 11673 if (verificationParams.getVerificationURI() != null) { 11674 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11675 verificationParams.getVerificationURI()); 11676 } 11677 if (verificationParams.getOriginatingURI() != null) { 11678 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11679 verificationParams.getOriginatingURI()); 11680 } 11681 if (verificationParams.getReferrer() != null) { 11682 verification.putExtra(Intent.EXTRA_REFERRER, 11683 verificationParams.getReferrer()); 11684 } 11685 if (verificationParams.getOriginatingUid() >= 0) { 11686 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11687 verificationParams.getOriginatingUid()); 11688 } 11689 if (verificationParams.getInstallerUid() >= 0) { 11690 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11691 verificationParams.getInstallerUid()); 11692 } 11693 } 11694 11695 final PackageVerificationState verificationState = new PackageVerificationState( 11696 requiredUid, args); 11697 11698 mPendingVerification.append(verificationId, verificationState); 11699 11700 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11701 receivers, verificationState); 11702 11703 /* 11704 * If any sufficient verifiers were listed in the package 11705 * manifest, attempt to ask them. 11706 */ 11707 if (sufficientVerifiers != null) { 11708 final int N = sufficientVerifiers.size(); 11709 if (N == 0) { 11710 Slog.i(TAG, "Additional verifiers required, but none installed."); 11711 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11712 } else { 11713 for (int i = 0; i < N; i++) { 11714 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11715 11716 final Intent sufficientIntent = new Intent(verification); 11717 sufficientIntent.setComponent(verifierComponent); 11718 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11719 } 11720 } 11721 } 11722 11723 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11724 mRequiredVerifierPackage, receivers); 11725 if (ret == PackageManager.INSTALL_SUCCEEDED 11726 && mRequiredVerifierPackage != null) { 11727 Trace.asyncTraceBegin( 11728 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11729 /* 11730 * Send the intent to the required verification agent, 11731 * but only start the verification timeout after the 11732 * target BroadcastReceivers have run. 11733 */ 11734 verification.setComponent(requiredVerifierComponent); 11735 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11736 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11737 new BroadcastReceiver() { 11738 @Override 11739 public void onReceive(Context context, Intent intent) { 11740 final Message msg = mHandler 11741 .obtainMessage(CHECK_PENDING_VERIFICATION); 11742 msg.arg1 = verificationId; 11743 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11744 } 11745 }, null, 0, null, null); 11746 11747 /* 11748 * We don't want the copy to proceed until verification 11749 * succeeds, so null out this field. 11750 */ 11751 mArgs = null; 11752 } 11753 } else { 11754 /* 11755 * No package verification is enabled, so immediately start 11756 * the remote call to initiate copy using temporary file. 11757 */ 11758 ret = args.copyApk(mContainerService, true); 11759 } 11760 } 11761 11762 mRet = ret; 11763 } 11764 11765 @Override 11766 void handleReturnCode() { 11767 // If mArgs is null, then MCS couldn't be reached. When it 11768 // reconnects, it will try again to install. At that point, this 11769 // will succeed. 11770 if (mArgs != null) { 11771 processPendingInstall(mArgs, mRet); 11772 } 11773 } 11774 11775 @Override 11776 void handleServiceError() { 11777 mArgs = createInstallArgs(this); 11778 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11779 } 11780 11781 public boolean isForwardLocked() { 11782 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11783 } 11784 } 11785 11786 /** 11787 * Used during creation of InstallArgs 11788 * 11789 * @param installFlags package installation flags 11790 * @return true if should be installed on external storage 11791 */ 11792 private static boolean installOnExternalAsec(int installFlags) { 11793 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11794 return false; 11795 } 11796 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11797 return true; 11798 } 11799 return false; 11800 } 11801 11802 /** 11803 * Used during creation of InstallArgs 11804 * 11805 * @param installFlags package installation flags 11806 * @return true if should be installed as forward locked 11807 */ 11808 private static boolean installForwardLocked(int installFlags) { 11809 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11810 } 11811 11812 private InstallArgs createInstallArgs(InstallParams params) { 11813 if (params.move != null) { 11814 return new MoveInstallArgs(params); 11815 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11816 return new AsecInstallArgs(params); 11817 } else { 11818 return new FileInstallArgs(params); 11819 } 11820 } 11821 11822 /** 11823 * Create args that describe an existing installed package. Typically used 11824 * when cleaning up old installs, or used as a move source. 11825 */ 11826 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11827 String resourcePath, String[] instructionSets) { 11828 final boolean isInAsec; 11829 if (installOnExternalAsec(installFlags)) { 11830 /* Apps on SD card are always in ASEC containers. */ 11831 isInAsec = true; 11832 } else if (installForwardLocked(installFlags) 11833 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11834 /* 11835 * Forward-locked apps are only in ASEC containers if they're the 11836 * new style 11837 */ 11838 isInAsec = true; 11839 } else { 11840 isInAsec = false; 11841 } 11842 11843 if (isInAsec) { 11844 return new AsecInstallArgs(codePath, instructionSets, 11845 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11846 } else { 11847 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11848 } 11849 } 11850 11851 static abstract class InstallArgs { 11852 /** @see InstallParams#origin */ 11853 final OriginInfo origin; 11854 /** @see InstallParams#move */ 11855 final MoveInfo move; 11856 11857 final IPackageInstallObserver2 observer; 11858 // Always refers to PackageManager flags only 11859 final int installFlags; 11860 final String installerPackageName; 11861 final String volumeUuid; 11862 final UserHandle user; 11863 final String abiOverride; 11864 final String[] installGrantPermissions; 11865 /** If non-null, drop an async trace when the install completes */ 11866 final String traceMethod; 11867 final int traceCookie; 11868 11869 // The list of instruction sets supported by this app. This is currently 11870 // only used during the rmdex() phase to clean up resources. We can get rid of this 11871 // if we move dex files under the common app path. 11872 /* nullable */ String[] instructionSets; 11873 11874 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11875 int installFlags, String installerPackageName, String volumeUuid, 11876 UserHandle user, String[] instructionSets, 11877 String abiOverride, String[] installGrantPermissions, 11878 String traceMethod, int traceCookie) { 11879 this.origin = origin; 11880 this.move = move; 11881 this.installFlags = installFlags; 11882 this.observer = observer; 11883 this.installerPackageName = installerPackageName; 11884 this.volumeUuid = volumeUuid; 11885 this.user = user; 11886 this.instructionSets = instructionSets; 11887 this.abiOverride = abiOverride; 11888 this.installGrantPermissions = installGrantPermissions; 11889 this.traceMethod = traceMethod; 11890 this.traceCookie = traceCookie; 11891 } 11892 11893 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11894 abstract int doPreInstall(int status); 11895 11896 /** 11897 * Rename package into final resting place. All paths on the given 11898 * scanned package should be updated to reflect the rename. 11899 */ 11900 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11901 abstract int doPostInstall(int status, int uid); 11902 11903 /** @see PackageSettingBase#codePathString */ 11904 abstract String getCodePath(); 11905 /** @see PackageSettingBase#resourcePathString */ 11906 abstract String getResourcePath(); 11907 11908 // Need installer lock especially for dex file removal. 11909 abstract void cleanUpResourcesLI(); 11910 abstract boolean doPostDeleteLI(boolean delete); 11911 11912 /** 11913 * Called before the source arguments are copied. This is used mostly 11914 * for MoveParams when it needs to read the source file to put it in the 11915 * destination. 11916 */ 11917 int doPreCopy() { 11918 return PackageManager.INSTALL_SUCCEEDED; 11919 } 11920 11921 /** 11922 * Called after the source arguments are copied. This is used mostly for 11923 * MoveParams when it needs to read the source file to put it in the 11924 * destination. 11925 * 11926 * @return 11927 */ 11928 int doPostCopy(int uid) { 11929 return PackageManager.INSTALL_SUCCEEDED; 11930 } 11931 11932 protected boolean isFwdLocked() { 11933 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11934 } 11935 11936 protected boolean isExternalAsec() { 11937 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11938 } 11939 11940 protected boolean isEphemeral() { 11941 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11942 } 11943 11944 UserHandle getUser() { 11945 return user; 11946 } 11947 } 11948 11949 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11950 if (!allCodePaths.isEmpty()) { 11951 if (instructionSets == null) { 11952 throw new IllegalStateException("instructionSet == null"); 11953 } 11954 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11955 for (String codePath : allCodePaths) { 11956 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11957 try { 11958 mInstaller.rmdex(codePath, dexCodeInstructionSet); 11959 } catch (InstallerException ignored) { 11960 } 11961 } 11962 } 11963 } 11964 } 11965 11966 /** 11967 * Logic to handle installation of non-ASEC applications, including copying 11968 * and renaming logic. 11969 */ 11970 class FileInstallArgs extends InstallArgs { 11971 private File codeFile; 11972 private File resourceFile; 11973 11974 // Example topology: 11975 // /data/app/com.example/base.apk 11976 // /data/app/com.example/split_foo.apk 11977 // /data/app/com.example/lib/arm/libfoo.so 11978 // /data/app/com.example/lib/arm64/libfoo.so 11979 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11980 11981 /** New install */ 11982 FileInstallArgs(InstallParams params) { 11983 super(params.origin, params.move, params.observer, params.installFlags, 11984 params.installerPackageName, params.volumeUuid, 11985 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11986 params.grantedRuntimePermissions, 11987 params.traceMethod, params.traceCookie); 11988 if (isFwdLocked()) { 11989 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11990 } 11991 } 11992 11993 /** Existing install */ 11994 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11995 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 11996 null, null, null, 0); 11997 this.codeFile = (codePath != null) ? new File(codePath) : null; 11998 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11999 } 12000 12001 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12002 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12003 try { 12004 return doCopyApk(imcs, temp); 12005 } finally { 12006 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12007 } 12008 } 12009 12010 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12011 if (origin.staged) { 12012 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12013 codeFile = origin.file; 12014 resourceFile = origin.file; 12015 return PackageManager.INSTALL_SUCCEEDED; 12016 } 12017 12018 try { 12019 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12020 final File tempDir = 12021 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12022 codeFile = tempDir; 12023 resourceFile = tempDir; 12024 } catch (IOException e) { 12025 Slog.w(TAG, "Failed to create copy file: " + e); 12026 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12027 } 12028 12029 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12030 @Override 12031 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12032 if (!FileUtils.isValidExtFilename(name)) { 12033 throw new IllegalArgumentException("Invalid filename: " + name); 12034 } 12035 try { 12036 final File file = new File(codeFile, name); 12037 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12038 O_RDWR | O_CREAT, 0644); 12039 Os.chmod(file.getAbsolutePath(), 0644); 12040 return new ParcelFileDescriptor(fd); 12041 } catch (ErrnoException e) { 12042 throw new RemoteException("Failed to open: " + e.getMessage()); 12043 } 12044 } 12045 }; 12046 12047 int ret = PackageManager.INSTALL_SUCCEEDED; 12048 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12049 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12050 Slog.e(TAG, "Failed to copy package"); 12051 return ret; 12052 } 12053 12054 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12055 NativeLibraryHelper.Handle handle = null; 12056 try { 12057 handle = NativeLibraryHelper.Handle.create(codeFile); 12058 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12059 abiOverride); 12060 } catch (IOException e) { 12061 Slog.e(TAG, "Copying native libraries failed", e); 12062 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12063 } finally { 12064 IoUtils.closeQuietly(handle); 12065 } 12066 12067 return ret; 12068 } 12069 12070 int doPreInstall(int status) { 12071 if (status != PackageManager.INSTALL_SUCCEEDED) { 12072 cleanUp(); 12073 } 12074 return status; 12075 } 12076 12077 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12078 if (status != PackageManager.INSTALL_SUCCEEDED) { 12079 cleanUp(); 12080 return false; 12081 } 12082 12083 final File targetDir = codeFile.getParentFile(); 12084 final File beforeCodeFile = codeFile; 12085 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12086 12087 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12088 try { 12089 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12090 } catch (ErrnoException e) { 12091 Slog.w(TAG, "Failed to rename", e); 12092 return false; 12093 } 12094 12095 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12096 Slog.w(TAG, "Failed to restorecon"); 12097 return false; 12098 } 12099 12100 // Reflect the rename internally 12101 codeFile = afterCodeFile; 12102 resourceFile = afterCodeFile; 12103 12104 // Reflect the rename in scanned details 12105 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12106 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12107 afterCodeFile, pkg.baseCodePath)); 12108 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12109 afterCodeFile, pkg.splitCodePaths)); 12110 12111 // Reflect the rename in app info 12112 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12113 pkg.setApplicationInfoCodePath(pkg.codePath); 12114 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12115 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12116 pkg.setApplicationInfoResourcePath(pkg.codePath); 12117 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12118 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12119 12120 return true; 12121 } 12122 12123 int doPostInstall(int status, int uid) { 12124 if (status != PackageManager.INSTALL_SUCCEEDED) { 12125 cleanUp(); 12126 } 12127 return status; 12128 } 12129 12130 @Override 12131 String getCodePath() { 12132 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12133 } 12134 12135 @Override 12136 String getResourcePath() { 12137 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12138 } 12139 12140 private boolean cleanUp() { 12141 if (codeFile == null || !codeFile.exists()) { 12142 return false; 12143 } 12144 12145 removeCodePathLI(codeFile); 12146 12147 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12148 resourceFile.delete(); 12149 } 12150 12151 return true; 12152 } 12153 12154 void cleanUpResourcesLI() { 12155 // Try enumerating all code paths before deleting 12156 List<String> allCodePaths = Collections.EMPTY_LIST; 12157 if (codeFile != null && codeFile.exists()) { 12158 try { 12159 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12160 allCodePaths = pkg.getAllCodePaths(); 12161 } catch (PackageParserException e) { 12162 // Ignored; we tried our best 12163 } 12164 } 12165 12166 cleanUp(); 12167 removeDexFiles(allCodePaths, instructionSets); 12168 } 12169 12170 boolean doPostDeleteLI(boolean delete) { 12171 // XXX err, shouldn't we respect the delete flag? 12172 cleanUpResourcesLI(); 12173 return true; 12174 } 12175 } 12176 12177 private boolean isAsecExternal(String cid) { 12178 final String asecPath = PackageHelper.getSdFilesystem(cid); 12179 return !asecPath.startsWith(mAsecInternalPath); 12180 } 12181 12182 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12183 PackageManagerException { 12184 if (copyRet < 0) { 12185 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12186 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12187 throw new PackageManagerException(copyRet, message); 12188 } 12189 } 12190 } 12191 12192 /** 12193 * Extract the MountService "container ID" from the full code path of an 12194 * .apk. 12195 */ 12196 static String cidFromCodePath(String fullCodePath) { 12197 int eidx = fullCodePath.lastIndexOf("/"); 12198 String subStr1 = fullCodePath.substring(0, eidx); 12199 int sidx = subStr1.lastIndexOf("/"); 12200 return subStr1.substring(sidx+1, eidx); 12201 } 12202 12203 /** 12204 * Logic to handle installation of ASEC applications, including copying and 12205 * renaming logic. 12206 */ 12207 class AsecInstallArgs extends InstallArgs { 12208 static final String RES_FILE_NAME = "pkg.apk"; 12209 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12210 12211 String cid; 12212 String packagePath; 12213 String resourcePath; 12214 12215 /** New install */ 12216 AsecInstallArgs(InstallParams params) { 12217 super(params.origin, params.move, params.observer, params.installFlags, 12218 params.installerPackageName, params.volumeUuid, 12219 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12220 params.grantedRuntimePermissions, 12221 params.traceMethod, params.traceCookie); 12222 } 12223 12224 /** Existing install */ 12225 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12226 boolean isExternal, boolean isForwardLocked) { 12227 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12228 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12229 instructionSets, null, null, null, 0); 12230 // Hackily pretend we're still looking at a full code path 12231 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12232 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12233 } 12234 12235 // Extract cid from fullCodePath 12236 int eidx = fullCodePath.lastIndexOf("/"); 12237 String subStr1 = fullCodePath.substring(0, eidx); 12238 int sidx = subStr1.lastIndexOf("/"); 12239 cid = subStr1.substring(sidx+1, eidx); 12240 setMountPath(subStr1); 12241 } 12242 12243 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12244 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12245 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12246 instructionSets, null, null, null, 0); 12247 this.cid = cid; 12248 setMountPath(PackageHelper.getSdDir(cid)); 12249 } 12250 12251 void createCopyFile() { 12252 cid = mInstallerService.allocateExternalStageCidLegacy(); 12253 } 12254 12255 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12256 if (origin.staged && origin.cid != null) { 12257 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12258 cid = origin.cid; 12259 setMountPath(PackageHelper.getSdDir(cid)); 12260 return PackageManager.INSTALL_SUCCEEDED; 12261 } 12262 12263 if (temp) { 12264 createCopyFile(); 12265 } else { 12266 /* 12267 * Pre-emptively destroy the container since it's destroyed if 12268 * copying fails due to it existing anyway. 12269 */ 12270 PackageHelper.destroySdDir(cid); 12271 } 12272 12273 final String newMountPath = imcs.copyPackageToContainer( 12274 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12275 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12276 12277 if (newMountPath != null) { 12278 setMountPath(newMountPath); 12279 return PackageManager.INSTALL_SUCCEEDED; 12280 } else { 12281 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12282 } 12283 } 12284 12285 @Override 12286 String getCodePath() { 12287 return packagePath; 12288 } 12289 12290 @Override 12291 String getResourcePath() { 12292 return resourcePath; 12293 } 12294 12295 int doPreInstall(int status) { 12296 if (status != PackageManager.INSTALL_SUCCEEDED) { 12297 // Destroy container 12298 PackageHelper.destroySdDir(cid); 12299 } else { 12300 boolean mounted = PackageHelper.isContainerMounted(cid); 12301 if (!mounted) { 12302 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 12303 Process.SYSTEM_UID); 12304 if (newMountPath != null) { 12305 setMountPath(newMountPath); 12306 } else { 12307 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12308 } 12309 } 12310 } 12311 return status; 12312 } 12313 12314 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12315 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 12316 String newMountPath = null; 12317 if (PackageHelper.isContainerMounted(cid)) { 12318 // Unmount the container 12319 if (!PackageHelper.unMountSdDir(cid)) { 12320 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 12321 return false; 12322 } 12323 } 12324 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12325 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 12326 " which might be stale. Will try to clean up."); 12327 // Clean up the stale container and proceed to recreate. 12328 if (!PackageHelper.destroySdDir(newCacheId)) { 12329 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 12330 return false; 12331 } 12332 // Successfully cleaned up stale container. Try to rename again. 12333 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12334 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 12335 + " inspite of cleaning it up."); 12336 return false; 12337 } 12338 } 12339 if (!PackageHelper.isContainerMounted(newCacheId)) { 12340 Slog.w(TAG, "Mounting container " + newCacheId); 12341 newMountPath = PackageHelper.mountSdDir(newCacheId, 12342 getEncryptKey(), Process.SYSTEM_UID); 12343 } else { 12344 newMountPath = PackageHelper.getSdDir(newCacheId); 12345 } 12346 if (newMountPath == null) { 12347 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 12348 return false; 12349 } 12350 Log.i(TAG, "Succesfully renamed " + cid + 12351 " to " + newCacheId + 12352 " at new path: " + newMountPath); 12353 cid = newCacheId; 12354 12355 final File beforeCodeFile = new File(packagePath); 12356 setMountPath(newMountPath); 12357 final File afterCodeFile = new File(packagePath); 12358 12359 // Reflect the rename in scanned details 12360 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12361 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12362 afterCodeFile, pkg.baseCodePath)); 12363 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12364 afterCodeFile, pkg.splitCodePaths)); 12365 12366 // Reflect the rename in app info 12367 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12368 pkg.setApplicationInfoCodePath(pkg.codePath); 12369 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12370 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12371 pkg.setApplicationInfoResourcePath(pkg.codePath); 12372 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12373 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12374 12375 return true; 12376 } 12377 12378 private void setMountPath(String mountPath) { 12379 final File mountFile = new File(mountPath); 12380 12381 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 12382 if (monolithicFile.exists()) { 12383 packagePath = monolithicFile.getAbsolutePath(); 12384 if (isFwdLocked()) { 12385 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 12386 } else { 12387 resourcePath = packagePath; 12388 } 12389 } else { 12390 packagePath = mountFile.getAbsolutePath(); 12391 resourcePath = packagePath; 12392 } 12393 } 12394 12395 int doPostInstall(int status, int uid) { 12396 if (status != PackageManager.INSTALL_SUCCEEDED) { 12397 cleanUp(); 12398 } else { 12399 final int groupOwner; 12400 final String protectedFile; 12401 if (isFwdLocked()) { 12402 groupOwner = UserHandle.getSharedAppGid(uid); 12403 protectedFile = RES_FILE_NAME; 12404 } else { 12405 groupOwner = -1; 12406 protectedFile = null; 12407 } 12408 12409 if (uid < Process.FIRST_APPLICATION_UID 12410 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 12411 Slog.e(TAG, "Failed to finalize " + cid); 12412 PackageHelper.destroySdDir(cid); 12413 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12414 } 12415 12416 boolean mounted = PackageHelper.isContainerMounted(cid); 12417 if (!mounted) { 12418 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12419 } 12420 } 12421 return status; 12422 } 12423 12424 private void cleanUp() { 12425 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12426 12427 // Destroy secure container 12428 PackageHelper.destroySdDir(cid); 12429 } 12430 12431 private List<String> getAllCodePaths() { 12432 final File codeFile = new File(getCodePath()); 12433 if (codeFile != null && codeFile.exists()) { 12434 try { 12435 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12436 return pkg.getAllCodePaths(); 12437 } catch (PackageParserException e) { 12438 // Ignored; we tried our best 12439 } 12440 } 12441 return Collections.EMPTY_LIST; 12442 } 12443 12444 void cleanUpResourcesLI() { 12445 // Enumerate all code paths before deleting 12446 cleanUpResourcesLI(getAllCodePaths()); 12447 } 12448 12449 private void cleanUpResourcesLI(List<String> allCodePaths) { 12450 cleanUp(); 12451 removeDexFiles(allCodePaths, instructionSets); 12452 } 12453 12454 String getPackageName() { 12455 return getAsecPackageName(cid); 12456 } 12457 12458 boolean doPostDeleteLI(boolean delete) { 12459 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12460 final List<String> allCodePaths = getAllCodePaths(); 12461 boolean mounted = PackageHelper.isContainerMounted(cid); 12462 if (mounted) { 12463 // Unmount first 12464 if (PackageHelper.unMountSdDir(cid)) { 12465 mounted = false; 12466 } 12467 } 12468 if (!mounted && delete) { 12469 cleanUpResourcesLI(allCodePaths); 12470 } 12471 return !mounted; 12472 } 12473 12474 @Override 12475 int doPreCopy() { 12476 if (isFwdLocked()) { 12477 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12478 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12479 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12480 } 12481 } 12482 12483 return PackageManager.INSTALL_SUCCEEDED; 12484 } 12485 12486 @Override 12487 int doPostCopy(int uid) { 12488 if (isFwdLocked()) { 12489 if (uid < Process.FIRST_APPLICATION_UID 12490 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12491 RES_FILE_NAME)) { 12492 Slog.e(TAG, "Failed to finalize " + cid); 12493 PackageHelper.destroySdDir(cid); 12494 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12495 } 12496 } 12497 12498 return PackageManager.INSTALL_SUCCEEDED; 12499 } 12500 } 12501 12502 /** 12503 * Logic to handle movement of existing installed applications. 12504 */ 12505 class MoveInstallArgs extends InstallArgs { 12506 private File codeFile; 12507 private File resourceFile; 12508 12509 /** New install */ 12510 MoveInstallArgs(InstallParams params) { 12511 super(params.origin, params.move, params.observer, params.installFlags, 12512 params.installerPackageName, params.volumeUuid, 12513 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12514 params.grantedRuntimePermissions, 12515 params.traceMethod, params.traceCookie); 12516 } 12517 12518 int copyApk(IMediaContainerService imcs, boolean temp) { 12519 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12520 + move.fromUuid + " to " + move.toUuid); 12521 synchronized (mInstaller) { 12522 try { 12523 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12524 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12525 } catch (InstallerException e) { 12526 Slog.w(TAG, "Failed to move app", e); 12527 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12528 } 12529 } 12530 12531 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12532 resourceFile = codeFile; 12533 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12534 12535 return PackageManager.INSTALL_SUCCEEDED; 12536 } 12537 12538 int doPreInstall(int status) { 12539 if (status != PackageManager.INSTALL_SUCCEEDED) { 12540 cleanUp(move.toUuid); 12541 } 12542 return status; 12543 } 12544 12545 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12546 if (status != PackageManager.INSTALL_SUCCEEDED) { 12547 cleanUp(move.toUuid); 12548 return false; 12549 } 12550 12551 // Reflect the move in app info 12552 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12553 pkg.setApplicationInfoCodePath(pkg.codePath); 12554 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12555 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12556 pkg.setApplicationInfoResourcePath(pkg.codePath); 12557 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12558 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12559 12560 return true; 12561 } 12562 12563 int doPostInstall(int status, int uid) { 12564 if (status == PackageManager.INSTALL_SUCCEEDED) { 12565 cleanUp(move.fromUuid); 12566 } else { 12567 cleanUp(move.toUuid); 12568 } 12569 return status; 12570 } 12571 12572 @Override 12573 String getCodePath() { 12574 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12575 } 12576 12577 @Override 12578 String getResourcePath() { 12579 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12580 } 12581 12582 private boolean cleanUp(String volumeUuid) { 12583 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12584 move.dataAppName); 12585 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12586 synchronized (mInstallLock) { 12587 // Clean up both app data and code 12588 removeDataDirsLI(volumeUuid, move.packageName); 12589 removeCodePathLI(codeFile); 12590 } 12591 return true; 12592 } 12593 12594 void cleanUpResourcesLI() { 12595 throw new UnsupportedOperationException(); 12596 } 12597 12598 boolean doPostDeleteLI(boolean delete) { 12599 throw new UnsupportedOperationException(); 12600 } 12601 } 12602 12603 static String getAsecPackageName(String packageCid) { 12604 int idx = packageCid.lastIndexOf("-"); 12605 if (idx == -1) { 12606 return packageCid; 12607 } 12608 return packageCid.substring(0, idx); 12609 } 12610 12611 // Utility method used to create code paths based on package name and available index. 12612 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12613 String idxStr = ""; 12614 int idx = 1; 12615 // Fall back to default value of idx=1 if prefix is not 12616 // part of oldCodePath 12617 if (oldCodePath != null) { 12618 String subStr = oldCodePath; 12619 // Drop the suffix right away 12620 if (suffix != null && subStr.endsWith(suffix)) { 12621 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12622 } 12623 // If oldCodePath already contains prefix find out the 12624 // ending index to either increment or decrement. 12625 int sidx = subStr.lastIndexOf(prefix); 12626 if (sidx != -1) { 12627 subStr = subStr.substring(sidx + prefix.length()); 12628 if (subStr != null) { 12629 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12630 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12631 } 12632 try { 12633 idx = Integer.parseInt(subStr); 12634 if (idx <= 1) { 12635 idx++; 12636 } else { 12637 idx--; 12638 } 12639 } catch(NumberFormatException e) { 12640 } 12641 } 12642 } 12643 } 12644 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12645 return prefix + idxStr; 12646 } 12647 12648 private File getNextCodePath(File targetDir, String packageName) { 12649 int suffix = 1; 12650 File result; 12651 do { 12652 result = new File(targetDir, packageName + "-" + suffix); 12653 suffix++; 12654 } while (result.exists()); 12655 return result; 12656 } 12657 12658 // Utility method that returns the relative package path with respect 12659 // to the installation directory. Like say for /data/data/com.test-1.apk 12660 // string com.test-1 is returned. 12661 static String deriveCodePathName(String codePath) { 12662 if (codePath == null) { 12663 return null; 12664 } 12665 final File codeFile = new File(codePath); 12666 final String name = codeFile.getName(); 12667 if (codeFile.isDirectory()) { 12668 return name; 12669 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12670 final int lastDot = name.lastIndexOf('.'); 12671 return name.substring(0, lastDot); 12672 } else { 12673 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12674 return null; 12675 } 12676 } 12677 12678 static class PackageInstalledInfo { 12679 String name; 12680 int uid; 12681 // The set of users that originally had this package installed. 12682 int[] origUsers; 12683 // The set of users that now have this package installed. 12684 int[] newUsers; 12685 PackageParser.Package pkg; 12686 int returnCode; 12687 String returnMsg; 12688 PackageRemovedInfo removedInfo; 12689 12690 public void setError(int code, String msg) { 12691 returnCode = code; 12692 returnMsg = msg; 12693 Slog.w(TAG, msg); 12694 } 12695 12696 public void setError(String msg, PackageParserException e) { 12697 returnCode = e.error; 12698 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12699 Slog.w(TAG, msg, e); 12700 } 12701 12702 public void setError(String msg, PackageManagerException e) { 12703 returnCode = e.error; 12704 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12705 Slog.w(TAG, msg, e); 12706 } 12707 12708 // In some error cases we want to convey more info back to the observer 12709 String origPackage; 12710 String origPermission; 12711 } 12712 12713 /* 12714 * Install a non-existing package. 12715 */ 12716 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12717 UserHandle user, String installerPackageName, String volumeUuid, 12718 PackageInstalledInfo res) { 12719 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12720 12721 // Remember this for later, in case we need to rollback this install 12722 String pkgName = pkg.packageName; 12723 12724 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12725 12726 synchronized(mPackages) { 12727 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12728 // A package with the same name is already installed, though 12729 // it has been renamed to an older name. The package we 12730 // are trying to install should be installed as an update to 12731 // the existing one, but that has not been requested, so bail. 12732 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12733 + " without first uninstalling package running as " 12734 + mSettings.mRenamedPackages.get(pkgName)); 12735 return; 12736 } 12737 if (mPackages.containsKey(pkgName)) { 12738 // Don't allow installation over an existing package with the same name. 12739 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12740 + " without first uninstalling."); 12741 return; 12742 } 12743 } 12744 12745 try { 12746 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12747 System.currentTimeMillis(), user); 12748 12749 updateSettingsLI(newPackage, installerPackageName, null, null, res, user); 12750 12751 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12752 prepareAppDataAfterInstall(newPackage); 12753 12754 } else { 12755 // Remove package from internal structures, but keep around any 12756 // data that might have already existed 12757 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12758 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 12759 } 12760 12761 } catch (PackageManagerException e) { 12762 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12763 } 12764 12765 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12766 } 12767 12768 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12769 // Can't rotate keys during boot or if sharedUser. 12770 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12771 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12772 return false; 12773 } 12774 // app is using upgradeKeySets; make sure all are valid 12775 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12776 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12777 for (int i = 0; i < upgradeKeySets.length; i++) { 12778 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12779 Slog.wtf(TAG, "Package " 12780 + (oldPs.name != null ? oldPs.name : "<null>") 12781 + " contains upgrade-key-set reference to unknown key-set: " 12782 + upgradeKeySets[i] 12783 + " reverting to signatures check."); 12784 return false; 12785 } 12786 } 12787 return true; 12788 } 12789 12790 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12791 // Upgrade keysets are being used. Determine if new package has a superset of the 12792 // required keys. 12793 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12794 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12795 for (int i = 0; i < upgradeKeySets.length; i++) { 12796 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12797 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12798 return true; 12799 } 12800 } 12801 return false; 12802 } 12803 12804 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12805 UserHandle user, String installerPackageName, String volumeUuid, 12806 PackageInstalledInfo res) { 12807 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12808 12809 final PackageParser.Package oldPackage; 12810 final String pkgName = pkg.packageName; 12811 final int[] allUsers; 12812 final boolean[] perUserInstalled; 12813 12814 // First find the old package info and check signatures 12815 synchronized(mPackages) { 12816 oldPackage = mPackages.get(pkgName); 12817 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12818 if (isEphemeral && !oldIsEphemeral) { 12819 // can't downgrade from full to ephemeral 12820 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12821 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12822 return; 12823 } 12824 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12825 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12826 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12827 if (!checkUpgradeKeySetLP(ps, pkg)) { 12828 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12829 "New package not signed by keys specified by upgrade-keysets: " 12830 + pkgName); 12831 return; 12832 } 12833 } else { 12834 // default to original signature matching 12835 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12836 != PackageManager.SIGNATURE_MATCH) { 12837 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12838 "New package has a different signature: " + pkgName); 12839 return; 12840 } 12841 } 12842 12843 // In case of rollback, remember per-user/profile install state 12844 allUsers = sUserManager.getUserIds(); 12845 perUserInstalled = new boolean[allUsers.length]; 12846 for (int i = 0; i < allUsers.length; i++) { 12847 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12848 } 12849 } 12850 12851 boolean sysPkg = (isSystemApp(oldPackage)); 12852 if (sysPkg) { 12853 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12854 user, allUsers, perUserInstalled, installerPackageName, res); 12855 } else { 12856 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12857 user, allUsers, perUserInstalled, installerPackageName, res); 12858 } 12859 } 12860 12861 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12862 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12863 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12864 PackageInstalledInfo res) { 12865 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12866 + deletedPackage); 12867 12868 String pkgName = deletedPackage.packageName; 12869 boolean deletedPkg = true; 12870 boolean addedPkg = false; 12871 12872 final long origUpdateTime = (pkg.mExtras != null) 12873 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 12874 12875 // First delete the existing package while retaining the data directory 12876 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12877 res.removedInfo, true, pkg)) { 12878 // If the existing package wasn't successfully deleted 12879 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12880 deletedPkg = false; 12881 } else { 12882 // Successfully deleted the old package; proceed with replace. 12883 12884 // If deleted package lived in a container, give users a chance to 12885 // relinquish resources before killing. 12886 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12887 if (DEBUG_INSTALL) { 12888 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12889 } 12890 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12891 final ArrayList<String> pkgList = new ArrayList<String>(1); 12892 pkgList.add(deletedPackage.applicationInfo.packageName); 12893 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12894 } 12895 12896 deleteCodeCacheDirsLI(pkg); 12897 12898 try { 12899 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12900 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12901 updateSettingsLI(newPackage, installerPackageName, allUsers, 12902 perUserInstalled, res, user); 12903 prepareAppDataAfterInstall(newPackage); 12904 addedPkg = true; 12905 } catch (PackageManagerException e) { 12906 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12907 } 12908 } 12909 12910 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12911 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12912 12913 // Revert all internal state mutations and added folders for the failed install 12914 if (addedPkg) { 12915 deletePackageLI(pkgName, null, true, allUsers, perUserInstalled, 12916 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 12917 } 12918 12919 // Restore the old package 12920 if (deletedPkg) { 12921 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12922 File restoreFile = new File(deletedPackage.codePath); 12923 // Parse old package 12924 boolean oldExternal = isExternal(deletedPackage); 12925 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12926 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12927 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12928 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12929 try { 12930 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12931 null); 12932 } catch (PackageManagerException e) { 12933 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12934 + e.getMessage()); 12935 return; 12936 } 12937 12938 synchronized (mPackages) { 12939 // Ensure the installer package name up to date 12940 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 12941 12942 // Update permissions for restored package 12943 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 12944 12945 mSettings.writeLPr(); 12946 } 12947 12948 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12949 } 12950 } 12951 } 12952 12953 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12954 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12955 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12956 PackageInstalledInfo res) { 12957 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12958 + ", old=" + deletedPackage); 12959 12960 final boolean disabledSystem; 12961 12962 // Set the system/privileged flags as needed 12963 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12964 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12965 != 0) { 12966 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12967 } 12968 12969 // Kill package processes including services, providers, etc. 12970 killPackage(deletedPackage, "replace sys pkg"); 12971 12972 // Report the result for the parent package only 12973 res.removedInfo.uid = deletedPackage.applicationInfo.uid; 12974 res.removedInfo.removedPackage = deletedPackage.packageName; 12975 12976 // Remove existing system package 12977 removePackageSettingLI(deletedPackage, true); 12978 12979 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 12980 if (!disabledSystem) { 12981 // We didn't need to disable the .apk as a current system package, 12982 // which means we are replacing another update that is already 12983 // installed. We need to make sure to delete the older one's .apk. 12984 res.removedInfo.args = createInstallArgsForExisting(0, 12985 deletedPackage.applicationInfo.getCodePath(), 12986 deletedPackage.applicationInfo.getResourcePath(), 12987 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12988 } else { 12989 res.removedInfo.args = null; 12990 } 12991 12992 // Successfully disabled the old package. Now proceed with re-installation 12993 deleteCodeCacheDirsLI(pkg); 12994 12995 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12996 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 12997 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 12998 12999 PackageParser.Package newPackage = null; 13000 try { 13001 // Add the package to the internal data structures 13002 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13003 13004 // Set the update and install times 13005 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13006 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13007 System.currentTimeMillis()); 13008 13009 // Check for shared user id changes 13010 String invalidPackageName = getParentOrChildPackageChangedSharedUser(deletedPackage, newPackage); 13011 if (invalidPackageName != null) { 13012 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13013 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13014 + " to " + invalidPackageName); 13015 } 13016 13017 // Update the package dynamic state if succeeded 13018 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13019 // Now that the install succeeded make sure we remove data 13020 // directories for any child package the update removed. 13021 final int deletedChildCount = (deletedPackage.childPackages != null) 13022 ? deletedPackage.childPackages.size() : 0; 13023 final int newChildCount = (newPackage.childPackages != null) 13024 ? newPackage.childPackages.size() : 0; 13025 for (int i = 0; i < deletedChildCount; i++) { 13026 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13027 boolean childPackageDeleted = true; 13028 for (int j = 0; j < newChildCount; j++) { 13029 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13030 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13031 childPackageDeleted = false; 13032 break; 13033 } 13034 } 13035 if (childPackageDeleted) { 13036 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13037 deletedChildPkg.packageName); 13038 if (ps != null) { 13039 removePackageDataLI(ps, allUsers, perUserInstalled, null, 0, false); 13040 } 13041 } 13042 } 13043 13044 updateSettingsLI(newPackage, installerPackageName, allUsers, 13045 perUserInstalled, res, user); 13046 prepareAppDataAfterInstall(newPackage); 13047 } 13048 } catch (PackageManagerException e) { 13049 res.returnCode = INSTALL_FAILED_INTERNAL_ERROR; 13050 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13051 } 13052 13053 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13054 // Re installation failed. Restore old information 13055 // Remove new pkg information 13056 if (newPackage != null) { 13057 removeInstalledPackageLI(newPackage, true); 13058 } 13059 // Add back the old system package 13060 try { 13061 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13062 } catch (PackageManagerException e) { 13063 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13064 } 13065 13066 synchronized (mPackages) { 13067 if (disabledSystem) { 13068 enableSystemPackageLPw(deletedPackage); 13069 } 13070 13071 // Ensure the installer package name up to date 13072 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13073 13074 // Update permissions for restored package 13075 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13076 13077 mSettings.writeLPr(); 13078 } 13079 13080 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13081 + " after failed upgrade"); 13082 } 13083 } 13084 13085 /** 13086 * Checks whether the parent or any of the child packages have a change shared 13087 * user. For a package to be a valid update the shred users of the parent and 13088 * the children should match. We may later support changing child shared users. 13089 * @param oldPkg The updated package. 13090 * @param newPkg The update package. 13091 * @return The shared user that change between the versions. 13092 */ 13093 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13094 PackageParser.Package newPkg) { 13095 // Check parent shared user 13096 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13097 return newPkg.packageName; 13098 } 13099 // Check child shared users 13100 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13101 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13102 for (int i = 0; i < newChildCount; i++) { 13103 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13104 // If this child was present, did it have the same shared user? 13105 for (int j = 0; j < oldChildCount; j++) { 13106 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13107 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13108 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13109 return newChildPkg.packageName; 13110 } 13111 } 13112 } 13113 return null; 13114 } 13115 13116 private void removeNativeBinariesLI(PackageParser.Package pkg) { 13117 // Remove the lib path for the parent package 13118 PackageSetting ps = (PackageSetting) pkg.mExtras; 13119 if (ps != null) { 13120 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13121 } 13122 // Remove the lib path for the child packages 13123 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13124 for (int i = 0; i < childCount; i++) { 13125 ps = (PackageSetting) pkg.childPackages.get(i).mExtras; 13126 if (ps != null) { 13127 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13128 } 13129 } 13130 } 13131 13132 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13133 // Enable the parent package 13134 mSettings.enableSystemPackageLPw(pkg.packageName); 13135 // Enable the child packages 13136 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13137 for (int i = 0; i < childCount; i++) { 13138 PackageParser.Package childPkg = pkg.childPackages.get(i); 13139 mSettings.enableSystemPackageLPw(childPkg.packageName); 13140 } 13141 } 13142 13143 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13144 PackageParser.Package newPkg) { 13145 // Disable the parent package (parent always replaced) 13146 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13147 // Disable the child packages 13148 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13149 for (int i = 0; i < childCount; i++) { 13150 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13151 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13152 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13153 } 13154 return disabled; 13155 } 13156 13157 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13158 String installerPackageName) { 13159 // Enable the parent package 13160 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 13161 // Enable the child packages 13162 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13163 for (int i = 0; i < childCount; i++) { 13164 PackageParser.Package childPkg = pkg.childPackages.get(i); 13165 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 13166 } 13167 } 13168 13169 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 13170 // Collect all used permissions in the UID 13171 ArraySet<String> usedPermissions = new ArraySet<>(); 13172 final int packageCount = su.packages.size(); 13173 for (int i = 0; i < packageCount; i++) { 13174 PackageSetting ps = su.packages.valueAt(i); 13175 if (ps.pkg == null) { 13176 continue; 13177 } 13178 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 13179 for (int j = 0; j < requestedPermCount; j++) { 13180 String permission = ps.pkg.requestedPermissions.get(j); 13181 BasePermission bp = mSettings.mPermissions.get(permission); 13182 if (bp != null) { 13183 usedPermissions.add(permission); 13184 } 13185 } 13186 } 13187 13188 PermissionsState permissionsState = su.getPermissionsState(); 13189 // Prune install permissions 13190 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 13191 final int installPermCount = installPermStates.size(); 13192 for (int i = installPermCount - 1; i >= 0; i--) { 13193 PermissionState permissionState = installPermStates.get(i); 13194 if (!usedPermissions.contains(permissionState.getName())) { 13195 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13196 if (bp != null) { 13197 permissionsState.revokeInstallPermission(bp); 13198 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 13199 PackageManager.MASK_PERMISSION_FLAGS, 0); 13200 } 13201 } 13202 } 13203 13204 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 13205 13206 // Prune runtime permissions 13207 for (int userId : allUserIds) { 13208 List<PermissionState> runtimePermStates = permissionsState 13209 .getRuntimePermissionStates(userId); 13210 final int runtimePermCount = runtimePermStates.size(); 13211 for (int i = runtimePermCount - 1; i >= 0; i--) { 13212 PermissionState permissionState = runtimePermStates.get(i); 13213 if (!usedPermissions.contains(permissionState.getName())) { 13214 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13215 if (bp != null) { 13216 permissionsState.revokeRuntimePermission(bp, userId); 13217 permissionsState.updatePermissionFlags(bp, userId, 13218 PackageManager.MASK_PERMISSION_FLAGS, 0); 13219 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 13220 runtimePermissionChangedUserIds, userId); 13221 } 13222 } 13223 } 13224 } 13225 13226 return runtimePermissionChangedUserIds; 13227 } 13228 13229 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 13230 int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, UserHandle user) { 13231 // Update the parent package setting 13232 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, perUserInstalled, 13233 res, user); 13234 // Update the child packages setting 13235 final int childCount = (newPackage.childPackages != null) 13236 ? newPackage.childPackages.size() : 0; 13237 for (int i = 0; i < childCount; i++) { 13238 PackageParser.Package childPackage = newPackage.childPackages.get(i); 13239 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, perUserInstalled, 13240 res, user); 13241 } 13242 } 13243 13244 private void updateSettingsInternalLI(PackageParser.Package newPackage, 13245 String installerPackageName, int[] allUsers, boolean[] perUserInstalled, 13246 PackageInstalledInfo res, UserHandle user) { 13247 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 13248 13249 String pkgName = newPackage.packageName; 13250 synchronized (mPackages) { 13251 //write settings. the installStatus will be incomplete at this stage. 13252 //note that the new package setting would have already been 13253 //added to mPackages. It hasn't been persisted yet. 13254 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 13255 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13256 mSettings.writeLPr(); 13257 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13258 } 13259 13260 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 13261 synchronized (mPackages) { 13262 updatePermissionsLPw(newPackage.packageName, newPackage, 13263 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 13264 ? UPDATE_PERMISSIONS_ALL : 0)); 13265 // For system-bundled packages, we assume that installing an upgraded version 13266 // of the package implies that the user actually wants to run that new code, 13267 // so we enable the package. 13268 PackageSetting ps = mSettings.mPackages.get(pkgName); 13269 final int userId = user.getIdentifier(); 13270 if (ps != null) { 13271 if (isSystemApp(newPackage)) { 13272 if (DEBUG_INSTALL) { 13273 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 13274 } 13275 // Enable system package for requested users 13276 if (res.origUsers != null) { 13277 for (int origUserId : res.origUsers) { 13278 if (userId == UserHandle.USER_ALL || userId == origUserId) { 13279 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 13280 origUserId, installerPackageName); 13281 } 13282 } 13283 } 13284 // Also convey the prior install/uninstall state 13285 if (allUsers != null && perUserInstalled != null) { 13286 for (int i = 0; i < allUsers.length; i++) { 13287 if (DEBUG_INSTALL) { 13288 Slog.d(TAG, " user " + allUsers[i] 13289 + " => " + perUserInstalled[i]); 13290 } 13291 ps.setInstalled(perUserInstalled[i], allUsers[i]); 13292 } 13293 // these install state changes will be persisted in the 13294 // upcoming call to mSettings.writeLPr(). 13295 } 13296 } 13297 // It's implied that when a user requests installation, they want the app to be 13298 // installed and enabled. 13299 if (userId != UserHandle.USER_ALL) { 13300 ps.setInstalled(true, userId); 13301 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 13302 } 13303 } 13304 res.name = pkgName; 13305 res.uid = newPackage.applicationInfo.uid; 13306 res.pkg = newPackage; 13307 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 13308 mSettings.setInstallerPackageName(pkgName, installerPackageName); 13309 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 13310 //to update install status 13311 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13312 mSettings.writeLPr(); 13313 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13314 } 13315 13316 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13317 } 13318 13319 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 13320 try { 13321 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 13322 installPackageLI(args, res); 13323 } finally { 13324 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13325 } 13326 } 13327 13328 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 13329 final int installFlags = args.installFlags; 13330 final String installerPackageName = args.installerPackageName; 13331 final String volumeUuid = args.volumeUuid; 13332 final File tmpPackageFile = new File(args.getCodePath()); 13333 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 13334 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 13335 || (args.volumeUuid != null)); 13336 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 13337 boolean replace = false; 13338 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 13339 if (args.move != null) { 13340 // moving a complete application; perfom an initial scan on the new install location 13341 scanFlags |= SCAN_INITIAL; 13342 } 13343 // Result object to be returned 13344 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 13345 13346 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 13347 13348 // Sanity check 13349 if (ephemeral && (forwardLocked || onExternal)) { 13350 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 13351 + " external=" + onExternal); 13352 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 13353 return; 13354 } 13355 13356 // Retrieve PackageSettings and parse package 13357 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 13358 | PackageParser.PARSE_ENFORCE_CODE 13359 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 13360 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 13361 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 13362 PackageParser pp = new PackageParser(); 13363 pp.setSeparateProcesses(mSeparateProcesses); 13364 pp.setDisplayMetrics(mMetrics); 13365 13366 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 13367 final PackageParser.Package pkg; 13368 try { 13369 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 13370 } catch (PackageParserException e) { 13371 res.setError("Failed parse during installPackageLI", e); 13372 return; 13373 } finally { 13374 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13375 } 13376 13377 // If package doesn't declare API override, mark that we have an install 13378 // time CPU ABI override. 13379 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 13380 pkg.cpuAbiOverride = args.abiOverride; 13381 } 13382 13383 String pkgName = res.name = pkg.packageName; 13384 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 13385 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 13386 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 13387 return; 13388 } 13389 } 13390 13391 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 13392 try { 13393 PackageParser.collectCertificates(pkg, parseFlags); 13394 } catch (PackageParserException e) { 13395 res.setError("Failed collect during installPackageLI", e); 13396 return; 13397 } finally { 13398 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13399 } 13400 13401 // Get rid of all references to package scan path via parser. 13402 pp = null; 13403 String oldCodePath = null; 13404 boolean systemApp = false; 13405 synchronized (mPackages) { 13406 // Check if installing already existing package 13407 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13408 String oldName = mSettings.mRenamedPackages.get(pkgName); 13409 if (pkg.mOriginalPackages != null 13410 && pkg.mOriginalPackages.contains(oldName) 13411 && mPackages.containsKey(oldName)) { 13412 // This package is derived from an original package, 13413 // and this device has been updating from that original 13414 // name. We must continue using the original name, so 13415 // rename the new package here. 13416 pkg.setPackageName(oldName); 13417 pkgName = pkg.packageName; 13418 replace = true; 13419 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 13420 + oldName + " pkgName=" + pkgName); 13421 } else if (mPackages.containsKey(pkgName)) { 13422 // This package, under its official name, already exists 13423 // on the device; we should replace it. 13424 replace = true; 13425 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 13426 } 13427 13428 // Child packages are installed through the parent package 13429 if (pkg.parentPackage != null) { 13430 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13431 "Package " + pkg.packageName + " is child of package " 13432 + pkg.parentPackage.parentPackage + ". Child packages " 13433 + "can be updated only through the parent package."); 13434 return; 13435 } 13436 13437 if (replace) { 13438 // Prevent apps opting out from runtime permissions 13439 PackageParser.Package oldPackage = mPackages.get(pkgName); 13440 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 13441 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 13442 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 13443 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 13444 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 13445 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 13446 + " doesn't support runtime permissions but the old" 13447 + " target SDK " + oldTargetSdk + " does."); 13448 return; 13449 } 13450 13451 // Prevent installing of child packages 13452 if (oldPackage.parentPackage != null) { 13453 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13454 "Package " + pkg.packageName + " is child of package " 13455 + oldPackage.parentPackage + ". Child packages " 13456 + "can be updated only through the parent package."); 13457 return; 13458 } 13459 } 13460 } 13461 13462 PackageSetting ps = mSettings.mPackages.get(pkgName); 13463 if (ps != null) { 13464 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 13465 13466 // Quick sanity check that we're signed correctly if updating; 13467 // we'll check this again later when scanning, but we want to 13468 // bail early here before tripping over redefined permissions. 13469 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13470 if (!checkUpgradeKeySetLP(ps, pkg)) { 13471 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 13472 + pkg.packageName + " upgrade keys do not match the " 13473 + "previously installed version"); 13474 return; 13475 } 13476 } else { 13477 try { 13478 verifySignaturesLP(ps, pkg); 13479 } catch (PackageManagerException e) { 13480 res.setError(e.error, e.getMessage()); 13481 return; 13482 } 13483 } 13484 13485 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 13486 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 13487 systemApp = (ps.pkg.applicationInfo.flags & 13488 ApplicationInfo.FLAG_SYSTEM) != 0; 13489 } 13490 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13491 } 13492 13493 // Check whether the newly-scanned package wants to define an already-defined perm 13494 int N = pkg.permissions.size(); 13495 for (int i = N-1; i >= 0; i--) { 13496 PackageParser.Permission perm = pkg.permissions.get(i); 13497 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 13498 if (bp != null) { 13499 // If the defining package is signed with our cert, it's okay. This 13500 // also includes the "updating the same package" case, of course. 13501 // "updating same package" could also involve key-rotation. 13502 final boolean sigsOk; 13503 if (bp.sourcePackage.equals(pkg.packageName) 13504 && (bp.packageSetting instanceof PackageSetting) 13505 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 13506 scanFlags))) { 13507 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 13508 } else { 13509 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 13510 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 13511 } 13512 if (!sigsOk) { 13513 // If the owning package is the system itself, we log but allow 13514 // install to proceed; we fail the install on all other permission 13515 // redefinitions. 13516 if (!bp.sourcePackage.equals("android")) { 13517 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 13518 + pkg.packageName + " attempting to redeclare permission " 13519 + perm.info.name + " already owned by " + bp.sourcePackage); 13520 res.origPermission = perm.info.name; 13521 res.origPackage = bp.sourcePackage; 13522 return; 13523 } else { 13524 Slog.w(TAG, "Package " + pkg.packageName 13525 + " attempting to redeclare system permission " 13526 + perm.info.name + "; ignoring new declaration"); 13527 pkg.permissions.remove(i); 13528 } 13529 } 13530 } 13531 } 13532 } 13533 13534 if (systemApp) { 13535 if (onExternal) { 13536 // Abort update; system app can't be replaced with app on sdcard 13537 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 13538 "Cannot install updates to system apps on sdcard"); 13539 return; 13540 } else if (ephemeral) { 13541 // Abort update; system app can't be replaced with an ephemeral app 13542 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 13543 "Cannot update a system app with an ephemeral app"); 13544 return; 13545 } 13546 } 13547 13548 if (args.move != null) { 13549 // We did an in-place move, so dex is ready to roll 13550 scanFlags |= SCAN_NO_DEX; 13551 scanFlags |= SCAN_MOVE; 13552 13553 synchronized (mPackages) { 13554 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13555 if (ps == null) { 13556 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 13557 "Missing settings for moved package " + pkgName); 13558 } 13559 13560 // We moved the entire application as-is, so bring over the 13561 // previously derived ABI information. 13562 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13563 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13564 } 13565 13566 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13567 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13568 scanFlags |= SCAN_NO_DEX; 13569 13570 try { 13571 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 13572 args.abiOverride : pkg.cpuAbiOverride); 13573 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 13574 true /* extract libs */); 13575 } catch (PackageManagerException pme) { 13576 Slog.e(TAG, "Error deriving application ABI", pme); 13577 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13578 return; 13579 } 13580 13581 // Extract package to save the VM unzipping the APK in memory during 13582 // launch. Only do this if profile-guided compilation is enabled because 13583 // otherwise BackgroundDexOptService will not dexopt the package later. 13584 if (mUseJitProfiles) { 13585 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 13586 // Do not run PackageDexOptimizer through the local performDexOpt 13587 // method because `pkg` is not in `mPackages` yet. 13588 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 13589 false /* useProfiles */, true /* extractOnly */); 13590 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13591 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 13592 String msg = "Extracking package failed for " + pkgName; 13593 res.setError(INSTALL_FAILED_DEXOPT, msg); 13594 return; 13595 } 13596 } 13597 } 13598 13599 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13600 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13601 return; 13602 } 13603 13604 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13605 13606 if (replace) { 13607 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13608 installerPackageName, volumeUuid, res); 13609 } else { 13610 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13611 args.user, installerPackageName, volumeUuid, res); 13612 } 13613 synchronized (mPackages) { 13614 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13615 if (ps != null) { 13616 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13617 } 13618 } 13619 } 13620 13621 private void startIntentFilterVerifications(int userId, boolean replacing, 13622 PackageParser.Package pkg) { 13623 if (mIntentFilterVerifierComponent == null) { 13624 Slog.w(TAG, "No IntentFilter verification will not be done as " 13625 + "there is no IntentFilterVerifier available!"); 13626 return; 13627 } 13628 13629 final int verifierUid = getPackageUid( 13630 mIntentFilterVerifierComponent.getPackageName(), 13631 MATCH_DEBUG_TRIAGED_MISSING, 13632 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13633 13634 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 13635 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13636 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13637 mHandler.sendMessage(msg); 13638 } 13639 13640 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13641 PackageParser.Package pkg) { 13642 int size = pkg.activities.size(); 13643 if (size == 0) { 13644 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13645 "No activity, so no need to verify any IntentFilter!"); 13646 return; 13647 } 13648 13649 final boolean hasDomainURLs = hasDomainURLs(pkg); 13650 if (!hasDomainURLs) { 13651 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13652 "No domain URLs, so no need to verify any IntentFilter!"); 13653 return; 13654 } 13655 13656 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13657 + " if any IntentFilter from the " + size 13658 + " Activities needs verification ..."); 13659 13660 int count = 0; 13661 final String packageName = pkg.packageName; 13662 13663 synchronized (mPackages) { 13664 // If this is a new install and we see that we've already run verification for this 13665 // package, we have nothing to do: it means the state was restored from backup. 13666 if (!replacing) { 13667 IntentFilterVerificationInfo ivi = 13668 mSettings.getIntentFilterVerificationLPr(packageName); 13669 if (ivi != null) { 13670 if (DEBUG_DOMAIN_VERIFICATION) { 13671 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13672 + ivi.getStatusString()); 13673 } 13674 return; 13675 } 13676 } 13677 13678 // If any filters need to be verified, then all need to be. 13679 boolean needToVerify = false; 13680 for (PackageParser.Activity a : pkg.activities) { 13681 for (ActivityIntentInfo filter : a.intents) { 13682 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13683 if (DEBUG_DOMAIN_VERIFICATION) { 13684 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13685 } 13686 needToVerify = true; 13687 break; 13688 } 13689 } 13690 } 13691 13692 if (needToVerify) { 13693 final int verificationId = mIntentFilterVerificationToken++; 13694 for (PackageParser.Activity a : pkg.activities) { 13695 for (ActivityIntentInfo filter : a.intents) { 13696 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13697 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13698 "Verification needed for IntentFilter:" + filter.toString()); 13699 mIntentFilterVerifier.addOneIntentFilterVerification( 13700 verifierUid, userId, verificationId, filter, packageName); 13701 count++; 13702 } 13703 } 13704 } 13705 } 13706 } 13707 13708 if (count > 0) { 13709 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13710 + " IntentFilter verification" + (count > 1 ? "s" : "") 13711 + " for userId:" + userId); 13712 mIntentFilterVerifier.startVerifications(userId); 13713 } else { 13714 if (DEBUG_DOMAIN_VERIFICATION) { 13715 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13716 } 13717 } 13718 } 13719 13720 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13721 final ComponentName cn = filter.activity.getComponentName(); 13722 final String packageName = cn.getPackageName(); 13723 13724 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13725 packageName); 13726 if (ivi == null) { 13727 return true; 13728 } 13729 int status = ivi.getStatus(); 13730 switch (status) { 13731 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13732 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13733 return true; 13734 13735 default: 13736 // Nothing to do 13737 return false; 13738 } 13739 } 13740 13741 private static boolean isMultiArch(ApplicationInfo info) { 13742 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13743 } 13744 13745 private static boolean isExternal(PackageParser.Package pkg) { 13746 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13747 } 13748 13749 private static boolean isExternal(PackageSetting ps) { 13750 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13751 } 13752 13753 private static boolean isEphemeral(PackageParser.Package pkg) { 13754 return pkg.applicationInfo.isEphemeralApp(); 13755 } 13756 13757 private static boolean isEphemeral(PackageSetting ps) { 13758 return ps.pkg != null && isEphemeral(ps.pkg); 13759 } 13760 13761 private static boolean isSystemApp(PackageParser.Package pkg) { 13762 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13763 } 13764 13765 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13766 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13767 } 13768 13769 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13770 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13771 } 13772 13773 private static boolean isSystemApp(PackageSetting ps) { 13774 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13775 } 13776 13777 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13778 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13779 } 13780 13781 private int packageFlagsToInstallFlags(PackageSetting ps) { 13782 int installFlags = 0; 13783 if (isEphemeral(ps)) { 13784 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13785 } 13786 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13787 // This existing package was an external ASEC install when we have 13788 // the external flag without a UUID 13789 installFlags |= PackageManager.INSTALL_EXTERNAL; 13790 } 13791 if (ps.isForwardLocked()) { 13792 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13793 } 13794 return installFlags; 13795 } 13796 13797 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13798 if (isExternal(pkg)) { 13799 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13800 return StorageManager.UUID_PRIMARY_PHYSICAL; 13801 } else { 13802 return pkg.volumeUuid; 13803 } 13804 } else { 13805 return StorageManager.UUID_PRIVATE_INTERNAL; 13806 } 13807 } 13808 13809 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13810 if (isExternal(pkg)) { 13811 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13812 return mSettings.getExternalVersion(); 13813 } else { 13814 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13815 } 13816 } else { 13817 return mSettings.getInternalVersion(); 13818 } 13819 } 13820 13821 private void deleteTempPackageFiles() { 13822 final FilenameFilter filter = new FilenameFilter() { 13823 public boolean accept(File dir, String name) { 13824 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13825 } 13826 }; 13827 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13828 file.delete(); 13829 } 13830 } 13831 13832 @Override 13833 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13834 int flags) { 13835 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13836 flags); 13837 } 13838 13839 @Override 13840 public void deletePackage(final String packageName, 13841 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13842 mContext.enforceCallingOrSelfPermission( 13843 android.Manifest.permission.DELETE_PACKAGES, null); 13844 Preconditions.checkNotNull(packageName); 13845 Preconditions.checkNotNull(observer); 13846 final int uid = Binder.getCallingUid(); 13847 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13848 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13849 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13850 mContext.enforceCallingOrSelfPermission( 13851 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13852 "deletePackage for user " + userId); 13853 } 13854 13855 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13856 try { 13857 observer.onPackageDeleted(packageName, 13858 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13859 } catch (RemoteException re) { 13860 } 13861 return; 13862 } 13863 13864 for (int currentUserId : users) { 13865 if (getBlockUninstallForUser(packageName, currentUserId)) { 13866 try { 13867 observer.onPackageDeleted(packageName, 13868 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13869 } catch (RemoteException re) { 13870 } 13871 return; 13872 } 13873 } 13874 13875 if (DEBUG_REMOVE) { 13876 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13877 } 13878 // Queue up an async operation since the package deletion may take a little while. 13879 mHandler.post(new Runnable() { 13880 public void run() { 13881 mHandler.removeCallbacks(this); 13882 final int returnCode = deletePackageX(packageName, userId, flags); 13883 try { 13884 observer.onPackageDeleted(packageName, returnCode, null); 13885 } catch (RemoteException e) { 13886 Log.i(TAG, "Observer no longer exists."); 13887 } //end catch 13888 } //end run 13889 }); 13890 } 13891 13892 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13893 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13894 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13895 try { 13896 if (dpm != null) { 13897 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13898 /* callingUserOnly =*/ false); 13899 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13900 : deviceOwnerComponentName.getPackageName(); 13901 // Does the package contains the device owner? 13902 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13903 // this check is probably not needed, since DO should be registered as a device 13904 // admin on some user too. (Original bug for this: b/17657954) 13905 if (packageName.equals(deviceOwnerPackageName)) { 13906 return true; 13907 } 13908 // Does it contain a device admin for any user? 13909 int[] users; 13910 if (userId == UserHandle.USER_ALL) { 13911 users = sUserManager.getUserIds(); 13912 } else { 13913 users = new int[]{userId}; 13914 } 13915 for (int i = 0; i < users.length; ++i) { 13916 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13917 return true; 13918 } 13919 } 13920 } 13921 } catch (RemoteException e) { 13922 } 13923 return false; 13924 } 13925 13926 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13927 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13928 } 13929 13930 /** 13931 * This method is an internal method that could be get invoked either 13932 * to delete an installed package or to clean up a failed installation. 13933 * After deleting an installed package, a broadcast is sent to notify any 13934 * listeners that the package has been installed. For cleaning up a failed 13935 * installation, the broadcast is not necessary since the package's 13936 * installation wouldn't have sent the initial broadcast either 13937 * The key steps in deleting a package are 13938 * deleting the package information in internal structures like mPackages, 13939 * deleting the packages base directories through installd 13940 * updating mSettings to reflect current status 13941 * persisting settings for later use 13942 * sending a broadcast if necessary 13943 */ 13944 private int deletePackageX(String packageName, int userId, int flags) { 13945 final PackageRemovedInfo info = new PackageRemovedInfo(); 13946 final boolean res; 13947 13948 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13949 ? UserHandle.ALL : new UserHandle(userId); 13950 13951 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13952 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13953 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13954 } 13955 13956 boolean removedForAllUsers = false; 13957 boolean systemUpdate = false; 13958 13959 PackageParser.Package uninstalledPkg; 13960 13961 // for the uninstall-updates case and restricted profiles, remember the per- 13962 // userhandle installed state 13963 int[] allUsers; 13964 boolean[] perUserInstalled; 13965 synchronized (mPackages) { 13966 uninstalledPkg = mPackages.get(packageName); 13967 PackageSetting ps = mSettings.mPackages.get(packageName); 13968 allUsers = sUserManager.getUserIds(); 13969 perUserInstalled = new boolean[allUsers.length]; 13970 for (int i = 0; i < allUsers.length; i++) { 13971 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13972 } 13973 } 13974 13975 synchronized (mInstallLock) { 13976 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13977 res = deletePackageLI(packageName, removeForUser, true, allUsers, perUserInstalled, 13978 flags | REMOVE_CHATTY, info, true, null); 13979 systemUpdate = info.isRemovedPackageSystemUpdate; 13980 synchronized (mPackages) { 13981 if (res) { 13982 if (!systemUpdate && mPackages.get(packageName) == null) { 13983 removedForAllUsers = true; 13984 } 13985 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg); 13986 } 13987 } 13988 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13989 + " removedForAllUsers=" + removedForAllUsers); 13990 } 13991 13992 if (res) { 13993 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13994 13995 // If the removed package was a system update, the old system package 13996 // was re-enabled; we need to broadcast this information 13997 if (systemUpdate) { 13998 Bundle extras = new Bundle(1); 13999 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 14000 ? info.removedAppId : info.uid); 14001 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14002 14003 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 14004 extras, 0, null, null, null); 14005 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 14006 extras, 0, null, null, null); 14007 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14008 null, 0, packageName, null, null); 14009 } 14010 } 14011 // Force a gc here. 14012 Runtime.getRuntime().gc(); 14013 // Delete the resources here after sending the broadcast to let 14014 // other processes clean up before deleting resources. 14015 if (info.args != null) { 14016 synchronized (mInstallLock) { 14017 info.args.doPostDeleteLI(true); 14018 } 14019 } 14020 14021 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14022 } 14023 14024 class PackageRemovedInfo { 14025 String removedPackage; 14026 int uid = -1; 14027 int removedAppId = -1; 14028 int[] removedUsers = null; 14029 boolean isRemovedPackageSystemUpdate = false; 14030 // Clean up resources deleted packages. 14031 InstallArgs args = null; 14032 14033 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 14034 Bundle extras = new Bundle(1); 14035 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14036 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 14037 if (replacing) { 14038 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14039 } 14040 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14041 if (removedPackage != null) { 14042 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14043 extras, 0, null, null, removedUsers); 14044 if (fullRemove && !replacing) { 14045 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 14046 extras, 0, null, null, removedUsers); 14047 } 14048 } 14049 if (removedAppId >= 0) { 14050 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 14051 removedUsers); 14052 } 14053 } 14054 } 14055 14056 /* 14057 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 14058 * flag is not set, the data directory is removed as well. 14059 * make sure this flag is set for partially installed apps. If not its meaningless to 14060 * delete a partially installed application. 14061 */ 14062 private void removePackageDataLI(PackageSetting ps, 14063 int[] allUserHandles, boolean[] perUserInstalled, 14064 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 14065 String packageName = ps.name; 14066 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 14067 removePackageSettingLI(ps, (flags&REMOVE_CHATTY) != 0); 14068 // Retrieve object to delete permissions for shared user later on 14069 final PackageSetting deletedPs; 14070 // reader 14071 synchronized (mPackages) { 14072 deletedPs = mSettings.mPackages.get(packageName); 14073 if (outInfo != null) { 14074 outInfo.removedPackage = packageName; 14075 outInfo.removedUsers = deletedPs != null 14076 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 14077 : null; 14078 } 14079 } 14080 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14081 removeDataDirsLI(ps.volumeUuid, packageName); 14082 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 14083 } 14084 // writer 14085 synchronized (mPackages) { 14086 if (deletedPs != null) { 14087 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14088 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 14089 clearDefaultBrowserIfNeeded(packageName); 14090 if (outInfo != null) { 14091 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 14092 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 14093 } 14094 updatePermissionsLPw(deletedPs.name, null, 0); 14095 if (deletedPs.sharedUser != null) { 14096 // Remove permissions associated with package. Since runtime 14097 // permissions are per user we have to kill the removed package 14098 // or packages running under the shared user of the removed 14099 // package if revoking the permissions requested only by the removed 14100 // package is successful and this causes a change in gids. 14101 for (int userId : UserManagerService.getInstance().getUserIds()) { 14102 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 14103 userId); 14104 if (userIdToKill == UserHandle.USER_ALL 14105 || userIdToKill >= UserHandle.USER_SYSTEM) { 14106 // If gids changed for this user, kill all affected packages. 14107 mHandler.post(new Runnable() { 14108 @Override 14109 public void run() { 14110 // This has to happen with no lock held. 14111 killApplication(deletedPs.name, deletedPs.appId, 14112 KILL_APP_REASON_GIDS_CHANGED); 14113 } 14114 }); 14115 break; 14116 } 14117 } 14118 } 14119 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 14120 } 14121 // make sure to preserve per-user disabled state if this removal was just 14122 // a downgrade of a system app to the factory package 14123 if (allUserHandles != null && perUserInstalled != null) { 14124 if (DEBUG_REMOVE) { 14125 Slog.d(TAG, "Propagating install state across downgrade"); 14126 } 14127 for (int i = 0; i < allUserHandles.length; i++) { 14128 if (DEBUG_REMOVE) { 14129 Slog.d(TAG, " user " + allUserHandles[i] 14130 + " => " + perUserInstalled[i]); 14131 } 14132 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 14133 } 14134 } 14135 } 14136 // can downgrade to reader 14137 if (writeSettings) { 14138 // Save settings now 14139 mSettings.writeLPr(); 14140 } 14141 } 14142 if (outInfo != null) { 14143 // A user ID was deleted here. Go through all users and remove it 14144 // from KeyStore. 14145 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 14146 } 14147 } 14148 14149 static boolean locationIsPrivileged(File path) { 14150 try { 14151 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 14152 .getCanonicalPath(); 14153 return path.getCanonicalPath().startsWith(privilegedAppDir); 14154 } catch (IOException e) { 14155 Slog.e(TAG, "Unable to access code path " + path); 14156 } 14157 return false; 14158 } 14159 14160 /* 14161 * Tries to delete system package. 14162 */ 14163 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 14164 PackageSetting deletedPs, int[] allUserHandles, boolean[] perUserInstalled, 14165 int flags, PackageRemovedInfo outInfo, boolean writeSettings, 14166 PackageParser.Package replacingPackage) { 14167 if (deletedPkg.parentPackage != null) { 14168 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 14169 return false; 14170 } 14171 14172 final boolean applyUserRestrictions 14173 = (allUserHandles != null) && (perUserInstalled != null); 14174 final PackageSetting disabledPs; 14175 // Confirm if the system package has been updated 14176 // An updated system app can be deleted. This will also have to restore 14177 // the system pkg from system partition 14178 // reader 14179 synchronized (mPackages) { 14180 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPkg.packageName); 14181 } 14182 14183 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 14184 + " disabledPs=" + disabledPs); 14185 14186 if (disabledPs == null) { 14187 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 14188 return false; 14189 } else if (DEBUG_REMOVE) { 14190 Slog.d(TAG, "Deleting system pkg from data partition"); 14191 } 14192 14193 if (DEBUG_REMOVE) { 14194 if (applyUserRestrictions) { 14195 Slog.d(TAG, "Remembering install states:"); 14196 for (int i = 0; i < allUserHandles.length; i++) { 14197 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 14198 } 14199 } 14200 } 14201 14202 // Delete the updated package 14203 outInfo.isRemovedPackageSystemUpdate = true; 14204 if (disabledPs.versionCode < deletedPs.versionCode) { 14205 // Delete data for downgrades 14206 flags &= ~PackageManager.DELETE_KEEP_DATA; 14207 } else { 14208 // Preserve data by setting flag 14209 flags |= PackageManager.DELETE_KEEP_DATA; 14210 } 14211 boolean ret = deleteInstalledPackageLI(deletedPkg, true, flags, allUserHandles, 14212 perUserInstalled, outInfo, writeSettings, replacingPackage); 14213 if (!ret) { 14214 return false; 14215 } 14216 14217 // writer 14218 synchronized (mPackages) { 14219 // Reinstate the old system package 14220 enableSystemPackageLPw(disabledPs.pkg); 14221 // Remove any native libraries from the upgraded package. 14222 removeNativeBinariesLI(deletedPkg); 14223 } 14224 14225 // Install the system package 14226 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 14227 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 14228 if (locationIsPrivileged(disabledPs.codePath)) { 14229 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 14230 } 14231 14232 final PackageParser.Package newPkg; 14233 try { 14234 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 14235 } catch (PackageManagerException e) { 14236 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 14237 + e.getMessage()); 14238 return false; 14239 } 14240 14241 prepareAppDataAfterInstall(newPkg); 14242 14243 // writer 14244 synchronized (mPackages) { 14245 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 14246 14247 // Propagate the permissions state as we do not want to drop on the floor 14248 // runtime permissions. The update permissions method below will take 14249 // care of removing obsolete permissions and grant install permissions. 14250 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 14251 updatePermissionsLPw(newPkg.packageName, newPkg, 14252 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 14253 14254 if (applyUserRestrictions) { 14255 if (DEBUG_REMOVE) { 14256 Slog.d(TAG, "Propagating install state across reinstall"); 14257 } 14258 for (int i = 0; i < allUserHandles.length; i++) { 14259 if (DEBUG_REMOVE) { 14260 Slog.d(TAG, " user " + allUserHandles[i] 14261 + " => " + perUserInstalled[i]); 14262 } 14263 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 14264 14265 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 14266 } 14267 // Regardless of writeSettings we need to ensure that this restriction 14268 // state propagation is persisted 14269 mSettings.writeAllUsersPackageRestrictionsLPr(); 14270 } 14271 // can downgrade to reader here 14272 if (writeSettings) { 14273 mSettings.writeLPr(); 14274 } 14275 } 14276 return true; 14277 } 14278 14279 private boolean deleteInstalledPackageLI(PackageParser.Package pkg, 14280 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 14281 boolean[] perUserInstalled, PackageRemovedInfo outInfo, boolean writeSettings, 14282 PackageParser.Package replacingPackage) { 14283 PackageSetting ps = null; 14284 14285 synchronized (mPackages) { 14286 pkg = mPackages.get(pkg.packageName); 14287 if (pkg == null) { 14288 return false; 14289 } 14290 14291 ps = mSettings.mPackages.get(pkg.packageName); 14292 if (ps == null) { 14293 return false; 14294 } 14295 14296 if (outInfo != null) { 14297 outInfo.uid = ps.appId; 14298 } 14299 } 14300 14301 // Delete package data from internal structures and also remove data if flag is set 14302 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, 14303 writeSettings); 14304 14305 // Delete the child packages data 14306 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14307 for (int i = 0; i < childCount; i++) { 14308 PackageSetting childPs; 14309 synchronized (mPackages) { 14310 childPs = mSettings.peekPackageLPr(pkg.childPackages.get(i).packageName); 14311 } 14312 if (childPs != null) { 14313 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 14314 && (replacingPackage != null 14315 && !replacingPackage.hasChildPackage(childPs.name)) 14316 ? flags & ~DELETE_KEEP_DATA : flags; 14317 removePackageDataLI(childPs, allUserHandles, perUserInstalled, outInfo, 14318 deleteFlags, writeSettings); 14319 } 14320 } 14321 14322 // Delete application code and resources only for parent packages 14323 if (ps.pkg.parentPackage == null) { 14324 if (deleteCodeAndResources && (outInfo != null)) { 14325 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 14326 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 14327 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 14328 } 14329 } 14330 14331 return true; 14332 } 14333 14334 @Override 14335 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 14336 int userId) { 14337 mContext.enforceCallingOrSelfPermission( 14338 android.Manifest.permission.DELETE_PACKAGES, null); 14339 synchronized (mPackages) { 14340 PackageSetting ps = mSettings.mPackages.get(packageName); 14341 if (ps == null) { 14342 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 14343 return false; 14344 } 14345 if (!ps.getInstalled(userId)) { 14346 // Can't block uninstall for an app that is not installed or enabled. 14347 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 14348 return false; 14349 } 14350 ps.setBlockUninstall(blockUninstall, userId); 14351 mSettings.writePackageRestrictionsLPr(userId); 14352 } 14353 return true; 14354 } 14355 14356 @Override 14357 public boolean getBlockUninstallForUser(String packageName, int userId) { 14358 synchronized (mPackages) { 14359 PackageSetting ps = mSettings.mPackages.get(packageName); 14360 if (ps == null) { 14361 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 14362 return false; 14363 } 14364 return ps.getBlockUninstall(userId); 14365 } 14366 } 14367 14368 @Override 14369 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 14370 int callingUid = Binder.getCallingUid(); 14371 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 14372 throw new SecurityException( 14373 "setRequiredForSystemUser can only be run by the system or root"); 14374 } 14375 synchronized (mPackages) { 14376 PackageSetting ps = mSettings.mPackages.get(packageName); 14377 if (ps == null) { 14378 Log.w(TAG, "Package doesn't exist: " + packageName); 14379 return false; 14380 } 14381 if (systemUserApp) { 14382 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14383 } else { 14384 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14385 } 14386 mSettings.writeLPr(); 14387 } 14388 return true; 14389 } 14390 14391 /* 14392 * This method handles package deletion in general 14393 */ 14394 private boolean deletePackageLI(String packageName, UserHandle user, 14395 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 14396 int flags, PackageRemovedInfo outInfo, boolean writeSettings, 14397 PackageParser.Package replacingPackage) { 14398 if (packageName == null) { 14399 Slog.w(TAG, "Attempt to delete null packageName."); 14400 return false; 14401 } 14402 14403 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 14404 14405 PackageSetting ps; 14406 14407 synchronized (mPackages) { 14408 ps = mSettings.mPackages.get(packageName); 14409 if (ps == null) { 14410 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14411 return false; 14412 } 14413 14414 if (ps.pkg.parentPackage != null && (!isSystemApp(ps) 14415 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 14416 if (DEBUG_REMOVE) { 14417 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 14418 + ((user == null) ? UserHandle.USER_ALL : user)); 14419 } 14420 final int removedUserId = (user != null) ? user.getIdentifier() 14421 : UserHandle.USER_ALL; 14422 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 14423 return false; 14424 } 14425 markPackageUninstalledForUserLPw(ps, user); 14426 scheduleWritePackageRestrictionsLocked(user); 14427 return true; 14428 } 14429 } 14430 14431 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 14432 && user.getIdentifier() != UserHandle.USER_ALL)) { 14433 // The caller is asking that the package only be deleted for a single 14434 // user. To do this, we just mark its uninstalled state and delete 14435 // its data. If this is a system app, we only allow this to happen if 14436 // they have set the special DELETE_SYSTEM_APP which requests different 14437 // semantics than normal for uninstalling system apps. 14438 markPackageUninstalledForUserLPw(ps, user); 14439 14440 if (!isSystemApp(ps)) { 14441 // Do not uninstall the APK if an app should be cached 14442 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 14443 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 14444 // Other user still have this package installed, so all 14445 // we need to do is clear this user's data and save that 14446 // it is uninstalled. 14447 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 14448 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14449 return false; 14450 } 14451 scheduleWritePackageRestrictionsLocked(user); 14452 return true; 14453 } else { 14454 // We need to set it back to 'installed' so the uninstall 14455 // broadcasts will be sent correctly. 14456 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 14457 ps.setInstalled(true, user.getIdentifier()); 14458 } 14459 } else { 14460 // This is a system app, so we assume that the 14461 // other users still have this package installed, so all 14462 // we need to do is clear this user's data and save that 14463 // it is uninstalled. 14464 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 14465 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14466 return false; 14467 } 14468 scheduleWritePackageRestrictionsLocked(user); 14469 return true; 14470 } 14471 } 14472 14473 boolean ret = false; 14474 if (isSystemApp(ps)) { 14475 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 14476 // When an updated system application is deleted we delete the existing resources as well and 14477 // fall back to existing code in system partition 14478 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, perUserInstalled, 14479 flags, outInfo, writeSettings, replacingPackage); 14480 } else { 14481 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 14482 // Kill application pre-emptively especially for apps on sd. 14483 killApplication(packageName, ps.appId, "uninstall pkg"); 14484 ret = deleteInstalledPackageLI(ps.pkg, deleteCodeAndResources, flags, allUserHandles, 14485 perUserInstalled, outInfo, writeSettings, replacingPackage); 14486 } 14487 14488 return ret; 14489 } 14490 14491 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 14492 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 14493 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 14494 for (int nextUserId : userIds) { 14495 if (DEBUG_REMOVE) { 14496 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 14497 } 14498 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 14499 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 14500 false /*hidden*/, false /*suspended*/, null, null, null, 14501 false /*blockUninstall*/, 14502 ps.readUserState(nextUserId).domainVerificationStatus, 0); 14503 } 14504 } 14505 14506 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 14507 PackageRemovedInfo outInfo) { 14508 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 14509 : new int[] {userId}; 14510 for (int nextUserId : userIds) { 14511 if (DEBUG_REMOVE) { 14512 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 14513 + nextUserId); 14514 } 14515 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 14516 try { 14517 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 14518 } catch (InstallerException e) { 14519 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 14520 return false; 14521 } 14522 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 14523 schedulePackageCleaning(ps.name, nextUserId, false); 14524 synchronized (mPackages) { 14525 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 14526 scheduleWritePackageRestrictionsLocked(nextUserId); 14527 } 14528 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 14529 } 14530 } 14531 14532 if (outInfo != null) { 14533 outInfo.removedPackage = ps.name; 14534 outInfo.removedAppId = ps.appId; 14535 outInfo.removedUsers = userIds; 14536 } 14537 14538 return true; 14539 } 14540 14541 private final class ClearStorageConnection implements ServiceConnection { 14542 IMediaContainerService mContainerService; 14543 14544 @Override 14545 public void onServiceConnected(ComponentName name, IBinder service) { 14546 synchronized (this) { 14547 mContainerService = IMediaContainerService.Stub.asInterface(service); 14548 notifyAll(); 14549 } 14550 } 14551 14552 @Override 14553 public void onServiceDisconnected(ComponentName name) { 14554 } 14555 } 14556 14557 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 14558 final boolean mounted; 14559 if (Environment.isExternalStorageEmulated()) { 14560 mounted = true; 14561 } else { 14562 final String status = Environment.getExternalStorageState(); 14563 14564 mounted = status.equals(Environment.MEDIA_MOUNTED) 14565 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 14566 } 14567 14568 if (!mounted) { 14569 return; 14570 } 14571 14572 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 14573 int[] users; 14574 if (userId == UserHandle.USER_ALL) { 14575 users = sUserManager.getUserIds(); 14576 } else { 14577 users = new int[] { userId }; 14578 } 14579 final ClearStorageConnection conn = new ClearStorageConnection(); 14580 if (mContext.bindServiceAsUser( 14581 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 14582 try { 14583 for (int curUser : users) { 14584 long timeout = SystemClock.uptimeMillis() + 5000; 14585 synchronized (conn) { 14586 long now = SystemClock.uptimeMillis(); 14587 while (conn.mContainerService == null && now < timeout) { 14588 try { 14589 conn.wait(timeout - now); 14590 } catch (InterruptedException e) { 14591 } 14592 } 14593 } 14594 if (conn.mContainerService == null) { 14595 return; 14596 } 14597 14598 final UserEnvironment userEnv = new UserEnvironment(curUser); 14599 clearDirectory(conn.mContainerService, 14600 userEnv.buildExternalStorageAppCacheDirs(packageName)); 14601 if (allData) { 14602 clearDirectory(conn.mContainerService, 14603 userEnv.buildExternalStorageAppDataDirs(packageName)); 14604 clearDirectory(conn.mContainerService, 14605 userEnv.buildExternalStorageAppMediaDirs(packageName)); 14606 } 14607 } 14608 } finally { 14609 mContext.unbindService(conn); 14610 } 14611 } 14612 } 14613 14614 @Override 14615 public void clearApplicationUserData(final String packageName, 14616 final IPackageDataObserver observer, final int userId) { 14617 mContext.enforceCallingOrSelfPermission( 14618 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 14619 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 14620 // Queue up an async operation since the package deletion may take a little while. 14621 mHandler.post(new Runnable() { 14622 public void run() { 14623 mHandler.removeCallbacks(this); 14624 final boolean succeeded; 14625 synchronized (mInstallLock) { 14626 succeeded = clearApplicationUserDataLI(packageName, userId); 14627 } 14628 clearExternalStorageDataSync(packageName, userId, true); 14629 if (succeeded) { 14630 // invoke DeviceStorageMonitor's update method to clear any notifications 14631 DeviceStorageMonitorInternal 14632 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14633 if (dsm != null) { 14634 dsm.checkMemory(); 14635 } 14636 } 14637 if(observer != null) { 14638 try { 14639 observer.onRemoveCompleted(packageName, succeeded); 14640 } catch (RemoteException e) { 14641 Log.i(TAG, "Observer no longer exists."); 14642 } 14643 } //end if observer 14644 } //end run 14645 }); 14646 } 14647 14648 private boolean clearApplicationUserDataLI(String packageName, int userId) { 14649 if (packageName == null) { 14650 Slog.w(TAG, "Attempt to delete null packageName."); 14651 return false; 14652 } 14653 14654 // Try finding details about the requested package 14655 PackageParser.Package pkg; 14656 synchronized (mPackages) { 14657 pkg = mPackages.get(packageName); 14658 if (pkg == null) { 14659 final PackageSetting ps = mSettings.mPackages.get(packageName); 14660 if (ps != null) { 14661 pkg = ps.pkg; 14662 } 14663 } 14664 14665 if (pkg == null) { 14666 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14667 return false; 14668 } 14669 14670 PackageSetting ps = (PackageSetting) pkg.mExtras; 14671 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14672 } 14673 14674 // Always delete data directories for package, even if we found no other 14675 // record of app. This helps users recover from UID mismatches without 14676 // resorting to a full data wipe. 14677 // TODO: triage flags as part of 26466827 14678 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 14679 try { 14680 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 14681 } catch (InstallerException e) { 14682 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 14683 return false; 14684 } 14685 14686 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14687 removeKeystoreDataIfNeeded(userId, appId); 14688 14689 // Create a native library symlink only if we have native libraries 14690 // and if the native libraries are 32 bit libraries. We do not provide 14691 // this symlink for 64 bit libraries. 14692 if (pkg.applicationInfo.primaryCpuAbi != null && 14693 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 14694 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 14695 try { 14696 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 14697 nativeLibPath, userId); 14698 } catch (InstallerException e) { 14699 Slog.w(TAG, "Failed linking native library dir", e); 14700 return false; 14701 } 14702 } 14703 14704 return true; 14705 } 14706 14707 /** 14708 * Reverts user permission state changes (permissions and flags) in 14709 * all packages for a given user. 14710 * 14711 * @param userId The device user for which to do a reset. 14712 */ 14713 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 14714 final int packageCount = mPackages.size(); 14715 for (int i = 0; i < packageCount; i++) { 14716 PackageParser.Package pkg = mPackages.valueAt(i); 14717 PackageSetting ps = (PackageSetting) pkg.mExtras; 14718 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14719 } 14720 } 14721 14722 /** 14723 * Reverts user permission state changes (permissions and flags). 14724 * 14725 * @param ps The package for which to reset. 14726 * @param userId The device user for which to do a reset. 14727 */ 14728 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 14729 final PackageSetting ps, final int userId) { 14730 if (ps.pkg == null) { 14731 return; 14732 } 14733 14734 // These are flags that can change base on user actions. 14735 final int userSettableMask = FLAG_PERMISSION_USER_SET 14736 | FLAG_PERMISSION_USER_FIXED 14737 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 14738 | FLAG_PERMISSION_REVIEW_REQUIRED; 14739 14740 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 14741 | FLAG_PERMISSION_POLICY_FIXED; 14742 14743 boolean writeInstallPermissions = false; 14744 boolean writeRuntimePermissions = false; 14745 14746 final int permissionCount = ps.pkg.requestedPermissions.size(); 14747 for (int i = 0; i < permissionCount; i++) { 14748 String permission = ps.pkg.requestedPermissions.get(i); 14749 14750 BasePermission bp = mSettings.mPermissions.get(permission); 14751 if (bp == null) { 14752 continue; 14753 } 14754 14755 // If shared user we just reset the state to which only this app contributed. 14756 if (ps.sharedUser != null) { 14757 boolean used = false; 14758 final int packageCount = ps.sharedUser.packages.size(); 14759 for (int j = 0; j < packageCount; j++) { 14760 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 14761 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 14762 && pkg.pkg.requestedPermissions.contains(permission)) { 14763 used = true; 14764 break; 14765 } 14766 } 14767 if (used) { 14768 continue; 14769 } 14770 } 14771 14772 PermissionsState permissionsState = ps.getPermissionsState(); 14773 14774 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 14775 14776 // Always clear the user settable flags. 14777 final boolean hasInstallState = permissionsState.getInstallPermissionState( 14778 bp.name) != null; 14779 // If permission review is enabled and this is a legacy app, mark the 14780 // permission as requiring a review as this is the initial state. 14781 int flags = 0; 14782 if (Build.PERMISSIONS_REVIEW_REQUIRED 14783 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 14784 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 14785 } 14786 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 14787 if (hasInstallState) { 14788 writeInstallPermissions = true; 14789 } else { 14790 writeRuntimePermissions = true; 14791 } 14792 } 14793 14794 // Below is only runtime permission handling. 14795 if (!bp.isRuntime()) { 14796 continue; 14797 } 14798 14799 // Never clobber system or policy. 14800 if ((oldFlags & policyOrSystemFlags) != 0) { 14801 continue; 14802 } 14803 14804 // If this permission was granted by default, make sure it is. 14805 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 14806 if (permissionsState.grantRuntimePermission(bp, userId) 14807 != PERMISSION_OPERATION_FAILURE) { 14808 writeRuntimePermissions = true; 14809 } 14810 // If permission review is enabled the permissions for a legacy apps 14811 // are represented as constantly granted runtime ones, so don't revoke. 14812 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 14813 // Otherwise, reset the permission. 14814 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 14815 switch (revokeResult) { 14816 case PERMISSION_OPERATION_SUCCESS: { 14817 writeRuntimePermissions = true; 14818 } break; 14819 14820 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 14821 writeRuntimePermissions = true; 14822 final int appId = ps.appId; 14823 mHandler.post(new Runnable() { 14824 @Override 14825 public void run() { 14826 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 14827 } 14828 }); 14829 } break; 14830 } 14831 } 14832 } 14833 14834 // Synchronously write as we are taking permissions away. 14835 if (writeRuntimePermissions) { 14836 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 14837 } 14838 14839 // Synchronously write as we are taking permissions away. 14840 if (writeInstallPermissions) { 14841 mSettings.writeLPr(); 14842 } 14843 } 14844 14845 /** 14846 * Remove entries from the keystore daemon. Will only remove it if the 14847 * {@code appId} is valid. 14848 */ 14849 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 14850 if (appId < 0) { 14851 return; 14852 } 14853 14854 final KeyStore keyStore = KeyStore.getInstance(); 14855 if (keyStore != null) { 14856 if (userId == UserHandle.USER_ALL) { 14857 for (final int individual : sUserManager.getUserIds()) { 14858 keyStore.clearUid(UserHandle.getUid(individual, appId)); 14859 } 14860 } else { 14861 keyStore.clearUid(UserHandle.getUid(userId, appId)); 14862 } 14863 } else { 14864 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 14865 } 14866 } 14867 14868 @Override 14869 public void deleteApplicationCacheFiles(final String packageName, 14870 final IPackageDataObserver observer) { 14871 mContext.enforceCallingOrSelfPermission( 14872 android.Manifest.permission.DELETE_CACHE_FILES, null); 14873 // Queue up an async operation since the package deletion may take a little while. 14874 final int userId = UserHandle.getCallingUserId(); 14875 mHandler.post(new Runnable() { 14876 public void run() { 14877 mHandler.removeCallbacks(this); 14878 final boolean succeded; 14879 synchronized (mInstallLock) { 14880 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14881 } 14882 clearExternalStorageDataSync(packageName, userId, false); 14883 if (observer != null) { 14884 try { 14885 observer.onRemoveCompleted(packageName, succeded); 14886 } catch (RemoteException e) { 14887 Log.i(TAG, "Observer no longer exists."); 14888 } 14889 } //end if observer 14890 } //end run 14891 }); 14892 } 14893 14894 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14895 if (packageName == null) { 14896 Slog.w(TAG, "Attempt to delete null packageName."); 14897 return false; 14898 } 14899 PackageParser.Package p; 14900 synchronized (mPackages) { 14901 p = mPackages.get(packageName); 14902 } 14903 if (p == null) { 14904 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14905 return false; 14906 } 14907 final ApplicationInfo applicationInfo = p.applicationInfo; 14908 if (applicationInfo == null) { 14909 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14910 return false; 14911 } 14912 // TODO: triage flags as part of 26466827 14913 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 14914 try { 14915 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 14916 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 14917 } catch (InstallerException e) { 14918 Slog.w(TAG, "Couldn't remove cache files for package " 14919 + packageName + " u" + userId, e); 14920 return false; 14921 } 14922 return true; 14923 } 14924 14925 @Override 14926 public void getPackageSizeInfo(final String packageName, int userHandle, 14927 final IPackageStatsObserver observer) { 14928 mContext.enforceCallingOrSelfPermission( 14929 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14930 if (packageName == null) { 14931 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14932 } 14933 14934 PackageStats stats = new PackageStats(packageName, userHandle); 14935 14936 /* 14937 * Queue up an async operation since the package measurement may take a 14938 * little while. 14939 */ 14940 Message msg = mHandler.obtainMessage(INIT_COPY); 14941 msg.obj = new MeasureParams(stats, observer); 14942 mHandler.sendMessage(msg); 14943 } 14944 14945 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14946 PackageStats pStats) { 14947 if (packageName == null) { 14948 Slog.w(TAG, "Attempt to get size of null packageName."); 14949 return false; 14950 } 14951 PackageParser.Package p; 14952 boolean dataOnly = false; 14953 String libDirRoot = null; 14954 String asecPath = null; 14955 PackageSetting ps = null; 14956 synchronized (mPackages) { 14957 p = mPackages.get(packageName); 14958 ps = mSettings.mPackages.get(packageName); 14959 if(p == null) { 14960 dataOnly = true; 14961 if((ps == null) || (ps.pkg == null)) { 14962 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14963 return false; 14964 } 14965 p = ps.pkg; 14966 } 14967 if (ps != null) { 14968 libDirRoot = ps.legacyNativeLibraryPathString; 14969 } 14970 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14971 final long token = Binder.clearCallingIdentity(); 14972 try { 14973 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14974 if (secureContainerId != null) { 14975 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14976 } 14977 } finally { 14978 Binder.restoreCallingIdentity(token); 14979 } 14980 } 14981 } 14982 String publicSrcDir = null; 14983 if(!dataOnly) { 14984 final ApplicationInfo applicationInfo = p.applicationInfo; 14985 if (applicationInfo == null) { 14986 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14987 return false; 14988 } 14989 if (p.isForwardLocked()) { 14990 publicSrcDir = applicationInfo.getBaseResourcePath(); 14991 } 14992 } 14993 // TODO: extend to measure size of split APKs 14994 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14995 // not just the first level. 14996 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14997 // just the primary. 14998 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14999 15000 String apkPath; 15001 File packageDir = new File(p.codePath); 15002 15003 if (packageDir.isDirectory() && p.canHaveOatDir()) { 15004 apkPath = packageDir.getAbsolutePath(); 15005 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 15006 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 15007 libDirRoot = null; 15008 } 15009 } else { 15010 apkPath = p.baseCodePath; 15011 } 15012 15013 // TODO: triage flags as part of 26466827 15014 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15015 try { 15016 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 15017 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 15018 } catch (InstallerException e) { 15019 return false; 15020 } 15021 15022 // Fix-up for forward-locked applications in ASEC containers. 15023 if (!isExternal(p)) { 15024 pStats.codeSize += pStats.externalCodeSize; 15025 pStats.externalCodeSize = 0L; 15026 } 15027 15028 return true; 15029 } 15030 15031 15032 @Override 15033 public void addPackageToPreferred(String packageName) { 15034 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 15035 } 15036 15037 @Override 15038 public void removePackageFromPreferred(String packageName) { 15039 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 15040 } 15041 15042 @Override 15043 public List<PackageInfo> getPreferredPackages(int flags) { 15044 return new ArrayList<PackageInfo>(); 15045 } 15046 15047 private int getUidTargetSdkVersionLockedLPr(int uid) { 15048 Object obj = mSettings.getUserIdLPr(uid); 15049 if (obj instanceof SharedUserSetting) { 15050 final SharedUserSetting sus = (SharedUserSetting) obj; 15051 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 15052 final Iterator<PackageSetting> it = sus.packages.iterator(); 15053 while (it.hasNext()) { 15054 final PackageSetting ps = it.next(); 15055 if (ps.pkg != null) { 15056 int v = ps.pkg.applicationInfo.targetSdkVersion; 15057 if (v < vers) vers = v; 15058 } 15059 } 15060 return vers; 15061 } else if (obj instanceof PackageSetting) { 15062 final PackageSetting ps = (PackageSetting) obj; 15063 if (ps.pkg != null) { 15064 return ps.pkg.applicationInfo.targetSdkVersion; 15065 } 15066 } 15067 return Build.VERSION_CODES.CUR_DEVELOPMENT; 15068 } 15069 15070 @Override 15071 public void addPreferredActivity(IntentFilter filter, int match, 15072 ComponentName[] set, ComponentName activity, int userId) { 15073 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15074 "Adding preferred"); 15075 } 15076 15077 private void addPreferredActivityInternal(IntentFilter filter, int match, 15078 ComponentName[] set, ComponentName activity, boolean always, int userId, 15079 String opname) { 15080 // writer 15081 int callingUid = Binder.getCallingUid(); 15082 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 15083 if (filter.countActions() == 0) { 15084 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15085 return; 15086 } 15087 synchronized (mPackages) { 15088 if (mContext.checkCallingOrSelfPermission( 15089 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15090 != PackageManager.PERMISSION_GRANTED) { 15091 if (getUidTargetSdkVersionLockedLPr(callingUid) 15092 < Build.VERSION_CODES.FROYO) { 15093 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 15094 + callingUid); 15095 return; 15096 } 15097 mContext.enforceCallingOrSelfPermission( 15098 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15099 } 15100 15101 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 15102 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 15103 + userId + ":"); 15104 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15105 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 15106 scheduleWritePackageRestrictionsLocked(userId); 15107 } 15108 } 15109 15110 @Override 15111 public void replacePreferredActivity(IntentFilter filter, int match, 15112 ComponentName[] set, ComponentName activity, int userId) { 15113 if (filter.countActions() != 1) { 15114 throw new IllegalArgumentException( 15115 "replacePreferredActivity expects filter to have only 1 action."); 15116 } 15117 if (filter.countDataAuthorities() != 0 15118 || filter.countDataPaths() != 0 15119 || filter.countDataSchemes() > 1 15120 || filter.countDataTypes() != 0) { 15121 throw new IllegalArgumentException( 15122 "replacePreferredActivity expects filter to have no data authorities, " + 15123 "paths, or types; and at most one scheme."); 15124 } 15125 15126 final int callingUid = Binder.getCallingUid(); 15127 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 15128 synchronized (mPackages) { 15129 if (mContext.checkCallingOrSelfPermission( 15130 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15131 != PackageManager.PERMISSION_GRANTED) { 15132 if (getUidTargetSdkVersionLockedLPr(callingUid) 15133 < Build.VERSION_CODES.FROYO) { 15134 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 15135 + Binder.getCallingUid()); 15136 return; 15137 } 15138 mContext.enforceCallingOrSelfPermission( 15139 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15140 } 15141 15142 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15143 if (pir != null) { 15144 // Get all of the existing entries that exactly match this filter. 15145 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 15146 if (existing != null && existing.size() == 1) { 15147 PreferredActivity cur = existing.get(0); 15148 if (DEBUG_PREFERRED) { 15149 Slog.i(TAG, "Checking replace of preferred:"); 15150 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15151 if (!cur.mPref.mAlways) { 15152 Slog.i(TAG, " -- CUR; not mAlways!"); 15153 } else { 15154 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 15155 Slog.i(TAG, " -- CUR: mSet=" 15156 + Arrays.toString(cur.mPref.mSetComponents)); 15157 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 15158 Slog.i(TAG, " -- NEW: mMatch=" 15159 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 15160 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 15161 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 15162 } 15163 } 15164 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 15165 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 15166 && cur.mPref.sameSet(set)) { 15167 // Setting the preferred activity to what it happens to be already 15168 if (DEBUG_PREFERRED) { 15169 Slog.i(TAG, "Replacing with same preferred activity " 15170 + cur.mPref.mShortComponent + " for user " 15171 + userId + ":"); 15172 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15173 } 15174 return; 15175 } 15176 } 15177 15178 if (existing != null) { 15179 if (DEBUG_PREFERRED) { 15180 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 15181 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15182 } 15183 for (int i = 0; i < existing.size(); i++) { 15184 PreferredActivity pa = existing.get(i); 15185 if (DEBUG_PREFERRED) { 15186 Slog.i(TAG, "Removing existing preferred activity " 15187 + pa.mPref.mComponent + ":"); 15188 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 15189 } 15190 pir.removeFilter(pa); 15191 } 15192 } 15193 } 15194 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15195 "Replacing preferred"); 15196 } 15197 } 15198 15199 @Override 15200 public void clearPackagePreferredActivities(String packageName) { 15201 final int uid = Binder.getCallingUid(); 15202 // writer 15203 synchronized (mPackages) { 15204 PackageParser.Package pkg = mPackages.get(packageName); 15205 if (pkg == null || pkg.applicationInfo.uid != uid) { 15206 if (mContext.checkCallingOrSelfPermission( 15207 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15208 != PackageManager.PERMISSION_GRANTED) { 15209 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 15210 < Build.VERSION_CODES.FROYO) { 15211 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 15212 + Binder.getCallingUid()); 15213 return; 15214 } 15215 mContext.enforceCallingOrSelfPermission( 15216 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15217 } 15218 } 15219 15220 int user = UserHandle.getCallingUserId(); 15221 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 15222 scheduleWritePackageRestrictionsLocked(user); 15223 } 15224 } 15225 } 15226 15227 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15228 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 15229 ArrayList<PreferredActivity> removed = null; 15230 boolean changed = false; 15231 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15232 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 15233 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15234 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 15235 continue; 15236 } 15237 Iterator<PreferredActivity> it = pir.filterIterator(); 15238 while (it.hasNext()) { 15239 PreferredActivity pa = it.next(); 15240 // Mark entry for removal only if it matches the package name 15241 // and the entry is of type "always". 15242 if (packageName == null || 15243 (pa.mPref.mComponent.getPackageName().equals(packageName) 15244 && pa.mPref.mAlways)) { 15245 if (removed == null) { 15246 removed = new ArrayList<PreferredActivity>(); 15247 } 15248 removed.add(pa); 15249 } 15250 } 15251 if (removed != null) { 15252 for (int j=0; j<removed.size(); j++) { 15253 PreferredActivity pa = removed.get(j); 15254 pir.removeFilter(pa); 15255 } 15256 changed = true; 15257 } 15258 } 15259 return changed; 15260 } 15261 15262 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15263 private void clearIntentFilterVerificationsLPw(int userId) { 15264 final int packageCount = mPackages.size(); 15265 for (int i = 0; i < packageCount; i++) { 15266 PackageParser.Package pkg = mPackages.valueAt(i); 15267 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 15268 } 15269 } 15270 15271 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15272 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 15273 if (userId == UserHandle.USER_ALL) { 15274 if (mSettings.removeIntentFilterVerificationLPw(packageName, 15275 sUserManager.getUserIds())) { 15276 for (int oneUserId : sUserManager.getUserIds()) { 15277 scheduleWritePackageRestrictionsLocked(oneUserId); 15278 } 15279 } 15280 } else { 15281 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 15282 scheduleWritePackageRestrictionsLocked(userId); 15283 } 15284 } 15285 } 15286 15287 void clearDefaultBrowserIfNeeded(String packageName) { 15288 for (int oneUserId : sUserManager.getUserIds()) { 15289 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 15290 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 15291 if (packageName.equals(defaultBrowserPackageName)) { 15292 setDefaultBrowserPackageName(null, oneUserId); 15293 } 15294 } 15295 } 15296 15297 @Override 15298 public void resetApplicationPreferences(int userId) { 15299 mContext.enforceCallingOrSelfPermission( 15300 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15301 // writer 15302 synchronized (mPackages) { 15303 final long identity = Binder.clearCallingIdentity(); 15304 try { 15305 clearPackagePreferredActivitiesLPw(null, userId); 15306 mSettings.applyDefaultPreferredAppsLPw(this, userId); 15307 // TODO: We have to reset the default SMS and Phone. This requires 15308 // significant refactoring to keep all default apps in the package 15309 // manager (cleaner but more work) or have the services provide 15310 // callbacks to the package manager to request a default app reset. 15311 applyFactoryDefaultBrowserLPw(userId); 15312 clearIntentFilterVerificationsLPw(userId); 15313 primeDomainVerificationsLPw(userId); 15314 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 15315 scheduleWritePackageRestrictionsLocked(userId); 15316 } finally { 15317 Binder.restoreCallingIdentity(identity); 15318 } 15319 } 15320 } 15321 15322 @Override 15323 public int getPreferredActivities(List<IntentFilter> outFilters, 15324 List<ComponentName> outActivities, String packageName) { 15325 15326 int num = 0; 15327 final int userId = UserHandle.getCallingUserId(); 15328 // reader 15329 synchronized (mPackages) { 15330 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15331 if (pir != null) { 15332 final Iterator<PreferredActivity> it = pir.filterIterator(); 15333 while (it.hasNext()) { 15334 final PreferredActivity pa = it.next(); 15335 if (packageName == null 15336 || (pa.mPref.mComponent.getPackageName().equals(packageName) 15337 && pa.mPref.mAlways)) { 15338 if (outFilters != null) { 15339 outFilters.add(new IntentFilter(pa)); 15340 } 15341 if (outActivities != null) { 15342 outActivities.add(pa.mPref.mComponent); 15343 } 15344 } 15345 } 15346 } 15347 } 15348 15349 return num; 15350 } 15351 15352 @Override 15353 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 15354 int userId) { 15355 int callingUid = Binder.getCallingUid(); 15356 if (callingUid != Process.SYSTEM_UID) { 15357 throw new SecurityException( 15358 "addPersistentPreferredActivity can only be run by the system"); 15359 } 15360 if (filter.countActions() == 0) { 15361 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15362 return; 15363 } 15364 synchronized (mPackages) { 15365 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 15366 ":"); 15367 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15368 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 15369 new PersistentPreferredActivity(filter, activity)); 15370 scheduleWritePackageRestrictionsLocked(userId); 15371 } 15372 } 15373 15374 @Override 15375 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 15376 int callingUid = Binder.getCallingUid(); 15377 if (callingUid != Process.SYSTEM_UID) { 15378 throw new SecurityException( 15379 "clearPackagePersistentPreferredActivities can only be run by the system"); 15380 } 15381 ArrayList<PersistentPreferredActivity> removed = null; 15382 boolean changed = false; 15383 synchronized (mPackages) { 15384 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 15385 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 15386 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 15387 .valueAt(i); 15388 if (userId != thisUserId) { 15389 continue; 15390 } 15391 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 15392 while (it.hasNext()) { 15393 PersistentPreferredActivity ppa = it.next(); 15394 // Mark entry for removal only if it matches the package name. 15395 if (ppa.mComponent.getPackageName().equals(packageName)) { 15396 if (removed == null) { 15397 removed = new ArrayList<PersistentPreferredActivity>(); 15398 } 15399 removed.add(ppa); 15400 } 15401 } 15402 if (removed != null) { 15403 for (int j=0; j<removed.size(); j++) { 15404 PersistentPreferredActivity ppa = removed.get(j); 15405 ppir.removeFilter(ppa); 15406 } 15407 changed = true; 15408 } 15409 } 15410 15411 if (changed) { 15412 scheduleWritePackageRestrictionsLocked(userId); 15413 } 15414 } 15415 } 15416 15417 /** 15418 * Common machinery for picking apart a restored XML blob and passing 15419 * it to a caller-supplied functor to be applied to the running system. 15420 */ 15421 private void restoreFromXml(XmlPullParser parser, int userId, 15422 String expectedStartTag, BlobXmlRestorer functor) 15423 throws IOException, XmlPullParserException { 15424 int type; 15425 while ((type = parser.next()) != XmlPullParser.START_TAG 15426 && type != XmlPullParser.END_DOCUMENT) { 15427 } 15428 if (type != XmlPullParser.START_TAG) { 15429 // oops didn't find a start tag?! 15430 if (DEBUG_BACKUP) { 15431 Slog.e(TAG, "Didn't find start tag during restore"); 15432 } 15433 return; 15434 } 15435Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 15436 // this is supposed to be TAG_PREFERRED_BACKUP 15437 if (!expectedStartTag.equals(parser.getName())) { 15438 if (DEBUG_BACKUP) { 15439 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 15440 } 15441 return; 15442 } 15443 15444 // skip interfering stuff, then we're aligned with the backing implementation 15445 while ((type = parser.next()) == XmlPullParser.TEXT) { } 15446Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 15447 functor.apply(parser, userId); 15448 } 15449 15450 private interface BlobXmlRestorer { 15451 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 15452 } 15453 15454 /** 15455 * Non-Binder method, support for the backup/restore mechanism: write the 15456 * full set of preferred activities in its canonical XML format. Returns the 15457 * XML output as a byte array, or null if there is none. 15458 */ 15459 @Override 15460 public byte[] getPreferredActivityBackup(int userId) { 15461 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15462 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 15463 } 15464 15465 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15466 try { 15467 final XmlSerializer serializer = new FastXmlSerializer(); 15468 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15469 serializer.startDocument(null, true); 15470 serializer.startTag(null, TAG_PREFERRED_BACKUP); 15471 15472 synchronized (mPackages) { 15473 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 15474 } 15475 15476 serializer.endTag(null, TAG_PREFERRED_BACKUP); 15477 serializer.endDocument(); 15478 serializer.flush(); 15479 } catch (Exception e) { 15480 if (DEBUG_BACKUP) { 15481 Slog.e(TAG, "Unable to write preferred activities for backup", e); 15482 } 15483 return null; 15484 } 15485 15486 return dataStream.toByteArray(); 15487 } 15488 15489 @Override 15490 public void restorePreferredActivities(byte[] backup, int userId) { 15491 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15492 throw new SecurityException("Only the system may call restorePreferredActivities()"); 15493 } 15494 15495 try { 15496 final XmlPullParser parser = Xml.newPullParser(); 15497 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15498 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 15499 new BlobXmlRestorer() { 15500 @Override 15501 public void apply(XmlPullParser parser, int userId) 15502 throws XmlPullParserException, IOException { 15503 synchronized (mPackages) { 15504 mSettings.readPreferredActivitiesLPw(parser, userId); 15505 } 15506 } 15507 } ); 15508 } catch (Exception e) { 15509 if (DEBUG_BACKUP) { 15510 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15511 } 15512 } 15513 } 15514 15515 /** 15516 * Non-Binder method, support for the backup/restore mechanism: write the 15517 * default browser (etc) settings in its canonical XML format. Returns the default 15518 * browser XML representation as a byte array, or null if there is none. 15519 */ 15520 @Override 15521 public byte[] getDefaultAppsBackup(int userId) { 15522 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15523 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 15524 } 15525 15526 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15527 try { 15528 final XmlSerializer serializer = new FastXmlSerializer(); 15529 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15530 serializer.startDocument(null, true); 15531 serializer.startTag(null, TAG_DEFAULT_APPS); 15532 15533 synchronized (mPackages) { 15534 mSettings.writeDefaultAppsLPr(serializer, userId); 15535 } 15536 15537 serializer.endTag(null, TAG_DEFAULT_APPS); 15538 serializer.endDocument(); 15539 serializer.flush(); 15540 } catch (Exception e) { 15541 if (DEBUG_BACKUP) { 15542 Slog.e(TAG, "Unable to write default apps for backup", e); 15543 } 15544 return null; 15545 } 15546 15547 return dataStream.toByteArray(); 15548 } 15549 15550 @Override 15551 public void restoreDefaultApps(byte[] backup, int userId) { 15552 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15553 throw new SecurityException("Only the system may call restoreDefaultApps()"); 15554 } 15555 15556 try { 15557 final XmlPullParser parser = Xml.newPullParser(); 15558 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15559 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 15560 new BlobXmlRestorer() { 15561 @Override 15562 public void apply(XmlPullParser parser, int userId) 15563 throws XmlPullParserException, IOException { 15564 synchronized (mPackages) { 15565 mSettings.readDefaultAppsLPw(parser, userId); 15566 } 15567 } 15568 } ); 15569 } catch (Exception e) { 15570 if (DEBUG_BACKUP) { 15571 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 15572 } 15573 } 15574 } 15575 15576 @Override 15577 public byte[] getIntentFilterVerificationBackup(int userId) { 15578 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15579 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 15580 } 15581 15582 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15583 try { 15584 final XmlSerializer serializer = new FastXmlSerializer(); 15585 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15586 serializer.startDocument(null, true); 15587 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 15588 15589 synchronized (mPackages) { 15590 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 15591 } 15592 15593 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 15594 serializer.endDocument(); 15595 serializer.flush(); 15596 } catch (Exception e) { 15597 if (DEBUG_BACKUP) { 15598 Slog.e(TAG, "Unable to write default apps for backup", e); 15599 } 15600 return null; 15601 } 15602 15603 return dataStream.toByteArray(); 15604 } 15605 15606 @Override 15607 public void restoreIntentFilterVerification(byte[] backup, int userId) { 15608 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15609 throw new SecurityException("Only the system may call restorePreferredActivities()"); 15610 } 15611 15612 try { 15613 final XmlPullParser parser = Xml.newPullParser(); 15614 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15615 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 15616 new BlobXmlRestorer() { 15617 @Override 15618 public void apply(XmlPullParser parser, int userId) 15619 throws XmlPullParserException, IOException { 15620 synchronized (mPackages) { 15621 mSettings.readAllDomainVerificationsLPr(parser, userId); 15622 mSettings.writeLPr(); 15623 } 15624 } 15625 } ); 15626 } catch (Exception e) { 15627 if (DEBUG_BACKUP) { 15628 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15629 } 15630 } 15631 } 15632 15633 @Override 15634 public byte[] getPermissionGrantBackup(int userId) { 15635 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15636 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 15637 } 15638 15639 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15640 try { 15641 final XmlSerializer serializer = new FastXmlSerializer(); 15642 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15643 serializer.startDocument(null, true); 15644 serializer.startTag(null, TAG_PERMISSION_BACKUP); 15645 15646 synchronized (mPackages) { 15647 serializeRuntimePermissionGrantsLPr(serializer, userId); 15648 } 15649 15650 serializer.endTag(null, TAG_PERMISSION_BACKUP); 15651 serializer.endDocument(); 15652 serializer.flush(); 15653 } catch (Exception e) { 15654 if (DEBUG_BACKUP) { 15655 Slog.e(TAG, "Unable to write default apps for backup", e); 15656 } 15657 return null; 15658 } 15659 15660 return dataStream.toByteArray(); 15661 } 15662 15663 @Override 15664 public void restorePermissionGrants(byte[] backup, int userId) { 15665 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15666 throw new SecurityException("Only the system may call restorePermissionGrants()"); 15667 } 15668 15669 try { 15670 final XmlPullParser parser = Xml.newPullParser(); 15671 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15672 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 15673 new BlobXmlRestorer() { 15674 @Override 15675 public void apply(XmlPullParser parser, int userId) 15676 throws XmlPullParserException, IOException { 15677 synchronized (mPackages) { 15678 processRestoredPermissionGrantsLPr(parser, userId); 15679 } 15680 } 15681 } ); 15682 } catch (Exception e) { 15683 if (DEBUG_BACKUP) { 15684 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15685 } 15686 } 15687 } 15688 15689 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 15690 throws IOException { 15691 serializer.startTag(null, TAG_ALL_GRANTS); 15692 15693 final int N = mSettings.mPackages.size(); 15694 for (int i = 0; i < N; i++) { 15695 final PackageSetting ps = mSettings.mPackages.valueAt(i); 15696 boolean pkgGrantsKnown = false; 15697 15698 PermissionsState packagePerms = ps.getPermissionsState(); 15699 15700 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 15701 final int grantFlags = state.getFlags(); 15702 // only look at grants that are not system/policy fixed 15703 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 15704 final boolean isGranted = state.isGranted(); 15705 // And only back up the user-twiddled state bits 15706 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 15707 final String packageName = mSettings.mPackages.keyAt(i); 15708 if (!pkgGrantsKnown) { 15709 serializer.startTag(null, TAG_GRANT); 15710 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 15711 pkgGrantsKnown = true; 15712 } 15713 15714 final boolean userSet = 15715 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 15716 final boolean userFixed = 15717 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 15718 final boolean revoke = 15719 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 15720 15721 serializer.startTag(null, TAG_PERMISSION); 15722 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 15723 if (isGranted) { 15724 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 15725 } 15726 if (userSet) { 15727 serializer.attribute(null, ATTR_USER_SET, "true"); 15728 } 15729 if (userFixed) { 15730 serializer.attribute(null, ATTR_USER_FIXED, "true"); 15731 } 15732 if (revoke) { 15733 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 15734 } 15735 serializer.endTag(null, TAG_PERMISSION); 15736 } 15737 } 15738 } 15739 15740 if (pkgGrantsKnown) { 15741 serializer.endTag(null, TAG_GRANT); 15742 } 15743 } 15744 15745 serializer.endTag(null, TAG_ALL_GRANTS); 15746 } 15747 15748 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 15749 throws XmlPullParserException, IOException { 15750 String pkgName = null; 15751 int outerDepth = parser.getDepth(); 15752 int type; 15753 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 15754 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 15755 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 15756 continue; 15757 } 15758 15759 final String tagName = parser.getName(); 15760 if (tagName.equals(TAG_GRANT)) { 15761 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 15762 if (DEBUG_BACKUP) { 15763 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 15764 } 15765 } else if (tagName.equals(TAG_PERMISSION)) { 15766 15767 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 15768 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 15769 15770 int newFlagSet = 0; 15771 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 15772 newFlagSet |= FLAG_PERMISSION_USER_SET; 15773 } 15774 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 15775 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 15776 } 15777 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 15778 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 15779 } 15780 if (DEBUG_BACKUP) { 15781 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 15782 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 15783 } 15784 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15785 if (ps != null) { 15786 // Already installed so we apply the grant immediately 15787 if (DEBUG_BACKUP) { 15788 Slog.v(TAG, " + already installed; applying"); 15789 } 15790 PermissionsState perms = ps.getPermissionsState(); 15791 BasePermission bp = mSettings.mPermissions.get(permName); 15792 if (bp != null) { 15793 if (isGranted) { 15794 perms.grantRuntimePermission(bp, userId); 15795 } 15796 if (newFlagSet != 0) { 15797 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 15798 } 15799 } 15800 } else { 15801 // Need to wait for post-restore install to apply the grant 15802 if (DEBUG_BACKUP) { 15803 Slog.v(TAG, " - not yet installed; saving for later"); 15804 } 15805 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 15806 isGranted, newFlagSet, userId); 15807 } 15808 } else { 15809 PackageManagerService.reportSettingsProblem(Log.WARN, 15810 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 15811 XmlUtils.skipCurrentTag(parser); 15812 } 15813 } 15814 15815 scheduleWriteSettingsLocked(); 15816 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15817 } 15818 15819 @Override 15820 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 15821 int sourceUserId, int targetUserId, int flags) { 15822 mContext.enforceCallingOrSelfPermission( 15823 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15824 int callingUid = Binder.getCallingUid(); 15825 enforceOwnerRights(ownerPackage, callingUid); 15826 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15827 if (intentFilter.countActions() == 0) { 15828 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 15829 return; 15830 } 15831 synchronized (mPackages) { 15832 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 15833 ownerPackage, targetUserId, flags); 15834 CrossProfileIntentResolver resolver = 15835 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15836 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 15837 // We have all those whose filter is equal. Now checking if the rest is equal as well. 15838 if (existing != null) { 15839 int size = existing.size(); 15840 for (int i = 0; i < size; i++) { 15841 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 15842 return; 15843 } 15844 } 15845 } 15846 resolver.addFilter(newFilter); 15847 scheduleWritePackageRestrictionsLocked(sourceUserId); 15848 } 15849 } 15850 15851 @Override 15852 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 15853 mContext.enforceCallingOrSelfPermission( 15854 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15855 int callingUid = Binder.getCallingUid(); 15856 enforceOwnerRights(ownerPackage, callingUid); 15857 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15858 synchronized (mPackages) { 15859 CrossProfileIntentResolver resolver = 15860 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15861 ArraySet<CrossProfileIntentFilter> set = 15862 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 15863 for (CrossProfileIntentFilter filter : set) { 15864 if (filter.getOwnerPackage().equals(ownerPackage)) { 15865 resolver.removeFilter(filter); 15866 } 15867 } 15868 scheduleWritePackageRestrictionsLocked(sourceUserId); 15869 } 15870 } 15871 15872 // Enforcing that callingUid is owning pkg on userId 15873 private void enforceOwnerRights(String pkg, int callingUid) { 15874 // The system owns everything. 15875 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 15876 return; 15877 } 15878 int callingUserId = UserHandle.getUserId(callingUid); 15879 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 15880 if (pi == null) { 15881 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 15882 + callingUserId); 15883 } 15884 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 15885 throw new SecurityException("Calling uid " + callingUid 15886 + " does not own package " + pkg); 15887 } 15888 } 15889 15890 @Override 15891 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 15892 Intent intent = new Intent(Intent.ACTION_MAIN); 15893 intent.addCategory(Intent.CATEGORY_HOME); 15894 15895 final int callingUserId = UserHandle.getCallingUserId(); 15896 List<ResolveInfo> list = queryIntentActivities(intent, null, 15897 PackageManager.GET_META_DATA, callingUserId); 15898 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 15899 true, false, false, callingUserId); 15900 15901 allHomeCandidates.clear(); 15902 if (list != null) { 15903 for (ResolveInfo ri : list) { 15904 allHomeCandidates.add(ri); 15905 } 15906 } 15907 return (preferred == null || preferred.activityInfo == null) 15908 ? null 15909 : new ComponentName(preferred.activityInfo.packageName, 15910 preferred.activityInfo.name); 15911 } 15912 15913 @Override 15914 public void setApplicationEnabledSetting(String appPackageName, 15915 int newState, int flags, int userId, String callingPackage) { 15916 if (!sUserManager.exists(userId)) return; 15917 if (callingPackage == null) { 15918 callingPackage = Integer.toString(Binder.getCallingUid()); 15919 } 15920 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 15921 } 15922 15923 @Override 15924 public void setComponentEnabledSetting(ComponentName componentName, 15925 int newState, int flags, int userId) { 15926 if (!sUserManager.exists(userId)) return; 15927 setEnabledSetting(componentName.getPackageName(), 15928 componentName.getClassName(), newState, flags, userId, null); 15929 } 15930 15931 private void setEnabledSetting(final String packageName, String className, int newState, 15932 final int flags, int userId, String callingPackage) { 15933 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 15934 || newState == COMPONENT_ENABLED_STATE_ENABLED 15935 || newState == COMPONENT_ENABLED_STATE_DISABLED 15936 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 15937 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 15938 throw new IllegalArgumentException("Invalid new component state: " 15939 + newState); 15940 } 15941 PackageSetting pkgSetting; 15942 final int uid = Binder.getCallingUid(); 15943 final int permission = mContext.checkCallingOrSelfPermission( 15944 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15945 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 15946 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15947 boolean sendNow = false; 15948 boolean isApp = (className == null); 15949 String componentName = isApp ? packageName : className; 15950 int packageUid = -1; 15951 ArrayList<String> components; 15952 15953 // writer 15954 synchronized (mPackages) { 15955 pkgSetting = mSettings.mPackages.get(packageName); 15956 if (pkgSetting == null) { 15957 if (className == null) { 15958 throw new IllegalArgumentException("Unknown package: " + packageName); 15959 } 15960 throw new IllegalArgumentException( 15961 "Unknown component: " + packageName + "/" + className); 15962 } 15963 // Allow root and verify that userId is not being specified by a different user 15964 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 15965 throw new SecurityException( 15966 "Permission Denial: attempt to change component state from pid=" 15967 + Binder.getCallingPid() 15968 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 15969 } 15970 if (className == null) { 15971 // We're dealing with an application/package level state change 15972 if (pkgSetting.getEnabled(userId) == newState) { 15973 // Nothing to do 15974 return; 15975 } 15976 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 15977 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 15978 // Don't care about who enables an app. 15979 callingPackage = null; 15980 } 15981 pkgSetting.setEnabled(newState, userId, callingPackage); 15982 // pkgSetting.pkg.mSetEnabled = newState; 15983 } else { 15984 // We're dealing with a component level state change 15985 // First, verify that this is a valid class name. 15986 PackageParser.Package pkg = pkgSetting.pkg; 15987 if (pkg == null || !pkg.hasComponentClassName(className)) { 15988 if (pkg != null && 15989 pkg.applicationInfo.targetSdkVersion >= 15990 Build.VERSION_CODES.JELLY_BEAN) { 15991 throw new IllegalArgumentException("Component class " + className 15992 + " does not exist in " + packageName); 15993 } else { 15994 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 15995 + className + " does not exist in " + packageName); 15996 } 15997 } 15998 switch (newState) { 15999 case COMPONENT_ENABLED_STATE_ENABLED: 16000 if (!pkgSetting.enableComponentLPw(className, userId)) { 16001 return; 16002 } 16003 break; 16004 case COMPONENT_ENABLED_STATE_DISABLED: 16005 if (!pkgSetting.disableComponentLPw(className, userId)) { 16006 return; 16007 } 16008 break; 16009 case COMPONENT_ENABLED_STATE_DEFAULT: 16010 if (!pkgSetting.restoreComponentLPw(className, userId)) { 16011 return; 16012 } 16013 break; 16014 default: 16015 Slog.e(TAG, "Invalid new component state: " + newState); 16016 return; 16017 } 16018 } 16019 scheduleWritePackageRestrictionsLocked(userId); 16020 components = mPendingBroadcasts.get(userId, packageName); 16021 final boolean newPackage = components == null; 16022 if (newPackage) { 16023 components = new ArrayList<String>(); 16024 } 16025 if (!components.contains(componentName)) { 16026 components.add(componentName); 16027 } 16028 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 16029 sendNow = true; 16030 // Purge entry from pending broadcast list if another one exists already 16031 // since we are sending one right away. 16032 mPendingBroadcasts.remove(userId, packageName); 16033 } else { 16034 if (newPackage) { 16035 mPendingBroadcasts.put(userId, packageName, components); 16036 } 16037 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 16038 // Schedule a message 16039 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 16040 } 16041 } 16042 } 16043 16044 long callingId = Binder.clearCallingIdentity(); 16045 try { 16046 if (sendNow) { 16047 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 16048 sendPackageChangedBroadcast(packageName, 16049 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 16050 } 16051 } finally { 16052 Binder.restoreCallingIdentity(callingId); 16053 } 16054 } 16055 16056 private void sendPackageChangedBroadcast(String packageName, 16057 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 16058 if (DEBUG_INSTALL) 16059 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 16060 + componentNames); 16061 Bundle extras = new Bundle(4); 16062 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 16063 String nameList[] = new String[componentNames.size()]; 16064 componentNames.toArray(nameList); 16065 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 16066 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 16067 extras.putInt(Intent.EXTRA_UID, packageUid); 16068 // If this is not reporting a change of the overall package, then only send it 16069 // to registered receivers. We don't want to launch a swath of apps for every 16070 // little component state change. 16071 final int flags = !componentNames.contains(packageName) 16072 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 16073 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 16074 new int[] {UserHandle.getUserId(packageUid)}); 16075 } 16076 16077 @Override 16078 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 16079 if (!sUserManager.exists(userId)) return; 16080 final int uid = Binder.getCallingUid(); 16081 final int permission = mContext.checkCallingOrSelfPermission( 16082 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16083 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16084 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 16085 // writer 16086 synchronized (mPackages) { 16087 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 16088 allowedByPermission, uid, userId)) { 16089 scheduleWritePackageRestrictionsLocked(userId); 16090 } 16091 } 16092 } 16093 16094 @Override 16095 public String getInstallerPackageName(String packageName) { 16096 // reader 16097 synchronized (mPackages) { 16098 return mSettings.getInstallerPackageNameLPr(packageName); 16099 } 16100 } 16101 16102 @Override 16103 public int getApplicationEnabledSetting(String packageName, int userId) { 16104 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16105 int uid = Binder.getCallingUid(); 16106 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 16107 // reader 16108 synchronized (mPackages) { 16109 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 16110 } 16111 } 16112 16113 @Override 16114 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 16115 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16116 int uid = Binder.getCallingUid(); 16117 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 16118 // reader 16119 synchronized (mPackages) { 16120 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 16121 } 16122 } 16123 16124 @Override 16125 public void enterSafeMode() { 16126 enforceSystemOrRoot("Only the system can request entering safe mode"); 16127 16128 if (!mSystemReady) { 16129 mSafeMode = true; 16130 } 16131 } 16132 16133 @Override 16134 public void systemReady() { 16135 mSystemReady = true; 16136 16137 // Read the compatibilty setting when the system is ready. 16138 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 16139 mContext.getContentResolver(), 16140 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 16141 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 16142 if (DEBUG_SETTINGS) { 16143 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 16144 } 16145 16146 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 16147 16148 synchronized (mPackages) { 16149 // Verify that all of the preferred activity components actually 16150 // exist. It is possible for applications to be updated and at 16151 // that point remove a previously declared activity component that 16152 // had been set as a preferred activity. We try to clean this up 16153 // the next time we encounter that preferred activity, but it is 16154 // possible for the user flow to never be able to return to that 16155 // situation so here we do a sanity check to make sure we haven't 16156 // left any junk around. 16157 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 16158 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16159 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16160 removed.clear(); 16161 for (PreferredActivity pa : pir.filterSet()) { 16162 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 16163 removed.add(pa); 16164 } 16165 } 16166 if (removed.size() > 0) { 16167 for (int r=0; r<removed.size(); r++) { 16168 PreferredActivity pa = removed.get(r); 16169 Slog.w(TAG, "Removing dangling preferred activity: " 16170 + pa.mPref.mComponent); 16171 pir.removeFilter(pa); 16172 } 16173 mSettings.writePackageRestrictionsLPr( 16174 mSettings.mPreferredActivities.keyAt(i)); 16175 } 16176 } 16177 16178 for (int userId : UserManagerService.getInstance().getUserIds()) { 16179 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 16180 grantPermissionsUserIds = ArrayUtils.appendInt( 16181 grantPermissionsUserIds, userId); 16182 } 16183 } 16184 } 16185 sUserManager.systemReady(); 16186 16187 // If we upgraded grant all default permissions before kicking off. 16188 for (int userId : grantPermissionsUserIds) { 16189 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 16190 } 16191 16192 // Kick off any messages waiting for system ready 16193 if (mPostSystemReadyMessages != null) { 16194 for (Message msg : mPostSystemReadyMessages) { 16195 msg.sendToTarget(); 16196 } 16197 mPostSystemReadyMessages = null; 16198 } 16199 16200 // Watch for external volumes that come and go over time 16201 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16202 storage.registerListener(mStorageListener); 16203 16204 mInstallerService.systemReady(); 16205 mPackageDexOptimizer.systemReady(); 16206 16207 MountServiceInternal mountServiceInternal = LocalServices.getService( 16208 MountServiceInternal.class); 16209 mountServiceInternal.addExternalStoragePolicy( 16210 new MountServiceInternal.ExternalStorageMountPolicy() { 16211 @Override 16212 public int getMountMode(int uid, String packageName) { 16213 if (Process.isIsolated(uid)) { 16214 return Zygote.MOUNT_EXTERNAL_NONE; 16215 } 16216 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 16217 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16218 } 16219 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16220 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16221 } 16222 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16223 return Zygote.MOUNT_EXTERNAL_READ; 16224 } 16225 return Zygote.MOUNT_EXTERNAL_WRITE; 16226 } 16227 16228 @Override 16229 public boolean hasExternalStorage(int uid, String packageName) { 16230 return true; 16231 } 16232 }); 16233 } 16234 16235 @Override 16236 public boolean isSafeMode() { 16237 return mSafeMode; 16238 } 16239 16240 @Override 16241 public boolean hasSystemUidErrors() { 16242 return mHasSystemUidErrors; 16243 } 16244 16245 static String arrayToString(int[] array) { 16246 StringBuffer buf = new StringBuffer(128); 16247 buf.append('['); 16248 if (array != null) { 16249 for (int i=0; i<array.length; i++) { 16250 if (i > 0) buf.append(", "); 16251 buf.append(array[i]); 16252 } 16253 } 16254 buf.append(']'); 16255 return buf.toString(); 16256 } 16257 16258 static class DumpState { 16259 public static final int DUMP_LIBS = 1 << 0; 16260 public static final int DUMP_FEATURES = 1 << 1; 16261 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 16262 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 16263 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 16264 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 16265 public static final int DUMP_PERMISSIONS = 1 << 6; 16266 public static final int DUMP_PACKAGES = 1 << 7; 16267 public static final int DUMP_SHARED_USERS = 1 << 8; 16268 public static final int DUMP_MESSAGES = 1 << 9; 16269 public static final int DUMP_PROVIDERS = 1 << 10; 16270 public static final int DUMP_VERIFIERS = 1 << 11; 16271 public static final int DUMP_PREFERRED = 1 << 12; 16272 public static final int DUMP_PREFERRED_XML = 1 << 13; 16273 public static final int DUMP_KEYSETS = 1 << 14; 16274 public static final int DUMP_VERSION = 1 << 15; 16275 public static final int DUMP_INSTALLS = 1 << 16; 16276 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 16277 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 16278 16279 public static final int OPTION_SHOW_FILTERS = 1 << 0; 16280 16281 private int mTypes; 16282 16283 private int mOptions; 16284 16285 private boolean mTitlePrinted; 16286 16287 private SharedUserSetting mSharedUser; 16288 16289 public boolean isDumping(int type) { 16290 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 16291 return true; 16292 } 16293 16294 return (mTypes & type) != 0; 16295 } 16296 16297 public void setDump(int type) { 16298 mTypes |= type; 16299 } 16300 16301 public boolean isOptionEnabled(int option) { 16302 return (mOptions & option) != 0; 16303 } 16304 16305 public void setOptionEnabled(int option) { 16306 mOptions |= option; 16307 } 16308 16309 public boolean onTitlePrinted() { 16310 final boolean printed = mTitlePrinted; 16311 mTitlePrinted = true; 16312 return printed; 16313 } 16314 16315 public boolean getTitlePrinted() { 16316 return mTitlePrinted; 16317 } 16318 16319 public void setTitlePrinted(boolean enabled) { 16320 mTitlePrinted = enabled; 16321 } 16322 16323 public SharedUserSetting getSharedUser() { 16324 return mSharedUser; 16325 } 16326 16327 public void setSharedUser(SharedUserSetting user) { 16328 mSharedUser = user; 16329 } 16330 } 16331 16332 @Override 16333 public void onShellCommand(FileDescriptor in, FileDescriptor out, 16334 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 16335 (new PackageManagerShellCommand(this)).exec( 16336 this, in, out, err, args, resultReceiver); 16337 } 16338 16339 @Override 16340 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 16341 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 16342 != PackageManager.PERMISSION_GRANTED) { 16343 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 16344 + Binder.getCallingPid() 16345 + ", uid=" + Binder.getCallingUid() 16346 + " without permission " 16347 + android.Manifest.permission.DUMP); 16348 return; 16349 } 16350 16351 DumpState dumpState = new DumpState(); 16352 boolean fullPreferred = false; 16353 boolean checkin = false; 16354 16355 String packageName = null; 16356 ArraySet<String> permissionNames = null; 16357 16358 int opti = 0; 16359 while (opti < args.length) { 16360 String opt = args[opti]; 16361 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 16362 break; 16363 } 16364 opti++; 16365 16366 if ("-a".equals(opt)) { 16367 // Right now we only know how to print all. 16368 } else if ("-h".equals(opt)) { 16369 pw.println("Package manager dump options:"); 16370 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 16371 pw.println(" --checkin: dump for a checkin"); 16372 pw.println(" -f: print details of intent filters"); 16373 pw.println(" -h: print this help"); 16374 pw.println(" cmd may be one of:"); 16375 pw.println(" l[ibraries]: list known shared libraries"); 16376 pw.println(" f[eatures]: list device features"); 16377 pw.println(" k[eysets]: print known keysets"); 16378 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 16379 pw.println(" perm[issions]: dump permissions"); 16380 pw.println(" permission [name ...]: dump declaration and use of given permission"); 16381 pw.println(" pref[erred]: print preferred package settings"); 16382 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 16383 pw.println(" prov[iders]: dump content providers"); 16384 pw.println(" p[ackages]: dump installed packages"); 16385 pw.println(" s[hared-users]: dump shared user IDs"); 16386 pw.println(" m[essages]: print collected runtime messages"); 16387 pw.println(" v[erifiers]: print package verifier info"); 16388 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 16389 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 16390 pw.println(" version: print database version info"); 16391 pw.println(" write: write current settings now"); 16392 pw.println(" installs: details about install sessions"); 16393 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 16394 pw.println(" <package.name>: info about given package"); 16395 return; 16396 } else if ("--checkin".equals(opt)) { 16397 checkin = true; 16398 } else if ("-f".equals(opt)) { 16399 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16400 } else { 16401 pw.println("Unknown argument: " + opt + "; use -h for help"); 16402 } 16403 } 16404 16405 // Is the caller requesting to dump a particular piece of data? 16406 if (opti < args.length) { 16407 String cmd = args[opti]; 16408 opti++; 16409 // Is this a package name? 16410 if ("android".equals(cmd) || cmd.contains(".")) { 16411 packageName = cmd; 16412 // When dumping a single package, we always dump all of its 16413 // filter information since the amount of data will be reasonable. 16414 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16415 } else if ("check-permission".equals(cmd)) { 16416 if (opti >= args.length) { 16417 pw.println("Error: check-permission missing permission argument"); 16418 return; 16419 } 16420 String perm = args[opti]; 16421 opti++; 16422 if (opti >= args.length) { 16423 pw.println("Error: check-permission missing package argument"); 16424 return; 16425 } 16426 String pkg = args[opti]; 16427 opti++; 16428 int user = UserHandle.getUserId(Binder.getCallingUid()); 16429 if (opti < args.length) { 16430 try { 16431 user = Integer.parseInt(args[opti]); 16432 } catch (NumberFormatException e) { 16433 pw.println("Error: check-permission user argument is not a number: " 16434 + args[opti]); 16435 return; 16436 } 16437 } 16438 pw.println(checkPermission(perm, pkg, user)); 16439 return; 16440 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 16441 dumpState.setDump(DumpState.DUMP_LIBS); 16442 } else if ("f".equals(cmd) || "features".equals(cmd)) { 16443 dumpState.setDump(DumpState.DUMP_FEATURES); 16444 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 16445 if (opti >= args.length) { 16446 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 16447 | DumpState.DUMP_SERVICE_RESOLVERS 16448 | DumpState.DUMP_RECEIVER_RESOLVERS 16449 | DumpState.DUMP_CONTENT_RESOLVERS); 16450 } else { 16451 while (opti < args.length) { 16452 String name = args[opti]; 16453 if ("a".equals(name) || "activity".equals(name)) { 16454 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 16455 } else if ("s".equals(name) || "service".equals(name)) { 16456 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 16457 } else if ("r".equals(name) || "receiver".equals(name)) { 16458 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 16459 } else if ("c".equals(name) || "content".equals(name)) { 16460 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 16461 } else { 16462 pw.println("Error: unknown resolver table type: " + name); 16463 return; 16464 } 16465 opti++; 16466 } 16467 } 16468 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 16469 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 16470 } else if ("permission".equals(cmd)) { 16471 if (opti >= args.length) { 16472 pw.println("Error: permission requires permission name"); 16473 return; 16474 } 16475 permissionNames = new ArraySet<>(); 16476 while (opti < args.length) { 16477 permissionNames.add(args[opti]); 16478 opti++; 16479 } 16480 dumpState.setDump(DumpState.DUMP_PERMISSIONS 16481 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 16482 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 16483 dumpState.setDump(DumpState.DUMP_PREFERRED); 16484 } else if ("preferred-xml".equals(cmd)) { 16485 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 16486 if (opti < args.length && "--full".equals(args[opti])) { 16487 fullPreferred = true; 16488 opti++; 16489 } 16490 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 16491 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 16492 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 16493 dumpState.setDump(DumpState.DUMP_PACKAGES); 16494 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 16495 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 16496 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 16497 dumpState.setDump(DumpState.DUMP_PROVIDERS); 16498 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 16499 dumpState.setDump(DumpState.DUMP_MESSAGES); 16500 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 16501 dumpState.setDump(DumpState.DUMP_VERIFIERS); 16502 } else if ("i".equals(cmd) || "ifv".equals(cmd) 16503 || "intent-filter-verifiers".equals(cmd)) { 16504 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 16505 } else if ("version".equals(cmd)) { 16506 dumpState.setDump(DumpState.DUMP_VERSION); 16507 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 16508 dumpState.setDump(DumpState.DUMP_KEYSETS); 16509 } else if ("installs".equals(cmd)) { 16510 dumpState.setDump(DumpState.DUMP_INSTALLS); 16511 } else if ("write".equals(cmd)) { 16512 synchronized (mPackages) { 16513 mSettings.writeLPr(); 16514 pw.println("Settings written."); 16515 return; 16516 } 16517 } 16518 } 16519 16520 if (checkin) { 16521 pw.println("vers,1"); 16522 } 16523 16524 // reader 16525 synchronized (mPackages) { 16526 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 16527 if (!checkin) { 16528 if (dumpState.onTitlePrinted()) 16529 pw.println(); 16530 pw.println("Database versions:"); 16531 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 16532 } 16533 } 16534 16535 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 16536 if (!checkin) { 16537 if (dumpState.onTitlePrinted()) 16538 pw.println(); 16539 pw.println("Verifiers:"); 16540 pw.print(" Required: "); 16541 pw.print(mRequiredVerifierPackage); 16542 pw.print(" (uid="); 16543 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 16544 UserHandle.USER_SYSTEM)); 16545 pw.println(")"); 16546 } else if (mRequiredVerifierPackage != null) { 16547 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 16548 pw.print(","); 16549 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 16550 UserHandle.USER_SYSTEM)); 16551 } 16552 } 16553 16554 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 16555 packageName == null) { 16556 if (mIntentFilterVerifierComponent != null) { 16557 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 16558 if (!checkin) { 16559 if (dumpState.onTitlePrinted()) 16560 pw.println(); 16561 pw.println("Intent Filter Verifier:"); 16562 pw.print(" Using: "); 16563 pw.print(verifierPackageName); 16564 pw.print(" (uid="); 16565 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 16566 UserHandle.USER_SYSTEM)); 16567 pw.println(")"); 16568 } else if (verifierPackageName != null) { 16569 pw.print("ifv,"); pw.print(verifierPackageName); 16570 pw.print(","); 16571 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 16572 UserHandle.USER_SYSTEM)); 16573 } 16574 } else { 16575 pw.println(); 16576 pw.println("No Intent Filter Verifier available!"); 16577 } 16578 } 16579 16580 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 16581 boolean printedHeader = false; 16582 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 16583 while (it.hasNext()) { 16584 String name = it.next(); 16585 SharedLibraryEntry ent = mSharedLibraries.get(name); 16586 if (!checkin) { 16587 if (!printedHeader) { 16588 if (dumpState.onTitlePrinted()) 16589 pw.println(); 16590 pw.println("Libraries:"); 16591 printedHeader = true; 16592 } 16593 pw.print(" "); 16594 } else { 16595 pw.print("lib,"); 16596 } 16597 pw.print(name); 16598 if (!checkin) { 16599 pw.print(" -> "); 16600 } 16601 if (ent.path != null) { 16602 if (!checkin) { 16603 pw.print("(jar) "); 16604 pw.print(ent.path); 16605 } else { 16606 pw.print(",jar,"); 16607 pw.print(ent.path); 16608 } 16609 } else { 16610 if (!checkin) { 16611 pw.print("(apk) "); 16612 pw.print(ent.apk); 16613 } else { 16614 pw.print(",apk,"); 16615 pw.print(ent.apk); 16616 } 16617 } 16618 pw.println(); 16619 } 16620 } 16621 16622 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 16623 if (dumpState.onTitlePrinted()) 16624 pw.println(); 16625 if (!checkin) { 16626 pw.println("Features:"); 16627 } 16628 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 16629 while (it.hasNext()) { 16630 String name = it.next(); 16631 if (!checkin) { 16632 pw.print(" "); 16633 } else { 16634 pw.print("feat,"); 16635 } 16636 pw.println(name); 16637 } 16638 } 16639 16640 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 16641 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 16642 : "Activity Resolver Table:", " ", packageName, 16643 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16644 dumpState.setTitlePrinted(true); 16645 } 16646 } 16647 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 16648 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 16649 : "Receiver Resolver Table:", " ", packageName, 16650 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16651 dumpState.setTitlePrinted(true); 16652 } 16653 } 16654 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 16655 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 16656 : "Service Resolver Table:", " ", packageName, 16657 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16658 dumpState.setTitlePrinted(true); 16659 } 16660 } 16661 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 16662 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 16663 : "Provider Resolver Table:", " ", packageName, 16664 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16665 dumpState.setTitlePrinted(true); 16666 } 16667 } 16668 16669 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 16670 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16671 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16672 int user = mSettings.mPreferredActivities.keyAt(i); 16673 if (pir.dump(pw, 16674 dumpState.getTitlePrinted() 16675 ? "\nPreferred Activities User " + user + ":" 16676 : "Preferred Activities User " + user + ":", " ", 16677 packageName, true, false)) { 16678 dumpState.setTitlePrinted(true); 16679 } 16680 } 16681 } 16682 16683 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 16684 pw.flush(); 16685 FileOutputStream fout = new FileOutputStream(fd); 16686 BufferedOutputStream str = new BufferedOutputStream(fout); 16687 XmlSerializer serializer = new FastXmlSerializer(); 16688 try { 16689 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 16690 serializer.startDocument(null, true); 16691 serializer.setFeature( 16692 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 16693 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 16694 serializer.endDocument(); 16695 serializer.flush(); 16696 } catch (IllegalArgumentException e) { 16697 pw.println("Failed writing: " + e); 16698 } catch (IllegalStateException e) { 16699 pw.println("Failed writing: " + e); 16700 } catch (IOException e) { 16701 pw.println("Failed writing: " + e); 16702 } 16703 } 16704 16705 if (!checkin 16706 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 16707 && packageName == null) { 16708 pw.println(); 16709 int count = mSettings.mPackages.size(); 16710 if (count == 0) { 16711 pw.println("No applications!"); 16712 pw.println(); 16713 } else { 16714 final String prefix = " "; 16715 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 16716 if (allPackageSettings.size() == 0) { 16717 pw.println("No domain preferred apps!"); 16718 pw.println(); 16719 } else { 16720 pw.println("App verification status:"); 16721 pw.println(); 16722 count = 0; 16723 for (PackageSetting ps : allPackageSettings) { 16724 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 16725 if (ivi == null || ivi.getPackageName() == null) continue; 16726 pw.println(prefix + "Package: " + ivi.getPackageName()); 16727 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 16728 pw.println(prefix + "Status: " + ivi.getStatusString()); 16729 pw.println(); 16730 count++; 16731 } 16732 if (count == 0) { 16733 pw.println(prefix + "No app verification established."); 16734 pw.println(); 16735 } 16736 for (int userId : sUserManager.getUserIds()) { 16737 pw.println("App linkages for user " + userId + ":"); 16738 pw.println(); 16739 count = 0; 16740 for (PackageSetting ps : allPackageSettings) { 16741 final long status = ps.getDomainVerificationStatusForUser(userId); 16742 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 16743 continue; 16744 } 16745 pw.println(prefix + "Package: " + ps.name); 16746 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 16747 String statusStr = IntentFilterVerificationInfo. 16748 getStatusStringFromValue(status); 16749 pw.println(prefix + "Status: " + statusStr); 16750 pw.println(); 16751 count++; 16752 } 16753 if (count == 0) { 16754 pw.println(prefix + "No configured app linkages."); 16755 pw.println(); 16756 } 16757 } 16758 } 16759 } 16760 } 16761 16762 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 16763 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 16764 if (packageName == null && permissionNames == null) { 16765 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 16766 if (iperm == 0) { 16767 if (dumpState.onTitlePrinted()) 16768 pw.println(); 16769 pw.println("AppOp Permissions:"); 16770 } 16771 pw.print(" AppOp Permission "); 16772 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 16773 pw.println(":"); 16774 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 16775 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 16776 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 16777 } 16778 } 16779 } 16780 } 16781 16782 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 16783 boolean printedSomething = false; 16784 for (PackageParser.Provider p : mProviders.mProviders.values()) { 16785 if (packageName != null && !packageName.equals(p.info.packageName)) { 16786 continue; 16787 } 16788 if (!printedSomething) { 16789 if (dumpState.onTitlePrinted()) 16790 pw.println(); 16791 pw.println("Registered ContentProviders:"); 16792 printedSomething = true; 16793 } 16794 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 16795 pw.print(" "); pw.println(p.toString()); 16796 } 16797 printedSomething = false; 16798 for (Map.Entry<String, PackageParser.Provider> entry : 16799 mProvidersByAuthority.entrySet()) { 16800 PackageParser.Provider p = entry.getValue(); 16801 if (packageName != null && !packageName.equals(p.info.packageName)) { 16802 continue; 16803 } 16804 if (!printedSomething) { 16805 if (dumpState.onTitlePrinted()) 16806 pw.println(); 16807 pw.println("ContentProvider Authorities:"); 16808 printedSomething = true; 16809 } 16810 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 16811 pw.print(" "); pw.println(p.toString()); 16812 if (p.info != null && p.info.applicationInfo != null) { 16813 final String appInfo = p.info.applicationInfo.toString(); 16814 pw.print(" applicationInfo="); pw.println(appInfo); 16815 } 16816 } 16817 } 16818 16819 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 16820 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 16821 } 16822 16823 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 16824 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 16825 } 16826 16827 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 16828 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 16829 } 16830 16831 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 16832 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 16833 } 16834 16835 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 16836 // XXX should handle packageName != null by dumping only install data that 16837 // the given package is involved with. 16838 if (dumpState.onTitlePrinted()) pw.println(); 16839 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 16840 } 16841 16842 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 16843 if (dumpState.onTitlePrinted()) pw.println(); 16844 mSettings.dumpReadMessagesLPr(pw, dumpState); 16845 16846 pw.println(); 16847 pw.println("Package warning messages:"); 16848 BufferedReader in = null; 16849 String line = null; 16850 try { 16851 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16852 while ((line = in.readLine()) != null) { 16853 if (line.contains("ignored: updated version")) continue; 16854 pw.println(line); 16855 } 16856 } catch (IOException ignored) { 16857 } finally { 16858 IoUtils.closeQuietly(in); 16859 } 16860 } 16861 16862 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 16863 BufferedReader in = null; 16864 String line = null; 16865 try { 16866 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16867 while ((line = in.readLine()) != null) { 16868 if (line.contains("ignored: updated version")) continue; 16869 pw.print("msg,"); 16870 pw.println(line); 16871 } 16872 } catch (IOException ignored) { 16873 } finally { 16874 IoUtils.closeQuietly(in); 16875 } 16876 } 16877 } 16878 } 16879 16880 private String dumpDomainString(String packageName) { 16881 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 16882 List<IntentFilter> filters = getAllIntentFilters(packageName); 16883 16884 ArraySet<String> result = new ArraySet<>(); 16885 if (iviList.size() > 0) { 16886 for (IntentFilterVerificationInfo ivi : iviList) { 16887 for (String host : ivi.getDomains()) { 16888 result.add(host); 16889 } 16890 } 16891 } 16892 if (filters != null && filters.size() > 0) { 16893 for (IntentFilter filter : filters) { 16894 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 16895 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 16896 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 16897 result.addAll(filter.getHostsList()); 16898 } 16899 } 16900 } 16901 16902 StringBuilder sb = new StringBuilder(result.size() * 16); 16903 for (String domain : result) { 16904 if (sb.length() > 0) sb.append(" "); 16905 sb.append(domain); 16906 } 16907 return sb.toString(); 16908 } 16909 16910 // ------- apps on sdcard specific code ------- 16911 static final boolean DEBUG_SD_INSTALL = false; 16912 16913 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 16914 16915 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 16916 16917 private boolean mMediaMounted = false; 16918 16919 static String getEncryptKey() { 16920 try { 16921 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 16922 SD_ENCRYPTION_KEYSTORE_NAME); 16923 if (sdEncKey == null) { 16924 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 16925 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 16926 if (sdEncKey == null) { 16927 Slog.e(TAG, "Failed to create encryption keys"); 16928 return null; 16929 } 16930 } 16931 return sdEncKey; 16932 } catch (NoSuchAlgorithmException nsae) { 16933 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 16934 return null; 16935 } catch (IOException ioe) { 16936 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 16937 return null; 16938 } 16939 } 16940 16941 /* 16942 * Update media status on PackageManager. 16943 */ 16944 @Override 16945 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 16946 int callingUid = Binder.getCallingUid(); 16947 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 16948 throw new SecurityException("Media status can only be updated by the system"); 16949 } 16950 // reader; this apparently protects mMediaMounted, but should probably 16951 // be a different lock in that case. 16952 synchronized (mPackages) { 16953 Log.i(TAG, "Updating external media status from " 16954 + (mMediaMounted ? "mounted" : "unmounted") + " to " 16955 + (mediaStatus ? "mounted" : "unmounted")); 16956 if (DEBUG_SD_INSTALL) 16957 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 16958 + ", mMediaMounted=" + mMediaMounted); 16959 if (mediaStatus == mMediaMounted) { 16960 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 16961 : 0, -1); 16962 mHandler.sendMessage(msg); 16963 return; 16964 } 16965 mMediaMounted = mediaStatus; 16966 } 16967 // Queue up an async operation since the package installation may take a 16968 // little while. 16969 mHandler.post(new Runnable() { 16970 public void run() { 16971 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 16972 } 16973 }); 16974 } 16975 16976 /** 16977 * Called by MountService when the initial ASECs to scan are available. 16978 * Should block until all the ASEC containers are finished being scanned. 16979 */ 16980 public void scanAvailableAsecs() { 16981 updateExternalMediaStatusInner(true, false, false); 16982 } 16983 16984 /* 16985 * Collect information of applications on external media, map them against 16986 * existing containers and update information based on current mount status. 16987 * Please note that we always have to report status if reportStatus has been 16988 * set to true especially when unloading packages. 16989 */ 16990 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 16991 boolean externalStorage) { 16992 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 16993 int[] uidArr = EmptyArray.INT; 16994 16995 final String[] list = PackageHelper.getSecureContainerList(); 16996 if (ArrayUtils.isEmpty(list)) { 16997 Log.i(TAG, "No secure containers found"); 16998 } else { 16999 // Process list of secure containers and categorize them 17000 // as active or stale based on their package internal state. 17001 17002 // reader 17003 synchronized (mPackages) { 17004 for (String cid : list) { 17005 // Leave stages untouched for now; installer service owns them 17006 if (PackageInstallerService.isStageName(cid)) continue; 17007 17008 if (DEBUG_SD_INSTALL) 17009 Log.i(TAG, "Processing container " + cid); 17010 String pkgName = getAsecPackageName(cid); 17011 if (pkgName == null) { 17012 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 17013 continue; 17014 } 17015 if (DEBUG_SD_INSTALL) 17016 Log.i(TAG, "Looking for pkg : " + pkgName); 17017 17018 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17019 if (ps == null) { 17020 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 17021 continue; 17022 } 17023 17024 /* 17025 * Skip packages that are not external if we're unmounting 17026 * external storage. 17027 */ 17028 if (externalStorage && !isMounted && !isExternal(ps)) { 17029 continue; 17030 } 17031 17032 final AsecInstallArgs args = new AsecInstallArgs(cid, 17033 getAppDexInstructionSets(ps), ps.isForwardLocked()); 17034 // The package status is changed only if the code path 17035 // matches between settings and the container id. 17036 if (ps.codePathString != null 17037 && ps.codePathString.startsWith(args.getCodePath())) { 17038 if (DEBUG_SD_INSTALL) { 17039 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 17040 + " at code path: " + ps.codePathString); 17041 } 17042 17043 // We do have a valid package installed on sdcard 17044 processCids.put(args, ps.codePathString); 17045 final int uid = ps.appId; 17046 if (uid != -1) { 17047 uidArr = ArrayUtils.appendInt(uidArr, uid); 17048 } 17049 } else { 17050 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 17051 + ps.codePathString); 17052 } 17053 } 17054 } 17055 17056 Arrays.sort(uidArr); 17057 } 17058 17059 // Process packages with valid entries. 17060 if (isMounted) { 17061 if (DEBUG_SD_INSTALL) 17062 Log.i(TAG, "Loading packages"); 17063 loadMediaPackages(processCids, uidArr, externalStorage); 17064 startCleaningPackages(); 17065 mInstallerService.onSecureContainersAvailable(); 17066 } else { 17067 if (DEBUG_SD_INSTALL) 17068 Log.i(TAG, "Unloading packages"); 17069 unloadMediaPackages(processCids, uidArr, reportStatus); 17070 } 17071 } 17072 17073 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17074 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 17075 final int size = infos.size(); 17076 final String[] packageNames = new String[size]; 17077 final int[] packageUids = new int[size]; 17078 for (int i = 0; i < size; i++) { 17079 final ApplicationInfo info = infos.get(i); 17080 packageNames[i] = info.packageName; 17081 packageUids[i] = info.uid; 17082 } 17083 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 17084 finishedReceiver); 17085 } 17086 17087 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17088 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17089 sendResourcesChangedBroadcast(mediaStatus, replacing, 17090 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 17091 } 17092 17093 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17094 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17095 int size = pkgList.length; 17096 if (size > 0) { 17097 // Send broadcasts here 17098 Bundle extras = new Bundle(); 17099 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 17100 if (uidArr != null) { 17101 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 17102 } 17103 if (replacing) { 17104 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 17105 } 17106 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 17107 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 17108 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 17109 } 17110 } 17111 17112 /* 17113 * Look at potentially valid container ids from processCids If package 17114 * information doesn't match the one on record or package scanning fails, 17115 * the cid is added to list of removeCids. We currently don't delete stale 17116 * containers. 17117 */ 17118 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 17119 boolean externalStorage) { 17120 ArrayList<String> pkgList = new ArrayList<String>(); 17121 Set<AsecInstallArgs> keys = processCids.keySet(); 17122 17123 for (AsecInstallArgs args : keys) { 17124 String codePath = processCids.get(args); 17125 if (DEBUG_SD_INSTALL) 17126 Log.i(TAG, "Loading container : " + args.cid); 17127 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17128 try { 17129 // Make sure there are no container errors first. 17130 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 17131 Slog.e(TAG, "Failed to mount cid : " + args.cid 17132 + " when installing from sdcard"); 17133 continue; 17134 } 17135 // Check code path here. 17136 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 17137 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 17138 + " does not match one in settings " + codePath); 17139 continue; 17140 } 17141 // Parse package 17142 int parseFlags = mDefParseFlags; 17143 if (args.isExternalAsec()) { 17144 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 17145 } 17146 if (args.isFwdLocked()) { 17147 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 17148 } 17149 17150 synchronized (mInstallLock) { 17151 PackageParser.Package pkg = null; 17152 try { 17153 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 17154 } catch (PackageManagerException e) { 17155 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 17156 } 17157 // Scan the package 17158 if (pkg != null) { 17159 /* 17160 * TODO why is the lock being held? doPostInstall is 17161 * called in other places without the lock. This needs 17162 * to be straightened out. 17163 */ 17164 // writer 17165 synchronized (mPackages) { 17166 retCode = PackageManager.INSTALL_SUCCEEDED; 17167 pkgList.add(pkg.packageName); 17168 // Post process args 17169 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 17170 pkg.applicationInfo.uid); 17171 } 17172 } else { 17173 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 17174 } 17175 } 17176 17177 } finally { 17178 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 17179 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 17180 } 17181 } 17182 } 17183 // writer 17184 synchronized (mPackages) { 17185 // If the platform SDK has changed since the last time we booted, 17186 // we need to re-grant app permission to catch any new ones that 17187 // appear. This is really a hack, and means that apps can in some 17188 // cases get permissions that the user didn't initially explicitly 17189 // allow... it would be nice to have some better way to handle 17190 // this situation. 17191 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 17192 : mSettings.getInternalVersion(); 17193 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 17194 : StorageManager.UUID_PRIVATE_INTERNAL; 17195 17196 int updateFlags = UPDATE_PERMISSIONS_ALL; 17197 if (ver.sdkVersion != mSdkVersion) { 17198 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17199 + mSdkVersion + "; regranting permissions for external"); 17200 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17201 } 17202 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17203 17204 // Yay, everything is now upgraded 17205 ver.forceCurrent(); 17206 17207 // can downgrade to reader 17208 // Persist settings 17209 mSettings.writeLPr(); 17210 } 17211 // Send a broadcast to let everyone know we are done processing 17212 if (pkgList.size() > 0) { 17213 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 17214 } 17215 } 17216 17217 /* 17218 * Utility method to unload a list of specified containers 17219 */ 17220 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 17221 // Just unmount all valid containers. 17222 for (AsecInstallArgs arg : cidArgs) { 17223 synchronized (mInstallLock) { 17224 arg.doPostDeleteLI(false); 17225 } 17226 } 17227 } 17228 17229 /* 17230 * Unload packages mounted on external media. This involves deleting package 17231 * data from internal structures, sending broadcasts about disabled packages, 17232 * gc'ing to free up references, unmounting all secure containers 17233 * corresponding to packages on external media, and posting a 17234 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 17235 * that we always have to post this message if status has been requested no 17236 * matter what. 17237 */ 17238 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 17239 final boolean reportStatus) { 17240 if (DEBUG_SD_INSTALL) 17241 Log.i(TAG, "unloading media packages"); 17242 ArrayList<String> pkgList = new ArrayList<String>(); 17243 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 17244 final Set<AsecInstallArgs> keys = processCids.keySet(); 17245 for (AsecInstallArgs args : keys) { 17246 String pkgName = args.getPackageName(); 17247 if (DEBUG_SD_INSTALL) 17248 Log.i(TAG, "Trying to unload pkg : " + pkgName); 17249 // Delete package internally 17250 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17251 synchronized (mInstallLock) { 17252 boolean res = deletePackageLI(pkgName, null, false, null, null, 17253 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 17254 if (res) { 17255 pkgList.add(pkgName); 17256 } else { 17257 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 17258 failedList.add(args); 17259 } 17260 } 17261 } 17262 17263 // reader 17264 synchronized (mPackages) { 17265 // We didn't update the settings after removing each package; 17266 // write them now for all packages. 17267 mSettings.writeLPr(); 17268 } 17269 17270 // We have to absolutely send UPDATED_MEDIA_STATUS only 17271 // after confirming that all the receivers processed the ordered 17272 // broadcast when packages get disabled, force a gc to clean things up. 17273 // and unload all the containers. 17274 if (pkgList.size() > 0) { 17275 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 17276 new IIntentReceiver.Stub() { 17277 public void performReceive(Intent intent, int resultCode, String data, 17278 Bundle extras, boolean ordered, boolean sticky, 17279 int sendingUser) throws RemoteException { 17280 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 17281 reportStatus ? 1 : 0, 1, keys); 17282 mHandler.sendMessage(msg); 17283 } 17284 }); 17285 } else { 17286 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 17287 keys); 17288 mHandler.sendMessage(msg); 17289 } 17290 } 17291 17292 private void loadPrivatePackages(final VolumeInfo vol) { 17293 mHandler.post(new Runnable() { 17294 @Override 17295 public void run() { 17296 loadPrivatePackagesInner(vol); 17297 } 17298 }); 17299 } 17300 17301 private void loadPrivatePackagesInner(VolumeInfo vol) { 17302 final String volumeUuid = vol.fsUuid; 17303 if (TextUtils.isEmpty(volumeUuid)) { 17304 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 17305 return; 17306 } 17307 17308 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 17309 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 17310 17311 final VersionInfo ver; 17312 final List<PackageSetting> packages; 17313 synchronized (mPackages) { 17314 ver = mSettings.findOrCreateVersion(volumeUuid); 17315 packages = mSettings.getVolumePackagesLPr(volumeUuid); 17316 } 17317 17318 // TODO: introduce a new concept similar to "frozen" to prevent these 17319 // apps from being launched until after data has been fully reconciled 17320 for (PackageSetting ps : packages) { 17321 synchronized (mInstallLock) { 17322 final PackageParser.Package pkg; 17323 try { 17324 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 17325 loaded.add(pkg.applicationInfo); 17326 17327 } catch (PackageManagerException e) { 17328 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 17329 } 17330 17331 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 17332 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 17333 } 17334 } 17335 } 17336 17337 // Reconcile app data for all started/unlocked users 17338 final StorageManager sm = mContext.getSystemService(StorageManager.class); 17339 final UserManager um = mContext.getSystemService(UserManager.class); 17340 for (UserInfo user : um.getUsers()) { 17341 final int flags; 17342 if (um.isUserUnlocked(user.id)) { 17343 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17344 } else if (um.isUserRunning(user.id)) { 17345 flags = StorageManager.FLAG_STORAGE_DE; 17346 } else { 17347 continue; 17348 } 17349 17350 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 17351 reconcileAppsData(volumeUuid, user.id, flags); 17352 } 17353 17354 synchronized (mPackages) { 17355 int updateFlags = UPDATE_PERMISSIONS_ALL; 17356 if (ver.sdkVersion != mSdkVersion) { 17357 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17358 + mSdkVersion + "; regranting permissions for " + volumeUuid); 17359 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17360 } 17361 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17362 17363 // Yay, everything is now upgraded 17364 ver.forceCurrent(); 17365 17366 mSettings.writeLPr(); 17367 } 17368 17369 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 17370 sendResourcesChangedBroadcast(true, false, loaded, null); 17371 } 17372 17373 private void unloadPrivatePackages(final VolumeInfo vol) { 17374 mHandler.post(new Runnable() { 17375 @Override 17376 public void run() { 17377 unloadPrivatePackagesInner(vol); 17378 } 17379 }); 17380 } 17381 17382 private void unloadPrivatePackagesInner(VolumeInfo vol) { 17383 final String volumeUuid = vol.fsUuid; 17384 if (TextUtils.isEmpty(volumeUuid)) { 17385 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 17386 return; 17387 } 17388 17389 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 17390 synchronized (mInstallLock) { 17391 synchronized (mPackages) { 17392 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 17393 for (PackageSetting ps : packages) { 17394 if (ps.pkg == null) continue; 17395 17396 final ApplicationInfo info = ps.pkg.applicationInfo; 17397 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17398 if (deletePackageLI(ps.name, null, false, null, null, 17399 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 17400 unloaded.add(info); 17401 } else { 17402 Slog.w(TAG, "Failed to unload " + ps.codePath); 17403 } 17404 } 17405 17406 mSettings.writeLPr(); 17407 } 17408 } 17409 17410 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 17411 sendResourcesChangedBroadcast(false, false, unloaded, null); 17412 } 17413 17414 /** 17415 * Examine all users present on given mounted volume, and destroy data 17416 * belonging to users that are no longer valid, or whose user ID has been 17417 * recycled. 17418 */ 17419 private void reconcileUsers(String volumeUuid) { 17420 // TODO: also reconcile DE directories 17421 final File[] files = FileUtils 17422 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 17423 for (File file : files) { 17424 if (!file.isDirectory()) continue; 17425 17426 final int userId; 17427 final UserInfo info; 17428 try { 17429 userId = Integer.parseInt(file.getName()); 17430 info = sUserManager.getUserInfo(userId); 17431 } catch (NumberFormatException e) { 17432 Slog.w(TAG, "Invalid user directory " + file); 17433 continue; 17434 } 17435 17436 boolean destroyUser = false; 17437 if (info == null) { 17438 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17439 + " because no matching user was found"); 17440 destroyUser = true; 17441 } else { 17442 try { 17443 UserManagerService.enforceSerialNumber(file, info.serialNumber); 17444 } catch (IOException e) { 17445 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17446 + " because we failed to enforce serial number: " + e); 17447 destroyUser = true; 17448 } 17449 } 17450 17451 if (destroyUser) { 17452 synchronized (mInstallLock) { 17453 try { 17454 mInstaller.removeUserDataDirs(volumeUuid, userId); 17455 } catch (InstallerException e) { 17456 Slog.w(TAG, "Failed to clean up user dirs", e); 17457 } 17458 } 17459 } 17460 } 17461 } 17462 17463 private void assertPackageKnown(String volumeUuid, String packageName) 17464 throws PackageManagerException { 17465 synchronized (mPackages) { 17466 final PackageSetting ps = mSettings.mPackages.get(packageName); 17467 if (ps == null) { 17468 throw new PackageManagerException("Package " + packageName + " is unknown"); 17469 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 17470 throw new PackageManagerException( 17471 "Package " + packageName + " found on unknown volume " + volumeUuid 17472 + "; expected volume " + ps.volumeUuid); 17473 } 17474 } 17475 } 17476 17477 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 17478 throws PackageManagerException { 17479 synchronized (mPackages) { 17480 final PackageSetting ps = mSettings.mPackages.get(packageName); 17481 if (ps == null) { 17482 throw new PackageManagerException("Package " + packageName + " is unknown"); 17483 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 17484 throw new PackageManagerException( 17485 "Package " + packageName + " found on unknown volume " + volumeUuid 17486 + "; expected volume " + ps.volumeUuid); 17487 } else if (!ps.getInstalled(userId)) { 17488 throw new PackageManagerException( 17489 "Package " + packageName + " not installed for user " + userId); 17490 } 17491 } 17492 } 17493 17494 /** 17495 * Examine all apps present on given mounted volume, and destroy apps that 17496 * aren't expected, either due to uninstallation or reinstallation on 17497 * another volume. 17498 */ 17499 private void reconcileApps(String volumeUuid) { 17500 final File[] files = FileUtils 17501 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 17502 for (File file : files) { 17503 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 17504 && !PackageInstallerService.isStageName(file.getName()); 17505 if (!isPackage) { 17506 // Ignore entries which are not packages 17507 continue; 17508 } 17509 17510 try { 17511 final PackageLite pkg = PackageParser.parsePackageLite(file, 17512 PackageParser.PARSE_MUST_BE_APK); 17513 assertPackageKnown(volumeUuid, pkg.packageName); 17514 17515 } catch (PackageParserException | PackageManagerException e) { 17516 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17517 synchronized (mInstallLock) { 17518 removeCodePathLI(file); 17519 } 17520 } 17521 } 17522 } 17523 17524 /** 17525 * Reconcile all app data for the given user. 17526 * <p> 17527 * Verifies that directories exist and that ownership and labeling is 17528 * correct for all installed apps on all mounted volumes. 17529 */ 17530 void reconcileAppsData(int userId, int flags) { 17531 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17532 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 17533 final String volumeUuid = vol.getFsUuid(); 17534 reconcileAppsData(volumeUuid, userId, flags); 17535 } 17536 } 17537 17538 /** 17539 * Reconcile all app data on given mounted volume. 17540 * <p> 17541 * Destroys app data that isn't expected, either due to uninstallation or 17542 * reinstallation on another volume. 17543 * <p> 17544 * Verifies that directories exist and that ownership and labeling is 17545 * correct for all installed apps. 17546 */ 17547 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 17548 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 17549 + Integer.toHexString(flags)); 17550 17551 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 17552 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 17553 17554 boolean restoreconNeeded = false; 17555 17556 // First look for stale data that doesn't belong, and check if things 17557 // have changed since we did our last restorecon 17558 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 17559 if (!isUserKeyUnlocked(userId)) { 17560 throw new RuntimeException( 17561 "Yikes, someone asked us to reconcile CE storage while " + userId 17562 + " was still locked; this would have caused massive data loss!"); 17563 } 17564 17565 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 17566 17567 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 17568 for (File file : files) { 17569 final String packageName = file.getName(); 17570 try { 17571 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 17572 } catch (PackageManagerException e) { 17573 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17574 synchronized (mInstallLock) { 17575 destroyAppDataLI(volumeUuid, packageName, userId, 17576 StorageManager.FLAG_STORAGE_CE); 17577 } 17578 } 17579 } 17580 } 17581 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 17582 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 17583 17584 final File[] files = FileUtils.listFilesOrEmpty(deDir); 17585 for (File file : files) { 17586 final String packageName = file.getName(); 17587 try { 17588 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 17589 } catch (PackageManagerException e) { 17590 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17591 synchronized (mInstallLock) { 17592 destroyAppDataLI(volumeUuid, packageName, userId, 17593 StorageManager.FLAG_STORAGE_DE); 17594 } 17595 } 17596 } 17597 } 17598 17599 // Ensure that data directories are ready to roll for all packages 17600 // installed for this volume and user 17601 final List<PackageSetting> packages; 17602 synchronized (mPackages) { 17603 packages = mSettings.getVolumePackagesLPr(volumeUuid); 17604 } 17605 int preparedCount = 0; 17606 for (PackageSetting ps : packages) { 17607 final String packageName = ps.name; 17608 if (ps.pkg == null) { 17609 Slog.w(TAG, "Odd, missing scanned package " + packageName); 17610 // TODO: might be due to legacy ASEC apps; we should circle back 17611 // and reconcile again once they're scanned 17612 continue; 17613 } 17614 17615 if (ps.getInstalled(userId)) { 17616 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 17617 preparedCount++; 17618 } 17619 } 17620 17621 if (restoreconNeeded) { 17622 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 17623 SELinuxMMAC.setRestoreconDone(ceDir); 17624 } 17625 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 17626 SELinuxMMAC.setRestoreconDone(deDir); 17627 } 17628 } 17629 17630 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 17631 + " packages; restoreconNeeded was " + restoreconNeeded); 17632 } 17633 17634 /** 17635 * Prepare app data for the given app just after it was installed or 17636 * upgraded. This method carefully only touches users that it's installed 17637 * for, and it forces a restorecon to handle any seinfo changes. 17638 * <p> 17639 * Verifies that directories exist and that ownership and labeling is 17640 * correct for all installed apps. If there is an ownership mismatch, it 17641 * will try recovering system apps by wiping data; third-party app data is 17642 * left intact. 17643 */ 17644 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 17645 prepareAppDataAfterInstallInternal(pkg); 17646 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17647 for (int i = 0; i < childCount; i++) { 17648 PackageParser.Package childPackage = pkg.childPackages.get(i); 17649 prepareAppDataAfterInstallInternal(childPackage); 17650 } 17651 } 17652 17653 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 17654 final PackageSetting ps; 17655 synchronized (mPackages) { 17656 ps = mSettings.mPackages.get(pkg.packageName); 17657 } 17658 17659 final UserManager um = mContext.getSystemService(UserManager.class); 17660 for (UserInfo user : um.getUsers()) { 17661 final int flags; 17662 if (um.isUserUnlocked(user.id)) { 17663 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17664 } else if (um.isUserRunning(user.id)) { 17665 flags = StorageManager.FLAG_STORAGE_DE; 17666 } else { 17667 continue; 17668 } 17669 17670 if (ps.getInstalled(user.id)) { 17671 // Whenever an app changes, force a restorecon of its data 17672 // TODO: when user data is locked, mark that we're still dirty 17673 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 17674 } 17675 } 17676 } 17677 17678 /** 17679 * Prepare app data for the given app. 17680 * <p> 17681 * Verifies that directories exist and that ownership and labeling is 17682 * correct for all installed apps. If there is an ownership mismatch, this 17683 * will try recovering system apps by wiping data; third-party app data is 17684 * left intact. 17685 */ 17686 private void prepareAppData(String volumeUuid, int userId, int flags, 17687 PackageParser.Package pkg, boolean restoreconNeeded) { 17688 if (DEBUG_APP_DATA) { 17689 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 17690 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 17691 } 17692 17693 final String packageName = pkg.packageName; 17694 final ApplicationInfo app = pkg.applicationInfo; 17695 final int appId = UserHandle.getAppId(app.uid); 17696 17697 Preconditions.checkNotNull(app.seinfo); 17698 17699 synchronized (mInstallLock) { 17700 try { 17701 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17702 appId, app.seinfo, app.targetSdkVersion); 17703 } catch (InstallerException e) { 17704 if (app.isSystemApp()) { 17705 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 17706 + ", but trying to recover: " + e); 17707 destroyAppDataLI(volumeUuid, packageName, userId, flags); 17708 try { 17709 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17710 appId, app.seinfo, app.targetSdkVersion); 17711 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 17712 } catch (InstallerException e2) { 17713 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 17714 } 17715 } else { 17716 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 17717 } 17718 } 17719 17720 if (restoreconNeeded) { 17721 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 17722 } 17723 17724 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 17725 // Create a native library symlink only if we have native libraries 17726 // and if the native libraries are 32 bit libraries. We do not provide 17727 // this symlink for 64 bit libraries. 17728 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 17729 final String nativeLibPath = app.nativeLibraryDir; 17730 try { 17731 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 17732 nativeLibPath, userId); 17733 } catch (InstallerException e) { 17734 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 17735 } 17736 } 17737 } 17738 } 17739 } 17740 17741 private void unfreezePackage(String packageName) { 17742 synchronized (mPackages) { 17743 final PackageSetting ps = mSettings.mPackages.get(packageName); 17744 if (ps != null) { 17745 ps.frozen = false; 17746 } 17747 } 17748 } 17749 17750 @Override 17751 public int movePackage(final String packageName, final String volumeUuid) { 17752 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17753 17754 final int moveId = mNextMoveId.getAndIncrement(); 17755 mHandler.post(new Runnable() { 17756 @Override 17757 public void run() { 17758 try { 17759 movePackageInternal(packageName, volumeUuid, moveId); 17760 } catch (PackageManagerException e) { 17761 Slog.w(TAG, "Failed to move " + packageName, e); 17762 mMoveCallbacks.notifyStatusChanged(moveId, 17763 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17764 } 17765 } 17766 }); 17767 return moveId; 17768 } 17769 17770 private void movePackageInternal(final String packageName, final String volumeUuid, 17771 final int moveId) throws PackageManagerException { 17772 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 17773 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17774 final PackageManager pm = mContext.getPackageManager(); 17775 17776 final boolean currentAsec; 17777 final String currentVolumeUuid; 17778 final File codeFile; 17779 final String installerPackageName; 17780 final String packageAbiOverride; 17781 final int appId; 17782 final String seinfo; 17783 final String label; 17784 final int targetSdkVersion; 17785 17786 // reader 17787 synchronized (mPackages) { 17788 final PackageParser.Package pkg = mPackages.get(packageName); 17789 final PackageSetting ps = mSettings.mPackages.get(packageName); 17790 if (pkg == null || ps == null) { 17791 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 17792 } 17793 17794 if (pkg.applicationInfo.isSystemApp()) { 17795 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 17796 "Cannot move system application"); 17797 } 17798 17799 if (pkg.applicationInfo.isExternalAsec()) { 17800 currentAsec = true; 17801 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 17802 } else if (pkg.applicationInfo.isForwardLocked()) { 17803 currentAsec = true; 17804 currentVolumeUuid = "forward_locked"; 17805 } else { 17806 currentAsec = false; 17807 currentVolumeUuid = ps.volumeUuid; 17808 17809 final File probe = new File(pkg.codePath); 17810 final File probeOat = new File(probe, "oat"); 17811 if (!probe.isDirectory() || !probeOat.isDirectory()) { 17812 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17813 "Move only supported for modern cluster style installs"); 17814 } 17815 } 17816 17817 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 17818 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17819 "Package already moved to " + volumeUuid); 17820 } 17821 17822 if (ps.frozen) { 17823 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 17824 "Failed to move already frozen package"); 17825 } 17826 ps.frozen = true; 17827 17828 codeFile = new File(pkg.codePath); 17829 installerPackageName = ps.installerPackageName; 17830 packageAbiOverride = ps.cpuAbiOverrideString; 17831 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 17832 seinfo = pkg.applicationInfo.seinfo; 17833 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 17834 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 17835 } 17836 17837 // Now that we're guarded by frozen state, kill app during move 17838 final long token = Binder.clearCallingIdentity(); 17839 try { 17840 killApplication(packageName, appId, "move pkg"); 17841 } finally { 17842 Binder.restoreCallingIdentity(token); 17843 } 17844 17845 final Bundle extras = new Bundle(); 17846 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 17847 extras.putString(Intent.EXTRA_TITLE, label); 17848 mMoveCallbacks.notifyCreated(moveId, extras); 17849 17850 int installFlags; 17851 final boolean moveCompleteApp; 17852 final File measurePath; 17853 17854 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 17855 installFlags = INSTALL_INTERNAL; 17856 moveCompleteApp = !currentAsec; 17857 measurePath = Environment.getDataAppDirectory(volumeUuid); 17858 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 17859 installFlags = INSTALL_EXTERNAL; 17860 moveCompleteApp = false; 17861 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 17862 } else { 17863 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 17864 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 17865 || !volume.isMountedWritable()) { 17866 unfreezePackage(packageName); 17867 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17868 "Move location not mounted private volume"); 17869 } 17870 17871 Preconditions.checkState(!currentAsec); 17872 17873 installFlags = INSTALL_INTERNAL; 17874 moveCompleteApp = true; 17875 measurePath = Environment.getDataAppDirectory(volumeUuid); 17876 } 17877 17878 final PackageStats stats = new PackageStats(null, -1); 17879 synchronized (mInstaller) { 17880 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 17881 unfreezePackage(packageName); 17882 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17883 "Failed to measure package size"); 17884 } 17885 } 17886 17887 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 17888 + stats.dataSize); 17889 17890 final long startFreeBytes = measurePath.getFreeSpace(); 17891 final long sizeBytes; 17892 if (moveCompleteApp) { 17893 sizeBytes = stats.codeSize + stats.dataSize; 17894 } else { 17895 sizeBytes = stats.codeSize; 17896 } 17897 17898 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 17899 unfreezePackage(packageName); 17900 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17901 "Not enough free space to move"); 17902 } 17903 17904 mMoveCallbacks.notifyStatusChanged(moveId, 10); 17905 17906 final CountDownLatch installedLatch = new CountDownLatch(1); 17907 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 17908 @Override 17909 public void onUserActionRequired(Intent intent) throws RemoteException { 17910 throw new IllegalStateException(); 17911 } 17912 17913 @Override 17914 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 17915 Bundle extras) throws RemoteException { 17916 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 17917 + PackageManager.installStatusToString(returnCode, msg)); 17918 17919 installedLatch.countDown(); 17920 17921 // Regardless of success or failure of the move operation, 17922 // always unfreeze the package 17923 unfreezePackage(packageName); 17924 17925 final int status = PackageManager.installStatusToPublicStatus(returnCode); 17926 switch (status) { 17927 case PackageInstaller.STATUS_SUCCESS: 17928 mMoveCallbacks.notifyStatusChanged(moveId, 17929 PackageManager.MOVE_SUCCEEDED); 17930 break; 17931 case PackageInstaller.STATUS_FAILURE_STORAGE: 17932 mMoveCallbacks.notifyStatusChanged(moveId, 17933 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 17934 break; 17935 default: 17936 mMoveCallbacks.notifyStatusChanged(moveId, 17937 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17938 break; 17939 } 17940 } 17941 }; 17942 17943 final MoveInfo move; 17944 if (moveCompleteApp) { 17945 // Kick off a thread to report progress estimates 17946 new Thread() { 17947 @Override 17948 public void run() { 17949 while (true) { 17950 try { 17951 if (installedLatch.await(1, TimeUnit.SECONDS)) { 17952 break; 17953 } 17954 } catch (InterruptedException ignored) { 17955 } 17956 17957 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 17958 final int progress = 10 + (int) MathUtils.constrain( 17959 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 17960 mMoveCallbacks.notifyStatusChanged(moveId, progress); 17961 } 17962 } 17963 }.start(); 17964 17965 final String dataAppName = codeFile.getName(); 17966 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 17967 dataAppName, appId, seinfo, targetSdkVersion); 17968 } else { 17969 move = null; 17970 } 17971 17972 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 17973 17974 final Message msg = mHandler.obtainMessage(INIT_COPY); 17975 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 17976 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 17977 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 17978 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 17979 msg.obj = params; 17980 17981 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 17982 System.identityHashCode(msg.obj)); 17983 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 17984 System.identityHashCode(msg.obj)); 17985 17986 mHandler.sendMessage(msg); 17987 } 17988 17989 @Override 17990 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 17991 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17992 17993 final int realMoveId = mNextMoveId.getAndIncrement(); 17994 final Bundle extras = new Bundle(); 17995 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 17996 mMoveCallbacks.notifyCreated(realMoveId, extras); 17997 17998 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 17999 @Override 18000 public void onCreated(int moveId, Bundle extras) { 18001 // Ignored 18002 } 18003 18004 @Override 18005 public void onStatusChanged(int moveId, int status, long estMillis) { 18006 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 18007 } 18008 }; 18009 18010 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18011 storage.setPrimaryStorageUuid(volumeUuid, callback); 18012 return realMoveId; 18013 } 18014 18015 @Override 18016 public int getMoveStatus(int moveId) { 18017 mContext.enforceCallingOrSelfPermission( 18018 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18019 return mMoveCallbacks.mLastStatus.get(moveId); 18020 } 18021 18022 @Override 18023 public void registerMoveCallback(IPackageMoveObserver callback) { 18024 mContext.enforceCallingOrSelfPermission( 18025 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18026 mMoveCallbacks.register(callback); 18027 } 18028 18029 @Override 18030 public void unregisterMoveCallback(IPackageMoveObserver callback) { 18031 mContext.enforceCallingOrSelfPermission( 18032 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18033 mMoveCallbacks.unregister(callback); 18034 } 18035 18036 @Override 18037 public boolean setInstallLocation(int loc) { 18038 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 18039 null); 18040 if (getInstallLocation() == loc) { 18041 return true; 18042 } 18043 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 18044 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 18045 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 18046 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 18047 return true; 18048 } 18049 return false; 18050 } 18051 18052 @Override 18053 public int getInstallLocation() { 18054 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 18055 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 18056 PackageHelper.APP_INSTALL_AUTO); 18057 } 18058 18059 /** Called by UserManagerService */ 18060 void cleanUpUser(UserManagerService userManager, int userHandle) { 18061 synchronized (mPackages) { 18062 mDirtyUsers.remove(userHandle); 18063 mUserNeedsBadging.delete(userHandle); 18064 mSettings.removeUserLPw(userHandle); 18065 mPendingBroadcasts.remove(userHandle); 18066 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 18067 } 18068 synchronized (mInstallLock) { 18069 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18070 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18071 final String volumeUuid = vol.getFsUuid(); 18072 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 18073 try { 18074 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 18075 } catch (InstallerException e) { 18076 Slog.w(TAG, "Failed to remove user data", e); 18077 } 18078 } 18079 synchronized (mPackages) { 18080 removeUnusedPackagesLILPw(userManager, userHandle); 18081 } 18082 } 18083 } 18084 18085 /** 18086 * We're removing userHandle and would like to remove any downloaded packages 18087 * that are no longer in use by any other user. 18088 * @param userHandle the user being removed 18089 */ 18090 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 18091 final boolean DEBUG_CLEAN_APKS = false; 18092 int [] users = userManager.getUserIds(); 18093 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 18094 while (psit.hasNext()) { 18095 PackageSetting ps = psit.next(); 18096 if (ps.pkg == null) { 18097 continue; 18098 } 18099 final String packageName = ps.pkg.packageName; 18100 // Skip over if system app 18101 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 18102 continue; 18103 } 18104 if (DEBUG_CLEAN_APKS) { 18105 Slog.i(TAG, "Checking package " + packageName); 18106 } 18107 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 18108 if (keep) { 18109 if (DEBUG_CLEAN_APKS) { 18110 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 18111 } 18112 } else { 18113 for (int i = 0; i < users.length; i++) { 18114 if (users[i] != userHandle && ps.getInstalled(users[i])) { 18115 keep = true; 18116 if (DEBUG_CLEAN_APKS) { 18117 Slog.i(TAG, " Keeping package " + packageName + " for user " 18118 + users[i]); 18119 } 18120 break; 18121 } 18122 } 18123 } 18124 if (!keep) { 18125 if (DEBUG_CLEAN_APKS) { 18126 Slog.i(TAG, " Removing package " + packageName); 18127 } 18128 mHandler.post(new Runnable() { 18129 public void run() { 18130 deletePackageX(packageName, userHandle, 0); 18131 } //end run 18132 }); 18133 } 18134 } 18135 } 18136 18137 /** Called by UserManagerService */ 18138 void createNewUser(int userHandle) { 18139 synchronized (mInstallLock) { 18140 try { 18141 mInstaller.createUserConfig(userHandle); 18142 } catch (InstallerException e) { 18143 Slog.w(TAG, "Failed to create user config", e); 18144 } 18145 mSettings.createNewUserLI(this, mInstaller, userHandle); 18146 } 18147 synchronized (mPackages) { 18148 applyFactoryDefaultBrowserLPw(userHandle); 18149 primeDomainVerificationsLPw(userHandle); 18150 } 18151 } 18152 18153 void newUserCreated(final int userHandle) { 18154 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 18155 // If permission review for legacy apps is required, we represent 18156 // dagerous permissions for such apps as always granted runtime 18157 // permissions to keep per user flag state whether review is needed. 18158 // Hence, if a new user is added we have to propagate dangerous 18159 // permission grants for these legacy apps. 18160 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 18161 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 18162 | UPDATE_PERMISSIONS_REPLACE_ALL); 18163 } 18164 } 18165 18166 @Override 18167 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 18168 mContext.enforceCallingOrSelfPermission( 18169 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 18170 "Only package verification agents can read the verifier device identity"); 18171 18172 synchronized (mPackages) { 18173 return mSettings.getVerifierDeviceIdentityLPw(); 18174 } 18175 } 18176 18177 @Override 18178 public void setPermissionEnforced(String permission, boolean enforced) { 18179 // TODO: Now that we no longer change GID for storage, this should to away. 18180 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 18181 "setPermissionEnforced"); 18182 if (READ_EXTERNAL_STORAGE.equals(permission)) { 18183 synchronized (mPackages) { 18184 if (mSettings.mReadExternalStorageEnforced == null 18185 || mSettings.mReadExternalStorageEnforced != enforced) { 18186 mSettings.mReadExternalStorageEnforced = enforced; 18187 mSettings.writeLPr(); 18188 } 18189 } 18190 // kill any non-foreground processes so we restart them and 18191 // grant/revoke the GID. 18192 final IActivityManager am = ActivityManagerNative.getDefault(); 18193 if (am != null) { 18194 final long token = Binder.clearCallingIdentity(); 18195 try { 18196 am.killProcessesBelowForeground("setPermissionEnforcement"); 18197 } catch (RemoteException e) { 18198 } finally { 18199 Binder.restoreCallingIdentity(token); 18200 } 18201 } 18202 } else { 18203 throw new IllegalArgumentException("No selective enforcement for " + permission); 18204 } 18205 } 18206 18207 @Override 18208 @Deprecated 18209 public boolean isPermissionEnforced(String permission) { 18210 return true; 18211 } 18212 18213 @Override 18214 public boolean isStorageLow() { 18215 final long token = Binder.clearCallingIdentity(); 18216 try { 18217 final DeviceStorageMonitorInternal 18218 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 18219 if (dsm != null) { 18220 return dsm.isMemoryLow(); 18221 } else { 18222 return false; 18223 } 18224 } finally { 18225 Binder.restoreCallingIdentity(token); 18226 } 18227 } 18228 18229 @Override 18230 public IPackageInstaller getPackageInstaller() { 18231 return mInstallerService; 18232 } 18233 18234 private boolean userNeedsBadging(int userId) { 18235 int index = mUserNeedsBadging.indexOfKey(userId); 18236 if (index < 0) { 18237 final UserInfo userInfo; 18238 final long token = Binder.clearCallingIdentity(); 18239 try { 18240 userInfo = sUserManager.getUserInfo(userId); 18241 } finally { 18242 Binder.restoreCallingIdentity(token); 18243 } 18244 final boolean b; 18245 if (userInfo != null && userInfo.isManagedProfile()) { 18246 b = true; 18247 } else { 18248 b = false; 18249 } 18250 mUserNeedsBadging.put(userId, b); 18251 return b; 18252 } 18253 return mUserNeedsBadging.valueAt(index); 18254 } 18255 18256 @Override 18257 public KeySet getKeySetByAlias(String packageName, String alias) { 18258 if (packageName == null || alias == null) { 18259 return null; 18260 } 18261 synchronized(mPackages) { 18262 final PackageParser.Package pkg = mPackages.get(packageName); 18263 if (pkg == null) { 18264 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18265 throw new IllegalArgumentException("Unknown package: " + packageName); 18266 } 18267 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18268 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 18269 } 18270 } 18271 18272 @Override 18273 public KeySet getSigningKeySet(String packageName) { 18274 if (packageName == null) { 18275 return null; 18276 } 18277 synchronized(mPackages) { 18278 final PackageParser.Package pkg = mPackages.get(packageName); 18279 if (pkg == null) { 18280 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18281 throw new IllegalArgumentException("Unknown package: " + packageName); 18282 } 18283 if (pkg.applicationInfo.uid != Binder.getCallingUid() 18284 && Process.SYSTEM_UID != Binder.getCallingUid()) { 18285 throw new SecurityException("May not access signing KeySet of other apps."); 18286 } 18287 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18288 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 18289 } 18290 } 18291 18292 @Override 18293 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 18294 if (packageName == null || ks == null) { 18295 return false; 18296 } 18297 synchronized(mPackages) { 18298 final PackageParser.Package pkg = mPackages.get(packageName); 18299 if (pkg == null) { 18300 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18301 throw new IllegalArgumentException("Unknown package: " + packageName); 18302 } 18303 IBinder ksh = ks.getToken(); 18304 if (ksh instanceof KeySetHandle) { 18305 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18306 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 18307 } 18308 return false; 18309 } 18310 } 18311 18312 @Override 18313 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 18314 if (packageName == null || ks == null) { 18315 return false; 18316 } 18317 synchronized(mPackages) { 18318 final PackageParser.Package pkg = mPackages.get(packageName); 18319 if (pkg == null) { 18320 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18321 throw new IllegalArgumentException("Unknown package: " + packageName); 18322 } 18323 IBinder ksh = ks.getToken(); 18324 if (ksh instanceof KeySetHandle) { 18325 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18326 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 18327 } 18328 return false; 18329 } 18330 } 18331 18332 private void deletePackageIfUnusedLPr(final String packageName) { 18333 PackageSetting ps = mSettings.mPackages.get(packageName); 18334 if (ps == null) { 18335 return; 18336 } 18337 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 18338 // TODO Implement atomic delete if package is unused 18339 // It is currently possible that the package will be deleted even if it is installed 18340 // after this method returns. 18341 mHandler.post(new Runnable() { 18342 public void run() { 18343 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 18344 } 18345 }); 18346 } 18347 } 18348 18349 /** 18350 * Check and throw if the given before/after packages would be considered a 18351 * downgrade. 18352 */ 18353 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 18354 throws PackageManagerException { 18355 if (after.versionCode < before.mVersionCode) { 18356 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18357 "Update version code " + after.versionCode + " is older than current " 18358 + before.mVersionCode); 18359 } else if (after.versionCode == before.mVersionCode) { 18360 if (after.baseRevisionCode < before.baseRevisionCode) { 18361 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18362 "Update base revision code " + after.baseRevisionCode 18363 + " is older than current " + before.baseRevisionCode); 18364 } 18365 18366 if (!ArrayUtils.isEmpty(after.splitNames)) { 18367 for (int i = 0; i < after.splitNames.length; i++) { 18368 final String splitName = after.splitNames[i]; 18369 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 18370 if (j != -1) { 18371 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 18372 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18373 "Update split " + splitName + " revision code " 18374 + after.splitRevisionCodes[i] + " is older than current " 18375 + before.splitRevisionCodes[j]); 18376 } 18377 } 18378 } 18379 } 18380 } 18381 } 18382 18383 private static class MoveCallbacks extends Handler { 18384 private static final int MSG_CREATED = 1; 18385 private static final int MSG_STATUS_CHANGED = 2; 18386 18387 private final RemoteCallbackList<IPackageMoveObserver> 18388 mCallbacks = new RemoteCallbackList<>(); 18389 18390 private final SparseIntArray mLastStatus = new SparseIntArray(); 18391 18392 public MoveCallbacks(Looper looper) { 18393 super(looper); 18394 } 18395 18396 public void register(IPackageMoveObserver callback) { 18397 mCallbacks.register(callback); 18398 } 18399 18400 public void unregister(IPackageMoveObserver callback) { 18401 mCallbacks.unregister(callback); 18402 } 18403 18404 @Override 18405 public void handleMessage(Message msg) { 18406 final SomeArgs args = (SomeArgs) msg.obj; 18407 final int n = mCallbacks.beginBroadcast(); 18408 for (int i = 0; i < n; i++) { 18409 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 18410 try { 18411 invokeCallback(callback, msg.what, args); 18412 } catch (RemoteException ignored) { 18413 } 18414 } 18415 mCallbacks.finishBroadcast(); 18416 args.recycle(); 18417 } 18418 18419 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 18420 throws RemoteException { 18421 switch (what) { 18422 case MSG_CREATED: { 18423 callback.onCreated(args.argi1, (Bundle) args.arg2); 18424 break; 18425 } 18426 case MSG_STATUS_CHANGED: { 18427 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 18428 break; 18429 } 18430 } 18431 } 18432 18433 private void notifyCreated(int moveId, Bundle extras) { 18434 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 18435 18436 final SomeArgs args = SomeArgs.obtain(); 18437 args.argi1 = moveId; 18438 args.arg2 = extras; 18439 obtainMessage(MSG_CREATED, args).sendToTarget(); 18440 } 18441 18442 private void notifyStatusChanged(int moveId, int status) { 18443 notifyStatusChanged(moveId, status, -1); 18444 } 18445 18446 private void notifyStatusChanged(int moveId, int status, long estMillis) { 18447 Slog.v(TAG, "Move " + moveId + " status " + status); 18448 18449 final SomeArgs args = SomeArgs.obtain(); 18450 args.argi1 = moveId; 18451 args.argi2 = status; 18452 args.arg3 = estMillis; 18453 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 18454 18455 synchronized (mLastStatus) { 18456 mLastStatus.put(moveId, status); 18457 } 18458 } 18459 } 18460 18461 private final static class OnPermissionChangeListeners extends Handler { 18462 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 18463 18464 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 18465 new RemoteCallbackList<>(); 18466 18467 public OnPermissionChangeListeners(Looper looper) { 18468 super(looper); 18469 } 18470 18471 @Override 18472 public void handleMessage(Message msg) { 18473 switch (msg.what) { 18474 case MSG_ON_PERMISSIONS_CHANGED: { 18475 final int uid = msg.arg1; 18476 handleOnPermissionsChanged(uid); 18477 } break; 18478 } 18479 } 18480 18481 public void addListenerLocked(IOnPermissionsChangeListener listener) { 18482 mPermissionListeners.register(listener); 18483 18484 } 18485 18486 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 18487 mPermissionListeners.unregister(listener); 18488 } 18489 18490 public void onPermissionsChanged(int uid) { 18491 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 18492 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 18493 } 18494 } 18495 18496 private void handleOnPermissionsChanged(int uid) { 18497 final int count = mPermissionListeners.beginBroadcast(); 18498 try { 18499 for (int i = 0; i < count; i++) { 18500 IOnPermissionsChangeListener callback = mPermissionListeners 18501 .getBroadcastItem(i); 18502 try { 18503 callback.onPermissionsChanged(uid); 18504 } catch (RemoteException e) { 18505 Log.e(TAG, "Permission listener is dead", e); 18506 } 18507 } 18508 } finally { 18509 mPermissionListeners.finishBroadcast(); 18510 } 18511 } 18512 } 18513 18514 private class PackageManagerInternalImpl extends PackageManagerInternal { 18515 @Override 18516 public void setLocationPackagesProvider(PackagesProvider provider) { 18517 synchronized (mPackages) { 18518 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 18519 } 18520 } 18521 18522 @Override 18523 public void setImePackagesProvider(PackagesProvider provider) { 18524 synchronized (mPackages) { 18525 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 18526 } 18527 } 18528 18529 @Override 18530 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 18531 synchronized (mPackages) { 18532 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 18533 } 18534 } 18535 18536 @Override 18537 public void setSmsAppPackagesProvider(PackagesProvider provider) { 18538 synchronized (mPackages) { 18539 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 18540 } 18541 } 18542 18543 @Override 18544 public void setDialerAppPackagesProvider(PackagesProvider provider) { 18545 synchronized (mPackages) { 18546 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 18547 } 18548 } 18549 18550 @Override 18551 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 18552 synchronized (mPackages) { 18553 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 18554 } 18555 } 18556 18557 @Override 18558 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 18559 synchronized (mPackages) { 18560 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 18561 } 18562 } 18563 18564 @Override 18565 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 18566 synchronized (mPackages) { 18567 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 18568 packageName, userId); 18569 } 18570 } 18571 18572 @Override 18573 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 18574 synchronized (mPackages) { 18575 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 18576 packageName, userId); 18577 } 18578 } 18579 18580 @Override 18581 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 18582 synchronized (mPackages) { 18583 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 18584 packageName, userId); 18585 } 18586 } 18587 18588 @Override 18589 public void setKeepUninstalledPackages(final List<String> packageList) { 18590 Preconditions.checkNotNull(packageList); 18591 List<String> removedFromList = null; 18592 synchronized (mPackages) { 18593 if (mKeepUninstalledPackages != null) { 18594 final int packagesCount = mKeepUninstalledPackages.size(); 18595 for (int i = 0; i < packagesCount; i++) { 18596 String oldPackage = mKeepUninstalledPackages.get(i); 18597 if (packageList != null && packageList.contains(oldPackage)) { 18598 continue; 18599 } 18600 if (removedFromList == null) { 18601 removedFromList = new ArrayList<>(); 18602 } 18603 removedFromList.add(oldPackage); 18604 } 18605 } 18606 mKeepUninstalledPackages = new ArrayList<>(packageList); 18607 if (removedFromList != null) { 18608 final int removedCount = removedFromList.size(); 18609 for (int i = 0; i < removedCount; i++) { 18610 deletePackageIfUnusedLPr(removedFromList.get(i)); 18611 } 18612 } 18613 } 18614 } 18615 18616 @Override 18617 public boolean isPermissionsReviewRequired(String packageName, int userId) { 18618 synchronized (mPackages) { 18619 // If we do not support permission review, done. 18620 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 18621 return false; 18622 } 18623 18624 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 18625 if (packageSetting == null) { 18626 return false; 18627 } 18628 18629 // Permission review applies only to apps not supporting the new permission model. 18630 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 18631 return false; 18632 } 18633 18634 // Legacy apps have the permission and get user consent on launch. 18635 PermissionsState permissionsState = packageSetting.getPermissionsState(); 18636 return permissionsState.isPermissionReviewRequired(userId); 18637 } 18638 } 18639 } 18640 18641 @Override 18642 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 18643 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 18644 synchronized (mPackages) { 18645 final long identity = Binder.clearCallingIdentity(); 18646 try { 18647 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 18648 packageNames, userId); 18649 } finally { 18650 Binder.restoreCallingIdentity(identity); 18651 } 18652 } 18653 } 18654 18655 private static void enforceSystemOrPhoneCaller(String tag) { 18656 int callingUid = Binder.getCallingUid(); 18657 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 18658 throw new SecurityException( 18659 "Cannot call " + tag + " from UID " + callingUid); 18660 } 18661 } 18662 18663 boolean isHistoricalPackageUsageAvailable() { 18664 return mPackageUsage.isHistoricalPackageUsageAvailable(); 18665 } 18666} 18667